FragmentManager replace()似乎在RecyclerView中复制卡片

时间:2015-06-26 19:57:40

标签: android android-recyclerview fragmentmanager

我很想发布堆栈溢出和android编程,所以请原谅我所犯的任何错误。

在我的主要活动中,我有一个导航抽屉,其中使用onNavigationDrawerItemSelected函数,并显示其中的代码:

    public void onNavigationDrawerItemSelected(int position) {
    // update the main content by replacing fragments
    Fragment myFragment = null;
    switch(position)
    {
        case 0:
            myFragment = new HomeFragment();
            break;
        case 1:
            //myFragment = new TestFragment();
            break;
        case 2:
            // TODO: Add more
            break;

    }
    if(myFragment!=null)
    {
        getFragmentManager().beginTransaction()
                .replace(R.id.nav_contentframe, myFragment)
                .commit();
    }
}

应该注意的是,当我尝试选择要求HomeFragment的按钮时,应用程序会添加卡片,而不是替换它。以下代码是HomeFragment.java

package tk.easthigh.witsmobile;

import android.app.FragmentManager;
import android.content.Context;
import android.os.Bundle;
import android.app.Fragment;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

public class HomeFragment extends Fragment {

    SimpleRecyclerAdapter adapter;

    public HomeFragment() {
        // Required empty public constructor
    }

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

        final View view = inflater.inflate(R.layout.fragment_home, container, false);

        RecyclerView recyclerView = (RecyclerView) view.findViewById(R.id.home_recyclerview);

        final Context context = getActivity().getApplicationContext();

        recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(new LinearLayoutManager(context));
        recyclerView.setItemAnimator(new DefaultItemAnimator());

        if (adapter == null) {
            adapter = new SimpleRecyclerAdapter(context);
            recyclerView.setAdapter(adapter);
        }

        adapter.SetOnItemClickListener(new SimpleRecyclerAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
               switch (position) {
                case 0:
                    Toast.makeText(getActivity().getBaseContext(), "Hi!", Toast.LENGTH_SHORT).show();
                    break;
                case 1:
                    break;
                case 2:
                    break;

                default:
                    Toast.makeText(getActivity().getBaseContext(), "Undefined Click!", Toast.LENGTH_SHORT).show();
                }
            }
        });
        // Inflate the layout for this fragment
        return view;
    }
}

对SimpleAdapter的引用是位于此github的代码。 这是activity_main.xml,其中包含ID为“nav_contentframe”的FrameLayout:

<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/nav_drawer"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true">

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <include layout="@layout/toolbar" />

    <FrameLayout
        android:id="@+id/nav_contentframe"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginTop="?attr/actionBarSize"
        android:background="@android:color/background_light">

    </FrameLayout>

</RelativeLayout>

<android.support.design.widget.NavigationView
    android:id="@+id/nav_view"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:layout_gravity="start"
    android:fitsSystemWindows="true"
    app:headerLayout="@layout/drawer_header"
    app:menu="@menu/drawer" />

这是fragment_home.xml:

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" tools:context="tk.easthigh.witsmobile.HomeFragment">

<android.support.v7.widget.RecyclerView
    android:id="@+id/home_recyclerview"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:clipToPadding="false" />

我能够确定,从FragmentManager调用replace方法似乎会在HomeFragment的RecyclerView中添加所有卡片的副本。

例如,RecyclerView有4张卡。但是,按下导航抽屉上应该替换内容的按钮,而不是复制卡片,留下8张卡片作为最终产品。再按一次会产生12张卡,依此类推。当然,这不是预期的情况,但谷歌在几个小时后,并试图调试,我无法弄清楚是什么问题。

1 个答案:

答案 0 :(得分:1)

正如我在评论中所述,SimpleRecyclerAdapter引用了两个静态列表:

public static List<String> homeActivitiesList = new ArrayList<String>();
public static List<String> homeActivitiesSubList = new ArrayList<String>();

这些将用于 SimpleRecyclerAdapter的每个参考。最重要的是,每次创建SimpleRecyclerAdapter对象时都会填充它们,这显然发生在这里。

我不知道开发人员为什么选择这样做。如果出于效率原因,那么在SimpleRecyclerAdapter的构造函数中,您需要进行检查以防止在创建列表后填充列表。像这样:

        public static List<String> homeActivitiesList = null;
        public static List<String> homeActivitiesSubList = null;
        Context context;
        OnItemClickListener clickListener;

        public SimpleRecyclerAdapter(Context context) {
            isHomeList = true;
            this.context = context;
            setHomeActivitiesList(context);
        }

        public void setHomeActivitiesList(Context context) {
            if (homeActivitiesList == null) {
              homeActivitiesList = new ArrayList<String>();
              homeActivitiesSubList = new ArrayList<String();
              String[] listArray = context.getResources().getStringArray(R.array.home_activities);
              String[] subTitleArray = context.getResources().getStringArray(R.array.home_activities_subtitle);
              for (int i = 0; i < listArray.length; ++i) {
                homeActivitiesList.add(listArray[i]);
                homeActivitiesSubList.add(subTitleArray[i]);
              }
           }
        }

另一件事是确保每次更换时都不会创建新的片段。因此,在您的主活动中,您可以保留对HomeFragment的引用,并使用它而不是像这样创建一个新的:

HomeFragment mHomeFragment = null

public void onNavigationDrawerItemSelected(int position) {
    // update the main content by replacing fragments
    Fragment myFragment = null;
    switch(position)
    {
        case 0:
            if (mHomeFragment == null) {
                mHomeFragment = new HomeFragment();
            }
            myFragment = mHomeFragment;
            break;
        case 1:
            //myFragment = new TestFragment();
            break;
        case 2:
            // TODO: Add more
            break;

    }
    if(myFragment!=null)
    {
        getFragmentManager().beginTransaction()
                .replace(R.id.nav_contentframe, myFragment)
                .commit();
    }
}

这样,只要内存中存在MainActivity,就可以确保最后一个HomeFragment的所有内容都保留在内存中。