在导航抽屉片段之间切换后无法在片段内添加 ListView 项目

Cannot add ListView Items inside Fragment after switching between Navigation Drawer Fragments

编辑: 我的滑动标签片段 ATabs 似乎有问题。 不使用 ATabs 片段,只使用导航抽屉在片段 A1 和 B 之间切换,一切正常!添加 ListItems 是可能的。编辑 MainActivity:

@Override
public void onNavigationDrawerItemSelected(int position) {
    mFragment = null;
    switch (position) {
        case 0:
            mFragment = A1.newInstance(position + 1, this);
            break;
        case 1:
            mFragment = B.newInstance(position + 1);
            break;
    }
    onSectionAttached(position);
    FragmentManager fragmentManager = getSupportFragmentManager();
    fragmentManager.beginTransaction()
            .replace(R.id.container, mFragment)
            .commit();

    mFragment = null;
}

但是一旦我使用 ATabs 片段(参见下面的 MainActivity)并切换到它并返回,不再可能添加 ListItems。虽然 Logcat 每次我按添加 (+) 时显示 Log.v(LOG_TAG, "Added Item");

我不知道是什么导致了这个问题。如果 ATabs 需要是 Activity 而不是 Fragment,或者我的 PagerAdapter 导致了问题。 在我的 ATabs class 中尝试使用两个不同的 PagerAdapters:

public static class MyAdapter extends FragmentStatePagerAdapter {
 ...
}

public static class MyAdapter extends FragmentPagerAdapter {
 ...
}

后者甚至导致整个片段无法正常显示,也无法在选项卡之间切换。


我有一个导航抽屉,显示两个不同的片段 ATabs 和 B。 Fragment ATabs 包含两个滑动标签。每个选项卡都包含另一个片段 A1 和 A2。到目前为止,A2 和 B 只是带有简单 TextView 的空片段,因此 A2 = B 基本相同。当应用程序启动时,片段 A1 有一个 ListView 和一些预定义的 EditText 项目。用户可以通过在该特定片段 (A1) 的 "custom" 操作栏内按下添加来添加其他 EditText 项目。

一般而言,片段 A1 应具有与片段 A2 和 B 不同的操作栏项目。这似乎已经奏效了。为此,我向每个片段添加了 set setHasOptionsMenu(true);,覆盖 onCreateOptionsMenu 方法,包括 menu.clear() 并从资源中设置所需的菜单。

这已经是我的第一个问题:是否有必要在所有使用默认主要 activity 操作栏的片段中执行此操作?

我的主要问题是向列表视图中添加其他项目:

当我在初始片段 A1(应用程序启动时显示)与片段 A2 之间切换并返回到 ATabs 片段内的 A1 时,一切正常。我可以添加其他项目,之前添加的项目也仍然可见。 但是一旦我使用导航抽屉在片段 B 和 A1 之间切换,我就无法再添加任何项目,也看不到我之前添加的项目。 稍后我将使用数据库来存储我的项目,但应该仍然可以像以前一样添加其他项目。

这里有一些屏幕可以更好地展示我的问题:

App以A1片段开始,在A1和A2之间切换,可以通过+item添加

我使用导航抽屉在 ATabs 和 B 之间切换后,显示了添加项 (+),但对片段 A1 没有影响。

这是我的 MainActivity,其中包含导航抽屉: 我不太确定 onNavigationDrawerItemSelected 片段之间的切换是否正确,或者我是否每次切换都创建新片段。是Android删除了之前的片段还是多次切换后内存溢出?而我的"first"A1片段还是"hidden behind"新建的吗? 我是 Android 的新手,我真的不明白为什么我在导航抽屉片段之间切换后无法添加任何项目。

public class MainActivity extends ActionBarActivity
        implements NavigationDrawerFragment.NavigationDrawerCallbacks, A1.OnFragmentInteractionListener, A2.OnFragmentInteractionListener, B.OnFragmentInteractionListener {

    private NavigationDrawerFragment mNavigationDrawerFragment;

    private CharSequence mTitle;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mNavigationDrawerFragment = (NavigationDrawerFragment)
                getSupportFragmentManager().findFragmentById(R.id.navigation_drawer);
        mTitle = getTitle();

        // Set up the drawer.
        mNavigationDrawerFragment.setUp(
                R.id.navigation_drawer,
                (DrawerLayout) findViewById(R.id.drawer_layout));
    }

    @Override
    public void onNavigationDrawerItemSelected(int position) {
        // update the main content by replacing fragments
        Fragment fragment = null;
        switch (position) {
            case 0:
                fragment = ATabs.newInstance(position + 1, this);
                break;
            case 1:
                fragment = B.newInstance(position + 1);
                break;
        }
        onSectionAttached(position);
        FragmentManager fragmentManager = getSupportFragmentManager();
        fragmentManager.beginTransaction()
                .replace(R.id.container, fragment)
                .commit();

    }

    public void onSectionAttached(int number) {
        switch (number+1) {
            case 1:
                mTitle = getString(R.string.title_ATabs);
                break;
            case 2:
                mTitle = getString(R.string.title_B);
                break;
        }
    }

    public void restoreActionBar() {
        ActionBar actionBar = getSupportActionBar();
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
        actionBar.setDisplayShowTitleEnabled(true);
        actionBar.setTitle(mTitle);
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        if (!mNavigationDrawerFragment.isDrawerOpen()) {
            // Only show items in the action bar relevant to this screen
            // if the drawer is not showing. Otherwise, let the drawer
            // decide what to show in the action bar.
            getMenuInflater().inflate(R.menu.main, menu);
            restoreActionBar();
            return true;
        }
        return super.onCreateOptionsMenu(menu);

    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onFragmentInteraction(Uri uri) {

    }

}

带有滑动标签的片段 ATabs:

public class ATabs extends Fragment {

    static final String LOG_TAG = "ATabs";
    private static final String ARG_PARAM1 = "param1";
    private static Context mContext;

    private SlidingTabLayout mSlidingTabLayout;

    private ViewPager mViewPager;


    public static ATabs newInstance(int sectionNumber, Context context) {
        ATabs fragment = new ATabs();
        mContext = context;
        Bundle args = new Bundle();
        args.putInt(ARG_PARAM1, sectionNumber);
        fragment.setArguments(args);
        return fragment;
    }

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

        setHasOptionsMenu(true);
    }


    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        menu.clear();
        super.onCreateOptionsMenu(menu, inflater);
        inflater.inflate(R.menu.main, menu);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_atabs, container, false);

    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        mViewPager = (ViewPager) view.findViewById(R.id.viewpager);
        mViewPager.setAdapter(new MyAdapter(getFragmentManager()));


        mSlidingTabLayout = (SlidingTabLayout) view.findViewById(R.id.sliding_tabs);
        mSlidingTabLayout.setViewPager(mViewPager);
    }



    public static class MyAdapter extends FragmentStatePagerAdapter {
        public MyAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public int getCount() {
            return 2;
        }

        @Override
        public Fragment getItem(int position) {
            Fragment fragment = null;
            switch (position) {
                case 0:
                    fragment = A1.newInstance(position, mContext);
                    break;
                case 1:
                    fragment = A2.newInstance(position);
                    break;
            }
            return fragment;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            CharSequence pageTitle = "NOT SET";
            switch (position) {
                case 0:
                    pageTitle = "A1 Tab";
                    break;
                case 1:
                    pageTitle = "A2 Tab";
                    break;
            }
            return pageTitle;
        }
    }
}

如前所述:是否有必要在使用默认主要 activity 操作栏的片段中调用 setHasOptionsMenu(true) 并覆盖 onCreateOptionsMenu()

这里是 Fragment A2(与 class B 相同)使用默认的主要 activity 操作栏:

public class A2 extends Fragment {
    private static final String ARG_PARAM1 = "param1";
    private String mParam1;

    private OnFragmentInteractionListener mListener;

    public static A2 newInstance(int sectionNumber) {
        A2 fragment = new A2();
        Bundle args = new Bundle();
        args.putInt(ARG_PARAM1, sectionNumber);
        fragment.setArguments(args);
        return fragment;
    }

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

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
        }

        setHasOptionsMenu(true);
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        menu.clear();
        super.onCreateOptionsMenu(menu, inflater);
        inflater.inflate(R.menu.main, menu);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_a2, container, false);
    }

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

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        public void onFragmentInteraction(Uri uri);
    }

}

Fragment A1 使用自己的 a1 操作栏菜单: 附加添加项。

public class A1 extends Fragment {
    private static final String ARG_PARAM1 = "param1";
    private final String LOG_TAG = A1.class.getSimpleName();
    private ArrayAdapter<String> mForecastAdapter;
    private static Context mContext = null;

    private ListView myList;
    private MyAdapter myAdapter;
    private String mParam1;
    private OnFragmentInteractionListener mListener;

    public static A1 newInstance(int sectionNumber, Context context) {
        A1 fragment = new A1();
        mContext = context;
        Bundle args = new Bundle();
        args.putInt(ARG_PARAM1, sectionNumber);
        fragment.setArguments(args);
        return fragment;
    }

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

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
        }

        setHasOptionsMenu(true);
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);
        menu.clear();
        inflater.inflate(R.menu.a1, menu);
    }

    public ArrayList myItems = new ArrayList();

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // handle item selection
        switch (item.getItemId()) {
            case R.id.action_add_item:
                ListItem listItem = new ListItem();
                listItem.caption = "Added Item";
                myItems.add(listItem);
                Log.v(LOG_TAG, "Added Item");
                myAdapter.notifyDataSetChanged();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    public class MyAdapter extends BaseAdapter {
        private LayoutInflater mInflater;


        public MyAdapter() {
            mInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

            for (int i = 0; i < 3; i++) {
                ListItem listItem = new ListItem();
                listItem.caption = "Caption" + i;
                myItems.add(listItem);
            }

            notifyDataSetChanged();
        }

        public int getCount() {
            return myItems.size();
        }

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

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

        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder;
            if (convertView == null) {
                holder = new ViewHolder();
                convertView = mInflater.inflate(R.layout.list_item_a1, null);
                holder.caption = (EditText) convertView
                        .findViewById(R.id.list_item_a1_edit_text);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            //Fill EditText with the value you have in data source
            ListItem item = (ListItem) myItems.get(position);
            holder.caption.setText(item.caption);
            holder.caption.setId(position);

            //we need to update adapter once we finish with editing
            holder.caption.setOnFocusChangeListener(new View.OnFocusChangeListener() {
                public void onFocusChange(View v, boolean hasFocus) {
                    if (!hasFocus){
                        final int position = v.getId();
                        final EditText Caption = (EditText) v;
                        ListItem item = (ListItem) myItems.get(position);
                        item.caption = Caption.getText().toString();
                    }
                }
            });

            return convertView;
        }
    }

    class ViewHolder {
        EditText caption;
    }

    class ListItem {
        String caption;
    }

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

        View rootView = inflater.inflate(R.layout.fragment_a1, container, false);

        // Get a reference to the ListView, and attach this adapter to it.
        myList = (ListView) rootView.findViewById(R.id.listview_a1);
        myList.setItemsCanFocus(true);
        myAdapter = new MyAdapter();
        myList.setAdapter(myAdapter);

        return rootView;
    }

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

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    public interface OnFragmentInteractionListener {
        public void onFragmentInteraction(Uri uri);
    }
}

最后是操作栏菜单: 主要:

<menu 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" tools:context=".MainActivity">

    <item
        android:id="@+id/action_example"
        android:title="@string/action_example"
        app:showAsAction="never" />

    <item
        android:id="@+id/action_settings"
        android:title="@string/action_settings"
        android:orderInCategory="100"
        app:showAsAction="never" />


    <item
        android:id="@+id/action_help"
        android:title="@string/action_help"
        android:orderInCategory="100"
        app:showAsAction="never" />

</menu>

a1:

<menu 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" tools:context=".MainActivity">

    <item
        android:id="@+id/action_add_item"
        android:title="@string/action_add_item"
        android:icon="@drawable/ic_action_new"
        app:showAsAction="always" />

    <item
        android:id="@+id/action_example"
        android:title="@string/action_example"
        app:showAsAction="never" />

    <item
        android:id="@+id/action_settings"
        android:title="@string/action_settings"
        android:orderInCategory="100"
        app:showAsAction="never" />

    <item
        android:id="@+id/action_help"
        android:title="@string/action_help"
        android:orderInCategory="100"
        app:showAsAction="never" />

</menu>

如果需要任何其他代码来解决我的问题,请告诉我。

感谢@Luksprog,使用getChildFragmentManager()解决了主要问题 而不是 ATabs 中的 FragmentManager()