Android fragments 在页面滑动选项卡中使用相同的片段摘要:返回了错误的视图

Android fragments 在页面滑动选项卡中使用相同的片段摘要:返回了错误的视图,android-fragments,android-tabs,pagerslidingtabstrip,greenrobot-eventbus,Android Fragments,Android Tabs,Pagerslidingtabstrip,Greenrobot Eventbus,我有8个标签。由于所有选项卡都应该显示自定义列表,所以我尝试添加相同的片段实例。我正在OnEventBackGroundThread中使用EventBus下载列表,并将其添加到OnEventMainThread中的适配器。 我可以看到页面SlidingTabstrip下载所选选项卡的数据,以及所选选项卡旁边的其他两个选项卡的数据。标签标题准确无误。我可以下载每个选项卡的数据。 现在的问题是选项卡显示了错误的视图。有时是下一页签的数据,有时是上一页签的数据。 我通过了这个解决方案,但没有为我工作。

我有8个标签。由于所有选项卡都应该显示自定义列表,所以我尝试添加相同的片段实例。我正在OnEventBackGroundThread中使用EventBus下载列表,并将其添加到OnEventMainThread中的适配器。 我可以看到页面SlidingTabstrip下载所选选项卡的数据,以及所选选项卡旁边的其他两个选项卡的数据。标签标题准确无误。我可以下载每个选项卡的数据。 现在的问题是选项卡显示了错误的视图。有时是下一页签的数据,有时是上一页签的数据。 我通过了这个解决方案,但没有为我工作。

如何显示正确的视图

我们能在销毁方法中保存每个片段并重用它吗

如果我使用AsyncTask而不是EventBus实现下载任务,则选项卡将按预期工作。我在EventBus中遗漏了什么,因为我对所有这些概念都是新手。我是android新手

我正在尝试创建类似于youtube应用程序的应用程序。导航抽屉中的每个项目都将有新的片段,其中包含选项卡和每个选项卡中的项目列表

这是我的密码

TabsFragmentPageAdapter

AllCategoriesFragment.java


在观察选项卡的行为之后,这应该对您有用

@Override 
public Fragment getItem(int position) {
    if(position==0){
         return AllCategoriesFragment.getInstance(subCategoryIdList.get(position)); 
    }else{
        int index=position-1;
        return AllCategoriesFragment.getInstance(subCategoryIdList.get(index)); 
    }
}

为了避免我推荐的复杂情况,PageSlidingTastrip显然有缺陷


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

感谢卡尔顿的帮助。我以前试过这个。当我们通过滑动移动到下一个选项卡时,它会起作用。若我们通过单击选项卡名称直接在选项卡之间跳转,它将显示以前查看的选项卡。我尝试了使用Async任务而不是EventBus.OnBackgroundThread进行下载工作,并且对我来说效果很好。正如我所知,PageSlidingAbstrip下载了包括所选选项卡在内的3个选项卡的数据。如果我使用AsyncTask下载数据,它会将下载的数据附加到正确的选项卡上。但如果我使用事件总线backgroundThread下载数据,它将无法连接到正确的选项卡。
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();
        }
    }
}
@Override 
public Fragment getItem(int position) {
    if(position==0){
         return AllCategoriesFragment.getInstance(subCategoryIdList.get(position)); 
    }else{
        int index=position-1;
        return AllCategoriesFragment.getInstance(subCategoryIdList.get(index)); 
    }
}