Fragment入门小案例:
实现如下功能:
1)先在Main_Activity.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/fragment1" android:layout_width="0dip" android:layout_height="match_parent" android:layout_weight="1" android:name="zjh.android.fragment.Fragment1"/> <fragment android:id="@+id/fragment2" android:layout_width="0dip" android:layout_weight="1" android:layout_height="match_parent" android:name="zjh.android.fragment.Fragment2"/>
</LinearLayout>
|
注意:fragment里的name值为类的完整路径
2)分别建立fragment1.xml和fragment2.xml文件:
fragment1.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" android:background="#ff00ff"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="fragment1"/> </LinearLayout>
|
fragment2.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" android:background="#00ffff"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="fragment2"/> </LinearLayout>
|
3)分别建立Fragment1.java和Fragment2.java两个类,并使其继承Fragment类,并覆写onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState)方法,具体代码如下:Fragment1.java
package zjh.android.fragment;
import android.annotation.SuppressLint; import android.app.Fragment; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup;
@SuppressLint("NewApi") public class Fragment1 extends Fragment {
@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment1,null); }
}
|
Fragment2.java
package zjh.android.fragment;
import android.annotation.SuppressLint; import android.app.Fragment; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup;
@SuppressLint("NewApi") public class Fragment2 extends Fragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment2,null); } }
|
注意:由于Fragment的API是在android版本11之后添加的,所以在使用时,必须确保android的最低版本为11以上,可以在AndroidMainfest.xml中修改如下代码即可:
<uses-sdk android:minSdkVersion="11" android:targetSdkVersion="18" /> |