1

我使用PagerSlidingTabStrip 库,但这个库有问题。我有一个在页面更改时GridView从网络上更新的内容。AsyncTask我的问题是第一页是空的。当我单击选项卡 2 时会显示内容,但是如果我在选择选项卡 1 时单击选项卡 3(从选定选项卡移动到选项卡),则页面也是空的。仅当我一页一页地滑动页面或单击“下一个选项卡”(移动一个选项卡表单选定选项卡)时,它才能正常工作。

为什么页面有时是空的?

库示例应用程序可以正常工作,但它会更改创建视图。我的代码不同,因为网格视图在 AsyncTask 中通过选择的更改页面进行更新。

subCategoryActivity.java的代码:

  public class SubCategoryActivity extends SherlockFragmentActivity {
    static SubCategoryObjectsFragment f;

    private PagerSlidingTabStrip tabs;
    private ViewPager pager;
    private MyPagerAdapter pagerAdapter;
    TextView tvCustomTitle;
    static List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
    static JSONArray jsonArray;
    static String url = "http://192.168.1.2/arel/SubCat.php";
    static String url2 = "http://192.168.1.2/arel/subCatObject.php";

    private static String[][] SubCat;
    GridviewAdapter gridAdapter;
    static GridView gridViewSubCategory;
    HashMap<String, String> map;
    static ArrayList<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();
    Intent intent;

    private class getSubCategoryObjects extends AsyncTask<String, Void, String> {
        @Override
        protected String doInBackground(String... url) {
            // TODO Auto-generated method stub
            return BaseActivity.jsonParser.makeHttpRequest(url[0], "POST",
                    nameValuePairs);
        }
        @Override
        protected void onProgressUpdate(Void... values) {
            // TODO Auto-generated method stub
            super.onProgressUpdate(values);
        }
        @Override
        protected void onPostExecute(String result) {
            // TODO Auto-generated method stub
            try {
                jsonArray = new JSONArray(result);
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject jsonObjet;
                map = new HashMap<String, String>();
                try {

                    jsonObjet = jsonArray.getJSONObject(i);
                    map.put("id", String.valueOf(jsonObjet.getInt("id")));
                    map.put("title", jsonObjet.getString("title_fa"));
                    map.put("image", jsonObjet.getString("image"));
                    map.put("price", jsonObjet.getString("price"));
                    map.put("date", jsonObjet.getString("date"));

                    list.add(map);

                } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (Exception e) {
                    // TODO: handle exception
                    e.printStackTrace();
                }

            }
            gridAdapter = new GridviewAdapter(SubCategoryActivity.this, list);
            gridViewSubCategory.setAdapter(gridAdapter);

        }
    }

    private class getSubCategory extends AsyncTask<String, Void, String> {

        @Override
        protected String doInBackground(String... url) {
            // TODO Auto-generated method stub
            return BaseActivity.jsonParser.makeHttpRequest(url[0], "POST",
                    nameValuePairs);

        }

        @Override
        protected void onProgressUpdate(Void... values) {
            // TODO Auto-generated method stub
            super.onProgressUpdate(values);
        }

        @Override
        protected void onPostExecute(String result) {
            // TODO Auto-generated method stub
            try {
                jsonArray = new JSONArray(result);
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            SubCat = new String[jsonArray.length()][2];
            for (int i = 0; i < jsonArray.length(); i++) {

                JSONObject jsonObjet;

                try {

                    jsonObjet = jsonArray.getJSONObject(i);
                    SubCat[i][0] = String.valueOf(jsonObjet.getInt("id"));
                    SubCat[i][1] = jsonObjet.getString("title_fa");

                } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (Exception e) {
                    // TODO: handle exception
                    e.toString();

                }

            }

            pagerAdapter = new MyPagerAdapter(getSupportFragmentManager());

            pager.setAdapter(pagerAdapter);
//  pager.setCurrentItem(0);
        //pager.setOffscreenPageLimit(0);



            tabs.setOnPageChangeListener(new OnPageChangeListener() {

                @Override
                public void onPageSelected(int arg0) {
                    // TODO Auto-generated method stub
                    jsonArray = new JSONArray();
                    list = new ArrayList<HashMap<String, String>>();
                    nameValuePairs = new ArrayList<NameValuePair>();
                    nameValuePairs.add(new BasicNameValuePair("getAdvertise", "true"));
                    nameValuePairs.add(new BasicNameValuePair("subCatId",
                            SubCat[arg0][0]));

                    // Activity myActivity = getActivity();
                    // if (myActivity instanceof SubCategoryActivity) {
                    new getSubCategoryObjects().execute(url2);


                }

                @Override
                public void onPageScrolled(int arg0, float arg1, int arg2) {
                    // TODO Auto-generated method stub

                }

                @Override
                public void onPageScrollStateChanged(int arg0) {
                    // TODO Auto-generated method stub

                }
            });

            //jsonArray = new JSONArray();


            // final int pageMargin = (int) TypedValue.applyDimension(
            // TypedValue.COMPLEX_UNIT_DIP, 16, getResources()
            // .getDisplayMetrics());
            // pager.setPageMargin(pageMargin);

            tabs.setViewPager(pager);
            tabs.setTextSize(20);
            tabs.setTypeface(BaseActivity.font, Typeface.NORMAL);

        //  list = new ArrayList<HashMap<String, String>>();
        //  nameValuePairs = new ArrayList<NameValuePair>();
        //  nameValuePairs.add(new BasicNameValuePair("getAdvertise", "true"));
        //  nameValuePairs.add(new BasicNameValuePair("subCatId",
        //          SubCat[0][0]));

            //new getSubCategoryObjects().execute(url2);

        }
    }

    @SuppressLint("NewApi")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_list);

        intent = getIntent();

        tabs = (PagerSlidingTabStrip) findViewById(R.id.tabs);
        pager = (ViewPager) findViewById(R.id.pager);

        jsonArray = new JSONArray();
        nameValuePairs = new ArrayList<NameValuePair>();
        nameValuePairs.add(new BasicNameValuePair("getSubCategory", "true"));
        nameValuePairs.add(new BasicNameValuePair("catId", intent
                .getStringExtra("id")));

        new getSubCategory().execute(url);

        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        getSupportActionBar().setDisplayShowTitleEnabled(false);
        getSupportActionBar().setDisplayShowCustomEnabled(true);

        tvCustomTitle = new TextView(this);
        tvCustomTitle.setText(intent.getStringExtra("title"));
        LinearLayout ll = new LinearLayout(this);
        LinearLayout.LayoutParams para = new LinearLayout.LayoutParams(
                LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        para.setMargins(0, 0, 0, 0); // left,top,right, bottom
        para.gravity = Gravity.CENTER_VERTICAL;
        tvCustomTitle.setTypeface(BaseActivity.font);
        Configuration config = getResources().getConfiguration();
        if (Build.VERSION.SDK_INT >= 13) {

            if (config.smallestScreenWidthDp >= 600) {
                tvCustomTitle.setTextSize(22);
            } else {
                tvCustomTitle.setTextSize(14);
            }
        } else {
            tvCustomTitle.setTextSize(14);
        }

        tvCustomTitle.setTextColor(Color.WHITE);
        ll.addView(tvCustomTitle, para);
        getSupportActionBar().setCustomView(ll);

        changeColor(intent.getIntExtra("color", Color.parseColor("#FF666666")));


    }

    private void changeColor(int newColor) {

        tabs.setIndicatorColor(newColor);

        // change ActionBar color just if an ActionBar is available

        Drawable colorDrawable = new ColorDrawable(newColor);
        Drawable bottomDrawable = getResources().getDrawable(
                R.drawable.actionbar_bottom);
        LayerDrawable ld = new LayerDrawable(new Drawable[] { colorDrawable,
                bottomDrawable });

        getSupportActionBar().setBackgroundDrawable(ld);

    }

    /*
     * @Override protected void onSaveInstanceState(Bundle outState) {
     * super.onSaveInstanceState(outState);
     * 
     * }
     * 
     * @Override protected void onRestoreInstanceState(Bundle
     * savedInstanceState) { super.onRestoreInstanceState(savedInstanceState);
     * 
     * }
     */
    public static class MyPagerAdapter extends FragmentStatePagerAdapter  {

        public MyPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return SubCat[position][1];
        }

        @Override
        public int getCount() {
            return SubCat.length;
        }

        @Override
        public Fragment getItem(int position) {
            f = new SubCategoryObjectsFragment();
            Bundle b = new Bundle();
            b.putString(SubCategoryObjectsFragment.ARG_ID, SubCat[position][0]);
            f.setArguments(b);

            return f;
        }




    }

    public static class SubCategoryObjectsFragment extends Fragment {

        private static final String ARG_ID = "id";

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {

            View rootView = inflater.inflate(
                    R.layout.fragment_sub_category_objects, container, false);
//          gridViewSubCategory = new GridView(getActivity());

                gridViewSubCategory = (GridView) rootView.findViewById(R.id.gridViewSubCategory);

            return rootView;
        }

        @Override
        public void onActivityCreated(Bundle savedInstanceState) {
            // TODO Auto-generated method stub
            super.onActivityCreated(savedInstanceState);

            /*
             * jsonArray = new JSONArray(); list = new ArrayList<HashMap<String,
             * String>>(); nameValuePairs = new ArrayList<NameValuePair>();
             * nameValuePairs.add(new BasicNameValuePair("getAdvertise",
             * "true")); nameValuePairs.add(new BasicNameValuePair("subCatId",
             * getArguments().getString("id")));
             * 
             * 
             * Activity myActivity = getActivity(); if (myActivity instanceof
             * SubCategoryActivity) { ((SubCategoryActivity) myActivity).new
             * getSubCategoryObjects().execute(url2); }
             */
            // Implement On Item click listener
            gridViewSubCategory
                    .setOnItemClickListener(new OnItemClickListener() {
                        @Override
                        public void onItemClick(AdapterView<?> parent,
                                View view, int position, long id) {
                            // TODO Auto-generated method stub
                            BaseActivity.cd = new ConnectionDetector(
                                    getActivity());
                            BaseActivity.isInternetPresent = BaseActivity.cd
                                    .isConnectingToInternet();

                            if (BaseActivity.isInternetPresent) {

                                Intent i = new Intent(getActivity(),
                                        SubCategoryActivity.class);
                                i.putExtra("id", ((TextView) view
                                        .findViewById(R.id.textViewId))
                                        .getText().toString());
                                i.putExtra(
                                        "color",
                                        i.getIntExtra("color",
                                                Color.parseColor("#FF666666")));
                                startActivity(i);
                            } else {
                                Toast.makeText(
                                        getActivity(),
                                        "به اینترنت متصل نیستید، به اینترنت متصل شده و دوباره امتحان کنید.",
                                        Toast.LENGTH_SHORT).show();
                            }

                        }
                    });
        }

    }

    public class GridviewAdapter extends BaseAdapter {

        private Activity activity;
        private ArrayList<HashMap<String, String>> list;
        HashMap<String, String> tempMap;

        public GridviewAdapter(Activity activity,
                ArrayList<HashMap<String, String>> list) {

            this.activity = activity;
            this.list = list;
        }

        @Override
        public int getCount() {
            // TODO Auto-generated method stub
            return list.size();
        }

        public Object getItem(int position) {
            return position;
        }

        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            // TODO Auto-generated method stub

            LayoutInflater inflator = activity.getLayoutInflater();

            View vi = convertView;
            if (convertView == null)
                vi = inflator.inflate(R.layout.gridview_sub_category_row, null);

            TextView id = (TextView) vi.findViewById(R.id.textViewId);
            TextView title = (TextView) vi.findViewById(R.id.textViewTitle);
            ImageView imageViewSubCat = (ImageView) vi
                    .findViewById(R.id.imageViewSubCat);
            TextView price = (TextView) vi.findViewById(R.id.textViewPrice);
            TextView date = (TextView) vi.findViewById(R.id.textViewDate);
            RelativeLayout textBackground = (RelativeLayout) vi
                    .findViewById(R.id.relativeLayoutText);

            tempMap = new HashMap<String, String>();
            tempMap = list.get(position);

            id.setText(tempMap.get("id"));
            textBackground.setBackgroundColor(intent.getIntExtra("color",
                    Color.parseColor("#FF666666")));
            title.setText(tempMap.get("title"));
            price.setText(tempMap.get("price"));
            date.setText(tempMap.get("date"));
            title.setTypeface(BaseActivity.font);
            price.setTypeface(BaseActivity.font);
            date.setTypeface(BaseActivity.font);

            // File cachedImg = ImageLoader.getInstance().getDiscCache()
            // .get(picUrl + tempMap.get("logo") + ".jpg");

            // if (cachedImg.exists())
            // cachedImg.delete();

            ImageLoader.getInstance().displayImage(
                    BaseActivity.picUrl + tempMap.get("image") + ".jpg",
                    imageViewSubCat);

            return vi;
        }
    }

    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        // TODO Auto-generated method stub
        menu.clear();

        menu.add("آگهی جدید").setIcon(R.drawable.action_advertise_new)
                .setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);

        menu.add("غربال").setIcon(R.drawable.action_search)
                .setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);

        menu.add("مرتب سازی").setIcon(R.drawable.action_sort)
                .setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);

        return super.onPrepareOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        if (item.getItemId() == android.R.id.home) {
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

}

activity_list.xml的代码:

    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <com.astuetz.viewpager.extensions.PagerSlidingTabStrip
        android:id="@+id/tabs"
        android:layout_width="match_parent"
        android:layout_height="48dip"
        android:background="@drawable/background_tabs" />

    <android.support.v4.view.ViewPager
        android:id="@+id/pager"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/tabs"
        tools:context=".SubCategoryActivity" />

</RelativeLayout>

gridview_sub_category_row.xml的代码:

    <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="5dp" >

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="200dp" >
            <TextView
        android:id="@+id/textViewId"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:visibility="gone" />

    <ImageView
        android:id="@+id/imageViewSubCat"
        android:layout_width="match_parent"
        android:layout_height="140dp"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true" />

    <RelativeLayout
        android:id="@+id/relativeLayoutText"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@+id/imageViewSubCat"
        android:background="#FF3F9FE0" >

         <TextView
             android:id="@+id/textViewTitle"
             android:layout_width="wrap_content"
             android:layout_height="wrap_content"
             android:layout_alignParentLeft="true"
             android:layout_alignParentRight="true"
             android:layout_marginLeft="10dp"
             android:layout_marginRight="10dp"
             android:layout_marginTop="5dp"
             android:gravity="right"
             android:text="همه"
             android:textAppearance="?android:attr/textAppearanceMedium" />

         <TextView
             android:id="@+id/textViewPrice"
             android:layout_width="wrap_content"
             android:layout_height="wrap_content"
             android:layout_alignParentBottom="true"
             android:layout_alignRight="@+id/textViewTitle"
             android:layout_marginBottom="5dp"
             android:layout_toRightOf="@+id/textViewDate"
             android:gravity="right"
             android:text="20500000 تومان" />

         <TextView
             android:id="@+id/textViewDate"
             android:layout_width="wrap_content"
             android:layout_height="wrap_content"
             android:layout_alignBaseline="@+id/textViewPrice"
             android:layout_alignBottom="@+id/textViewPrice"
             android:layout_alignParentLeft="true"
             android:layout_marginLeft="14dp"
             android:text="دقایقی پیش" />

    </RelativeLayout>

    </RelativeLayout>

</RelativeLayout>

fragment_sub_category_objects.xml的代码:

    <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <GridView 
        android:id="@+id/gridViewSubCategory"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:columnWidth="300dp"
        android:horizontalSpacing="16dp"
        android:numColumns="auto_fit"
        android:scrollbars="none"
        android:verticalSpacing="16dp" >

    </GridView>
</FrameLayout>
4

3 回答 3

1

尝试:

pager.setOffscreenPageLimit(2);

其中 2 是当前页面两侧要保存在内存中的页面数量。

于 2013-08-09T13:12:12.707 回答
0

简要查看了您的代码,然后:

我没有看到使用“FragmentStatePagerAdapter”而不是正常的原因。请注意,您可以使用 support.v4 库中适配器的 vanilla 实现。

另外,我不理解静态片段“f”的使用,而不是使用数组来提供要从 pagerAdapter 中的“getItem(位置)”返回的对象引用。

对于调试,它可以帮助查看ViewPager的源代码...

向下滚动到 #800 左右,查看“populate()”和“dataSetChanged()”,并查看您使用的适配器实现的基类的源代码。

如果您有“黑色”或空白页面,则 ViewPager 会被适配器提供错误的实例,因为 VP 尝试主动管理保存在内存中以便于滚动的 3 个相邻页面(默认)。

于 2013-08-09T14:41:10.263 回答
0

当您的片段视图距离当前显示的页面超过一页时,它通常会被破坏。但是,如果您的片段已经显示,它仍然会被创建,但是当它即将显示时,您的 onCreateView() 方法将被再次调用。因此,如果您将数据存储在局部变量中,则可以检查该局部变量(您可能应该将其状态保存在 OnSaveInstanceState() 中,并将其作为 savedInstanceState 包传递给您的 onCreateView() 方法)然后重新使用缓存的内容填充您的视图。

于 2013-08-09T13:22:31.210 回答