您好,登錄后才能下訂單哦!
下面四個步驟就能創建一個簡單的fragment
1. 擴展Fragment class
2. 在XML 或 Java中提供顯示
3. 覆蓋onCreateView方法
4. 在activity中使用Fragment
如下就是簡單的顯例
創建一個FirstActivityFragment.java文件,擴展Fragment class
package com.example.liang.login; import android.content.Context; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.view.VelocityTrackerCompat; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import android.widget.Toast; /** * Created by liang on 2016/7/15. */ public class FirstActivityFragment extends Fragment { public FirstActivityFragment(){ } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){ View v = inflater.inflate(R.layout.fragment_first, container, false); TextView textView = (TextView)v.findViewById(R.id.showFirstFragmentInfo); final Context context = this.getActivity(); textView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast hello; hello = Toast.makeText(context,"hello",Toast.LENGTH_LONG); hello.show(); } }); return v; } @Override public void onCreate( Bundle savedInstanceState) { super.onCreate(savedInstanceState); } }
為Fragment創建一個xml fragment_first.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <TextView android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/showFirstFragmentInfo" android:text="this is a firstFragment"/> </LinearLayout>
并在一個activity view 中使用
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:background="#33FF00"> <fragment xmlns: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>
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。