您的位置:首页 > 移动开发 > Android开发

android 静态创建fragment

2014-04-10 11:10 609 查看
在Android 4.0后出现了fragment,fragment可以看作是activity的一部分,特别是在pad上使用更多些,如果3.0以下想使用,可以导入 这个android.support.v4   jar   这个jar有向下兼容的,现在我们写个demo演示下

静态fragment,就是在xml文件中配置,不是代码动态 生成的

首先看activity_main.xml文件:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

    xmlns:tools="http://schemas.android.com/tools"

    android:layout_width="match_parent"

    android:layout_height="match_parent"

    android:orientation="horizontal"

     >

    <fragment

        android:id="@+id/f1"

        android:layout_width="0dp"

        android:layout_height="fill_parent"

        android:layout_weight="1"

        android:name="com.example.fragment.Fragment1"

         />
<fragment

        android:id="@+id/f2"

        android:layout_width="0dp"

        android:layout_height="fill_parent"

        android:layout_weight="1"

        android:name="com.example.fragment.Fragment2"

         />

</LinearLayout>

 

再看看Fragment1.java这个类继承了v4包里的Fragment类

public class Fragment1 extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
return inflater.inflate(R.layout.item1, null);
}

}

说明:onCreateView()这个方法返回的是一个view对象,然后加入到主activity的界面中

Fragment2.java

public
class Fragment2 extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.item2, null);
}

}

看item1.xml  item2.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"

    android:background="#ffff00"

     >

<TextView 

    android:layout_width="fill_parent"

    android:layout_height="fill_parent"

    android:text="fragment-----1111111111"

    android:gravity="center"

    />

</RelativeLayout>

-----------------------------------------------------------------------------

<?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"

    android:background="#ff00ff"

     >

<TextView 

    android:layout_width="fill_parent"

    android:layout_height="fill_parent"

    android:text="fragment-----222222222222222"

    android:gravity="center"

    />

</RelativeLayout>

现在看看 fragment的依赖类 MainActivity.java

public class MainActivity extends FragmentActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}

}

注意:静态的fragment一定继承FragmentActivity


效果图如下:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: