Adroid中Fragment的简单使用
下面四个步骤就能创建一个简单的fragment
1. 扩展Fragment class
2. 在XML 或 Java中提供显示
3. 覆盖onCreateView方法
4. 在activity中使用Fragment
如下就是简单的显例
创建一个FirstActivityFragment.java文件,扩展Fragment class
packagecom.example.liang.login;importandroid.content.Context;importandroid.os.Bundle;importandroid.support.v4.app.Fragment;importandroid.support.v4.view.VelocityTrackerCompat;importandroid.view.LayoutInflater;importandroid.view.View;importandroid.view.ViewGroup;importandroid.widget.TextView;importandroid.widget.Toast;/***Createdbyliangon2016/7/15.*/publicclassFirstActivityFragmentextendsFragment{publicFirstActivityFragment(){}@OverridepublicViewonCreateView(LayoutInflaterinflater,ViewGroupcontainer,BundlesavedInstanceState){Viewv=inflater.inflate(R.layout.fragment_first,container,false);TextViewtextView=(TextView)v.findViewById(R.id.showFirstFragmentInfo);finalContextcontext=this.getActivity();textView.setOnClickListener(newView.OnClickListener(){@OverridepublicvoidonClick(Viewv){Toasthello;hello=Toast.makeText(context,"hello",Toast.LENGTH_LONG);hello.show();}});returnv;}@OverridepublicvoidonCreate(BundlesavedInstanceState){super.onCreate(savedInstanceState);}}
为Fragment创建一个xmlfragment_first.xml
<?xmlversion="1.0"encoding="utf-8"?><LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"android:orientation="vertical"android:layout_width="match_parent"android:layout_height="match_parent"><TextViewandroid:layout_width="match_parent"android:layout_height="match_parent"android:id="@+id/showFirstFragmentInfo"android:text="thisisafirstFragment"/></LinearLayout>
并在一个activity view 中使用
<?xmlversion="1.0"encoding="utf-8"?><LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="match_parent"android:layout_height="match_parent"android:orientation="vertical"android:background="#33FF00"><fragmentxmlns:android="http://schemas.android.com/apk/res/android"xmlns:tools="http://schemas.android.com/tools"android:id="@+id/fragment"android:name="com.example.liang.login.FirstActivityFragment"tools:layout="@layout/fragment_first"android:layout_width="match_parent"android:layout_height="wrap_content"/></LinearLayout>
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。