1

我的片段相互重叠时遇到问题。我有一个 Android ActionBar 选项卡,我正在使用ActionBarSherlock. 当我选择其他选项卡时,来自的片段ListFragment被放置在我的HomeFragment. 就像它没有正确分离一样。

下面是代码HomeFragment

public class HomeFragment extends SherlockFragment
                          implements ActionBar.TabListener {

    private View homeView;

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

    @Override
    public void onTabSelected(Tab tab, FragmentTransaction ft) {
        ft.add(android.R.id.content, this,"apple");
        ft.attach(this);
    }

    @Override
    public void onTabUnselected(Tab tab, FragmentTransaction ft) {}

    @Override
    public void onTabReselected(Tab tab, FragmentTransaction ft) {}

}

代码HerbFragment

public class HerbsFragment extends SherlockListFragment 
                           implements ActionBar.TabListener {

    /** An array of items to display in ArrayList */
    String apple_versions[] = new String[]{
            "Pancreas",
            "Blood"
    };

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, 
                                                  Bundle savedInstanceState) {
        /** Creating array adapter to set data in listview */
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(
            getActivity().getBaseContext(), 
            android.R.layout.simple_list_item_1, 
            apple_versions);

        /** Setting the array adapter to the listview */
        setListAdapter(adapter);
        View v = inflater.inflate(R.layout.activity_main, container, false);
        return super.onCreateView(inflater, container, savedInstanceState);
    }

    @Override
    public void onStart() {
        super.onStart();
        /** Setting the multiselect choice mode for the listview */
        getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
    }

    @Override
    public void onTabSelected(Tab tab, FragmentTransaction ft) {
        ft.add(android.R.id.content, this,"apple");
        ft.attach(this);
    }

    @Override
    public void onTabUnselected(Tab tab, FragmentTransaction ft) {
        ft.detach(this);
    }

    @Override
    public void onTabReselected(Tab tab, FragmentTransaction ft) {}

}
4

1 回答 1

1

我认为 HerbFragment 中的代码放错了位置,因为您应该处理具有选项卡的活动/片段中的选项卡内容,而不是在选项卡中。您可以通过两种不同的方式在 HomeFragment 中处理它:

-当用户单击选项卡时,替换当前片段:只需将其更改为 a ft.replace(并删除该ft.attach行):

ft.add(android.R.id.content, this,"apple");
ft.attach(this);

- 附加新片段并分离前一个片段:如果您知道它是哪个片段,只需从附加片段中获取引用,并以与附加新片段相同的方法分离它。

于 2013-04-17T09:13:59.453 回答