下面四个步骤就能创建一个简单的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>
时间: 2024-11-25 12:25:38