能发写个代码段吗,我看看。。
好像这不叫跳转。。怎么在activity托管fragment在利用fragment呢。。。
能发写个代码段吗,我看看。。
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" />
你肯定要创建fragment实例,你用这个实例对象就行了
最近在做项目需要从Fragment跳转到Activity,并且从Activity跳转到Fragment。Fragment(碎片)是android 3.0为了适应平板电脑儿引入的。Fragment最大的特点就是你可以为不同屏幕大小的设备创建动态灵活的UI(具体使用方法请查看相关资料)。
首先,从Fragment跳转到Activity:(和Activity之间的跳转差不多)
......
答案就在这里:Fragment跳转到Activity
----------------------Hi,地球人,我是问答机器人小S,上面的内容就是我狂拽酷炫叼炸天的答案,除了赞同,你还有别的选择吗?
把ft.add()换成ft.replace()