当前位置: 首页 > 知识库问答 >
问题:

在PagesLidingTabStrip中的选项卡上使用相同的片段:返回错误的视图

曹和正
2023-03-14

我有8个标签。由于所有选项卡都应该显示自定义列表,所以我试图添加相同的片段实例。我正在使用OnEventBackGroundThread中的EventBus下载列表,并将其添加到OnEventMainThread中的adapter中。
我可以看到PageSlidingTabStrip下载选定选项卡的数据以及其他两个选项卡(在选定选项卡旁边)的数据。标签标题是准确的。我可以下载每个标签的数据。现在的问题是标签显示错误的视图。有时是下一个选项卡的数据,有时是上一个选定选项卡的数据。我经历了这个解决方案,但对我不起作用。PagerslidingTabStrip:如何在运行时刷新当前选项卡中的内部片段Listview并停止为下一个选项卡加载数据。

public class TabsFragmentPagerAdapter extends FragmentStatePagerAdapter {
    private ArrayList<String> tabTitles = new ArrayList<String>(); //  Contains name of the tab
    private ArrayList<Integer> subCategoryIdList = new ArrayList<Integer>(); // Contains its id
    private ArrayList<CategoryModel> categoryModelArrayList = new ArrayList<CategoryModel>();
    private int categoryId;

    public TabsFragmentPagerAdapter(FragmentManager fm, int cid) {
        super(fm);
        this.categoryId = cid;
        categoryModelArrayList = TabsFragment.subCategoriesHashMap.get(cid); // Gets prepopulated data from other class.
        for(CategoryModel c: categoryModelArrayList) {
            tabTitles.add(c.getName()); 
            subCategoryIdList.add(c.getCategoryId()); 
        }
    }

    @Override
    public int getCount() {
        return tabTitles.size();
    }

    @Override
    public Fragment getItem(int position) {
        return AllCategoriesFragment.getInstance(subCategoryIdList.get(position)); 
// Using same Fragment. Position is used as a parameter(Using Id's instead of position which is populated in Constructor)
    }

    @Override
    public CharSequence getPageTitle(int position) {
        // Generate title based on item position
        return tabTitles.get(position);
    }

    @Override
    public void destroyItem(ViewGroup container,int position, Object object ) {
        Log.d("Destroy","Destroying tab# "+position);
        FragmentManager manager = ((Fragment) object).getFragmentManager();
        FragmentTransaction trans = manager.beginTransaction();
        trans.remove((Fragment) object);
        trans.commit();

        super.destroyItem(container, position, object);
        container.removeView(container.getRootView());
    }
}
package com.android.thetake;

// import statements

public class AllCategoriesFragment extends Fragment implements AbsListView.OnItemClickListener, AbsListView.OnScrollListener {

    private View view;

    private OnFragmentInteractionListener mListener;

    /**
     * The fragment's ListView/GridView.
     */
    private AbsListView mListView;

    /**
     * The Adapter which will be used to populate the ListView/GridView with
     * Views.
     */
    private ListAdapter mAdapter;

    private CustomListAdapter customListAdapter;

    MessageListEvent msgEvent = new MessageListEvent();

    private static int categoryId=0;

    private static int startIndex=1;

    private Activity mActivity;

    static List<Item> newItemList= new LinkedList<Item>();

    static AllCategoriesFragment allCategoriesFragment;

    static EventBus eventBus;

    public static final String CATEGORY_ID = "CATEGORY_ID";


    /**
     * Mandatory empty constructor for the fragment manager to instantiate the
     * fragment (e.g. upon screen orientation changes).
     */
    public AllCategoriesFragment() {
        startIndex = 1;
        newItemList.clear();
    }


    public static AllCategoriesFragment getInstance(int categoryId) {
         Bundle args = new Bundle();
        args.putInt(CATEGORY_ID,categoryId); 
        allCategoriesFragment = new AllCategoriesFragment();
        allCategoriesFragment.msgEvent.itemList.clear();
        allCategoriesFragment.newItemList.clear();
        startIndex=1;
        allCategoriesFragment.setArguments(args);
        return allCategoriesFragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        customListAdapter = null;
        view = inflater.inflate(R.layout.fragment_item, container, false);
        allCategoriesFragment.categoryId = getArguments().getInt(CATEGORY_ID);
        eventBus = EventBus.getDefault();
        if (!eventBus.isRegistered(this))
            eventBus.register(this);   //Register this class to eventBus

        eventBus.post(new StartDownloadEvent()); // publish event

        return view;
    }

    public void onEventBackgroundThread(StartDownloadEvent event) {
        //Downloading the images in background thread
        HttpClient httpClient = new DefaultHttpClient();
        HttpContext localContext = new BasicHttpContext();
        String url = "https://company.com/listProducts?categoryId="+allCategoriesFragment.categoryId+"&start="+AllCategoriesFragment.startIndex+"&limit=20";

        HttpGet httpGet = new HttpGet(url);
        String results = null;

        boolean flag = msgEvent.itemList.size()==0;

        try {
            HttpResponse response = httpClient.execute(httpGet, localContext);
            HttpEntity entity = response.getEntity();
            results = msgEvent.getASCIIContentFromEntity(entity);
            if (results != null) {
                JSONArray jsonArray = new JSONArray(results);
                for (int i = 0; i < jsonArray.length(); i++) {

                        JSONObject obj = jsonArray.getJSONObject(i);
                        String product_id = obj.getString("product_id");
                        String actorImageLink = obj.getString("500pxCropLink");
                        String actorName=new String();
                        try {
                            actorName = obj.getString("actorName");
                        } catch (JSONException e) {
                            Log.d("Exception",e.getLocalizedMessage());
                        }
                        String largePicLink = obj.getString("500pxCropLink");
                        String smallPicLink = obj.getString("125pxLink");
                        String movieName = obj.getString("movieName");
                        String itemName = obj.getString("name");
                        String brand = obj.getString("brand");
                        String price = obj.getString("price");
                        boolean isMatchVerified = obj.getBoolean("verified");
                        Item item = new Item(product_id, actorImageLink, largePicLink, smallPicLink, movieName, itemName, brand, actorName, price, isMatchVerified);
                        if(flag) {
                        msgEvent.itemList.add(item);
                        } else
                            newItemList.add(item);

                }
            }
        } catch(IOException e) {
             Log.d("Exception",e.getLocalizedMessage());
        }
        catch (JSONException e) {
            Log.d("Exception",e.getLocalizedMessage());
        }
        if(!flag) {
            FragmentActivity f = getActivity();
                f.runOnUiThread(new Runnable() {

                    @Override
                    public void run() {
                        customListAdapter.addAll(newItemList);
                        customListAdapter.notifyDataSetChanged();
                    }
                });
        }
        EventBus.getDefault().post(msgEvent);
    }

    public void onEventMainThread(MessageListEvent event) {
        //Create Adapter
        //Set Adapter to List View
        customListAdapter = new CustomListAdapter(getActivity(),event.itemList);
        mListView = (ListView) view.findViewById(android.R.id.list);
        mListView.setAdapter(customListAdapter);
        mListView.setOnItemClickListener(this);
        // This loads the next images when scrolled all the way down to bottom.
        // Overrides onScroll and onScrollStateChanged function
        mListView.setOnScrollListener(this);
    }

    @Override
    public void onScroll(AbsListView view, int firstVisibleItem,
                         int visibleItemCount, int totalItemCount) {
        int loaded = firstVisibleItem+visibleItemCount;
        if(loaded>=totalItemCount && startIndex+19==loaded) {
            startIndex = loaded+1;
            newItemList.clear();
            Log.d("Scroll","Next Start Index "+startIndex);
            eventBus.post(new StartDownloadEvent());
        }
    }

    @Override
    public void onScrollStateChanged(AbsListView view, int scrollState) {
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        mActivity = activity;
        try {
            mListener = (OnFragmentInteractionListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                    + " must implement OnFragmentInteractionListener");
        }


    }

    @Override
    public void onDetach() {
        super.onDetach();
        EventBus.getDefault().unregister(this);
        mListener = null;
    }


    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        if (null != mListener) {
            // Notify the active callbacks interface (the activity, if the
            // fragment is attached to one) that an item has been selected.
            mListener.onFragmentInteraction(msgEvent.itemList.get(position).movieName);
        }

    }

    /**
     * The default content for this Fragment has a TextView that is shown when
     * the list is empty. If you would like to change the text, call this method
     * to supply the text it should use.
     */
    public void setEmptyText(CharSequence emptyText) {
        View emptyView = mListView.getEmptyView();

        if (emptyText instanceof TextView) {
            ((TextView) emptyView).setText(emptyText);
        }
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p/>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        public void onFragmentInteraction(String id);
    }

    public static class StartDownloadEvent {

    }

    public class MessageListEvent {
        public List<Item> itemList = new ArrayList<Item>();
        protected String getASCIIContentFromEntity(HttpEntity entity) throws IllegalStateException, IOException {
            ...
            return out.toString();
        }
    }
}

共有1个答案

寿和通
2023-03-14

PageSlidingTabStrip显然有缺陷,为了避免复杂,我推荐Android PagerSlidingTabStrip(默认材质设计)

实现非常相似。然而,这也将为您提供更好的自定义选项

 类似资料:
  • 我已经实现了ActionBarsherlock的示例com.actionBarsherlock.sample.fragments,所有这些都工作得很好,直到当所选选项卡有子片段时设备方向发生变化。 一切都好: 一切都很好,可以旋转设备没有问题。现在,如果我在Fragment2中选择一个列表项来推入Fragment2Child1,在我旋转设备之前,一切都是好的。 设备旋转时不良: tab1->Fra

  • 我有带Tablayout的基本ViewPager2,每个页面都有不同的片段。当我需要打开此视图而不是从第一个(默认)选项卡时,我会这样做: 这段代码选择了选项卡,但里面是从第一个选项卡打开的片段!只有当我点击选择选项卡时,我才能在每个选项卡中看到正确的片段。我还尝试使用如下Tablayout进行选择: 但是这段代码没有帮助,也可以处理这个bug。此外,我还尝试设置了查看页面。带有后/后延迟的cur

  • 我在sencha touch 2中创建了一个索引页面,在其中我在容器内创建了一些自定义按钮 这些按钮看起来像这个 单击橙色按钮后,我想显示一个新视图。 我尝试了ext.Navigation view,但它不是我想要的。我必须在按钮上添加一个事件监听器,还是我必须做一些其他事情请建议 我在controller文件夹main.js中创建了一个新控制器 还有我的新视图Eligibelity.js代码 还

  • 我想更改片段选项卡的大小。有什么办法吗??我们可以更改使用视图寻呼机和片段创建的片段选项卡的大小??

  • 我正在使用ViewPager Tablayout显示5个选项卡,当选择这些选项卡时,将从服务器获取数据以显示。所获取的数据的唯一区别是所选的选项卡。所以有5个片段做同样的事情是多余的。因此,我实现了使用一个片段,如下所示。 活动 片断 我怎样才能消除问题的点击选项卡混为一谈,我猜是由于双重调用开始片段。

  • 我试图在片段中创建自定义listView,我搜索了其他问题,但找不到任何东西。我的列表适配器是这样的 我的片段类是这样的: } 问题是这部分:CustomList adapter=新CustomList(tab1.this,string,imageId);构造函数(public CustomList(活动上下文,字符串[]web,整数[]imageId))只接受活动 我怎样才能解决这个问题?