能发写个代码段吗,我看看。。
好像这不叫跳转。。怎么在activity托管fragment在利用fragment呢。。。
能发写个代码段吗,我看看。。
怎么从activity跳转到fragment中,
- 写回答
- 好问题 0 提建议
- 关注问题
- 邀请回答
-
4条回答 默认 最新
- fanst_ 2015-08-04 11:03关注
Fragment是片段,和Activity不是对等的关系,可以理解是整个Activity页面的一部分,我刚开始学Android,刚写好的Fragment使用例子。其实简单讲需要四个部分:1.Activity的布局(xml)定义,里面要定义Fragment的容器 2.Fragment自身的布局定义 3.Fragment实现类 4.Activity的onCreate中,构造Fragment对象,add到对应的容器中。
关键代码如下:
Activity的onCreate():
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tab_home_page);
fm = this.getFragmentManager();
// 例子中是四个Tab页,因此用了四个不同的Fragment类
frags[0] = new MyFragment1();
frags[1] = new MyFragment2();
frags[2] = new MyFragment3();
frags[3] = new MyFragment4();;
FragmentTransaction ft = fm.beginTransaction();
ft.add(R.id.content, frags[0]); // add方法第一个参数是容器的ID,即下面xml中定义的FrameLayout
ft.add(R.id.content, frags[1]).hide(frags[1]);
ft.add(R.id.content, frags[2]).hide(frags[2]);
ft.add(R.id.content, frags[3]).hide(frags[3]);
ft.commit();Activity的layout中包含一个FrameLayout(我的是同一个区域有多个Fragment,类似Tab页效果,因此用了FrameLayout作为Fragment的容器):
注意:如果像上面用代码中new Fragment实例的方式的话,layout中不需要放Fragment节点(xml定义和代码构造Fragment对象是两种方式),仅需要定义容器节点,我下面就注释掉了
android:id="@+id/content"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1" >
<!--
android:id="@+id/fragment1"
android:name="com.example.fst.fragment.Fragment1"
android:layout_width="fill_parent"
android:layout_height="wrap_content" ><fragment android:id="@+id/fragment2" android:name="com.example.fst.fragment.Fragment2" android:layout_width="fill_parent" android:layout_height="wrap_content" > </fragment> --> </FrameLayout>
Fragment的类:
public class Fragment1 extends Fragment
{@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment1, container, false); return rootView; }
}
Fragment的layout文件:
<?xml version="1.0" encoding="utf-8"?>
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"><TextView android:id="@+id/mytv_text1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="This is MyTV" />
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决评论 打赏 举报无用 1