我的片段彼此重叠有问题。我有一个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) {}
}
答案 0 :(得分:1)
我认为HerbFragment中的代码是拼写错误的,因为您应该处理包含选项卡的activity / fragment中的选项卡内容,而不是在选项卡中。您可以通过两种不同的方式在HomeFragment中处理它:
- 当用户点击标签时,替换当前片段:只需更改ft.replace
(并删除ft.attach
行):
ft.add(android.R.id.content, this,"apple");
ft.attach(this);
- 连接新的片段并分离前一个片段:如果您知道它是哪个片段,只需从附加的片段中获取一个引用,并使用您附加新片段的相同方法将其分离。