我使用下面的代码来实现 tabhost :
public class MyActivity extends FragmentActivity {
private FragmentTabHost mTabHost = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mylayout);
mTabHost = (FragmentTabHost) findViewById(R.id.tabHost);
mTabHost.setup(this, getSupportFragmentManager(), android.R.id.tabcontent);
mTabHost.addTab(mTabHost.newTabSpec("A").setIndicator("A"), AFragment.class, null);
mTabHost.addTab(mTabHost.newTabSpec("B").setIndicator("B"), BFragment.class, null);
}
}
它包含2个标签, AFragment.class 如下:
public class AFragment extends Fragment {
private MyAdapter MyAdapter;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_folder_base, container, false);
ListView ListV = (ListView)view.findViewById(R.id.listview);
FolderList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//How to implement to launnch another fragmentC under the same tab
}
});
...
MyAdapter = new MyAdapter(this.getActivity(), this.getContext());
ListV.setAdapter(MyAdapter);
return view;
}
}
我想在点击项目时启动另一个片段(FragmentC),我该如何实现它?
如何在这些片段中实现onBackPressed()
函数?
答案 0 :(得分:0)
答:要在FragmentB中添加FragmentC,请将其放入FragmentB:
getActivity().getChildrenFragmentManager()
.beginTransaction()
.replace(R.id.fragmentCcontainer, new FragmentC)
.commit();
其中R.id.fragmentCcontainer是放置在其他fragmentB视图之上的空视图的id /它是一个片段持有者:
fragment_b.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!--Put FragmentB's Views Here-->
<FrameLayout
android:id="@+id/fragmentCcontainer"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</RelativeLayout>
B:片段中没有onBackPressed()方法。在您的情况下,您应该覆盖activity的onBackPressed()方法并实现切换到其中的上一个选项卡;