0

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

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

public static class MyAdapter extends FragmentStatePagerAdapter {
 ...
}

public static class MyAdapter extends FragmentPagerAdapter {
 ...
}

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


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

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

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

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

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

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

App以A1片段开头,在A1和A2之间切换,可以用+项目添加

ATabs 片段

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

导航抽屉,碎片 B,无法添加

这是包含导航抽屉的 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) {

    }

}

带有滑动标签的片段 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;
        }
    }
}

如前所述:是否有必要调用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);
    }

}

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

最后是操作栏菜单: main:

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

一:

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

请让我知道是否需要任何其他代码来解决我的问题。

4

1 回答 1

1

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

于 2015-03-12T21:51:47.577 回答