在导航抽屉碎片之间切换后,无法在Fragment中添加ListView项

时间:2015-03-05 01:15:42

标签: android listview android-actionbar navigation-drawer pagerslidingtabstrip

编辑: 我的滑动标签片段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就不再可能了。虽然每次按下add(+),Logcat都会显示Log.v(LOG_TAG, "Added Item");

我不知道导致问题的原因。如果ATabs需要是一个Activity而不是Fragment,或者我的PagerAdapter导致问题。 在我的ATabs课程中尝试使用两个不同的PagerAdapters:

public static class MyAdapter extends FragmentStatePagerAdapter {
 ...
}

public static class MyAdapter extends FragmentPagerAdapter {
 ...
}

后者甚至导致整个碎片无法正确显示,并且标签之间的切换也不可能。


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

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

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

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

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

以下是一些可以更好地展示我的问题的屏幕:

App以A1片段开始,在A1和A2之间切换,可以使用+ item

添加

ATabs fragment

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

nav drawer, frag B, not able to add

这是我的MainActivity,它包含导航抽屉: 我不确定片段之间的onNavigationDrawerItemSelected内部切换是否正确,或者每次切换时是否创建新片段。 Android是否删除了以前的片段,或者是多次切换后导致内存溢出?而我的第一个" A1片段仍然隐藏在"新创造的? 我对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) {

    }

}

使用滑动标签对片段进行打击:

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;
        }
    }
}

正如已经问到的:是否有必要在使用默认主要活动操作栏的片段内调用setHasOptionsMenu(true)并覆盖onCreateOptionsMenu()

这是使用默认主要活动操作栏的片段A2(与B类相同):

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);
    }

}

片段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>

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

1 个答案:

答案 0 :(得分:1)

感谢@Luksprog,使用getChildFragmentManager()解决了主要问题 在ATabs中代替FragmentManager()