Fragment 碎片 (上)

1.Fragment  产生

        为了让界面可以在平板上更好地展示,Android在3.0版本引入了Fragment(碎片)功能,它非常类似于Activity,可以像Activity一样包含布局。主要目的是应用在大屏幕设备上,比如平板电脑,支持更加动态和灵活的UI设计,而且其屏幕比手机的大的很多可以放更多的UI组件,这些组件之间有更多的交互。
Fragment 在我们的应用中应该是一个模块化和可重用的组件,因为  Fragment  定义了自己的布局,以及通过自己的生命周期回调方法定义了自己的行为可以将Fragment 包含到多个Activity中。

2.Fragment  生命周期

Fragment依存于Activity,因此Activity的生命周期会直接影响到Fragment的生命周期。
他们之间关系如下图
可以看到Fragment比Activity多了几个额外的生命周期回调方法:

onAttach(Activity)  当Fragment与Activity发生关联时调用。

onCreateView(LayoutInflater, ViewGroup,Bundle) //Fragment第一次绘制他的用户界面时候回调用此方法,为了绘制Fragment的UI,必须返回            一个view ,如果不显示UI则返回null。

onActivityCreated(Bundle) //当Activity的onCreate方法返回时调用

onDestoryView()//与onCreateView想对应,当该Fragment的视图被移除时调用

onDetach() //onAttach相对应,当Fragment与Activity关联被取消时调用


注意:除了onCreateView,其他的所有方法如果你重写了,必须调用父类对于该方法的实现。

3.Fragment  的特点

(1)Fragment 可以作为Activity 的一部分出现
(2)一个Activity中可以出现一个 Fragment 也可以出现多个,一个Fragment 可以出现在一个Activity 中也可以出现在多个Activity中。
(3)在Activity运行中可以添加 、移除、替换Fragment 。
(4)Fragment 可以相应自己的事件,有自己的生命周期,但是要受到Activity的生命周期的影响。
(5)Fragment  有自己的不久文件。
(6) Fragment  的加载有静态的和动态的。

4.Fragment  静态加载

在Activity的layout 文件中声明 Fragment ,需要注意的是<Fragment >中的 android:name= 属性 指定了在layout 中实例化的Fragment 类。
标示 Fragment 的方法:
android: id   提供一个唯一的ID
android:tag 提供一个唯一的字符串

下面以具体代码为例
在一个Activity中放两个 Fragment   activity_main2.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="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

   
    <fragment
        <strong>android:id="@+id/fragment"    //id 一定要写 否则会报错</strong>
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        <strong>android:name="com.example.fragment.myFragment" /> // 是具体的类名</strong>
    <fragment
        android:id="@+id/fragment2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:name="com.example.fragment.myFragment2" />

</LinearLayout>
MainActivity2.java中代码
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity2 extends Activity implements OnClickListener{
private Button button ,but11;
private TextView textView ,tv11;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main2);
		button=(Button) findViewById(R.id.but);
		textView=(TextView) findViewById(R.id.tv);		
		button.setOnClickListener(this);
		but11=(Button) findViewById(R.id.but11);
		but11.setOnClickListener(this);
		tv11=(TextView) findViewById(R.id.tv11);
	}
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch(v.getId()){
		case R.id.but:
			   textView.setText("ltg");
			break;
		case R.id.but11:
			tv11.setText("ltg");
			break;
		}
	}
}
fragment.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="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

   
    <TextView 
        android:id="@+id/tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="" />
    <Button 
        android:id="@+id/but"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="chang" />

</LinearLayout>
对应的java代码  myFragment.java 
import android.annotation.TargetApi;
import android.app.Fragment;
import android.os.Build;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public class myFragment extends Fragment {

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		// inflater.inflate(resource, root, attachToRoot);
		// resource 是Fragment要加载的布局文件
		// root 加载Fragment的父ViewGroup
		// attachToRoot :false 不返回父ViewGroup
		View view = inflater.inflate(R.layout.fragment, container, false);
		TextView textView = (TextView) view.findViewById(R.id.tv);
		textView.setText("静态加载Fragment");
		return view;
	}
}
第二个Fragment的    fragment2xml  代码为
<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="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <TextView 
        android:id="@+id/tv11"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="" />
    <Button 
        android:id="@+id/but11"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="点击" />

</LinearLayout>
对应java代码
import android.annotation.TargetApi;
import android.app.Fragment;
import android.os.Build;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

@TargetApi(Build.VERSION_CODES.HONEYCOMB) public class myFragment2 extends Fragment{

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		//inflater.inflate(resource, root, attachToRoot);
		//resource 是Fragment要加载的布局文件
		//root 加载Fragment的父ViewGroup
		//attachToRoot :false  不返回父ViewGroup
		 View view=inflater.inflate(R.layout.fragment2, container, false);
		 TextView textView=(TextView) view.findViewById(R.id.tv11);
		 textView.setText("电子科技大学");
		return view;
	}
}
注意的是两个fragment.xml 中的控件的id不要一样 否则就会造成混乱。
运行的结果如下图


5.Fragment  动态加载

inflate()方法的三个参数:
  第一个是resource ID,指明了当前的Fragment对应的资源文件;
  第二个参数是父容器控件;
  第三个布尔值参数表明是否连接该布局和其父容器控件,在这里的情况设置为false,因为系统已经插入了这个布局到父控件,设置为true将会产生多余的一个View Group。
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="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        

        <Button
            android:id="@+id/but2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="动态加载"
            android:textSize="15sp" />

        <Button
            android:id="@+id/but3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="动态加载1"
            android:textSize="15sp" />

       
    </LinearLayout>

       <strong><LinearLayout       </strong>
        android:id="@+id/<strong>frag</strong>"
        android:orientation="vertical"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        >
        </LinearLayout>

</LinearLayout>
下过如如


后面加载的fragement 就会在 布局文件中 linearlayout 中显示;

java 代码如下
import android.os.Build;
import android.os.Bundle;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.view.View;
import android.widget.Button;

@TargetApi(Build.VERSION_CODES.HONEYCOMB)
@SuppressLint("NewApi")
public class MainActivity extends Activity implements
		android.view.View.OnClickListener {
	private Button  but2, but3;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		but2 = (Button) findViewById(R.id.but2);
		but3 = (Button) findViewById(R.id.but3);
		but1.setOnClickListener(this);
		but2.setOnClickListener(this);
		but3.setOnClickListener(this);
		but4.setOnClickListener(this);
	}

	@TargetApi(Build.VERSION_CODES.HONEYCOMB)
	@SuppressLint("NewApi")
	@Override
	public void onClick(View arg0) {
		// TODO Auto-generated method stub
		switch (arg0.getId()) {
		case R.id.but2:
			myFragment2 m = new myFragment2();
			FragmentManager f = getFragmentManager();
			FragmentTransaction fragmentTransaction = f.beginTransaction();
			fragmentTransaction.replace(R.id.<strong>frag</strong>, m);
			fragmentTransaction.addToBackStack(null);
			fragmentTransaction.commit();

			break;
		case R.id.but3:

			myFragment m1 = new myFragment();
			FragmentManager f1 = getFragmentManager();
			FragmentTransaction fragmentTransaction1 = f1.beginTransaction();
			fragmentTransaction1.replace(R.id.<strong>frag</strong>, m1);
			fragmentTransaction1.addToBackStack(null);
			fragmentTransaction1.commit();
			break;
		}
	}

}
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="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <TextView 
        android:id="@+id/tv11"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="" />
    <Button 
        android:id="@+id/but11"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="点击" />

</LinearLayout>
对应java中代码为 
    
import android.annotation.TargetApi;
import android.app.Fragment;
import android.os.Build;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;

@TargetApi(Build.VERSION_CODES.HONEYCOMB) public class myFragment2 extends Fragment {
	TextView textView;
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		//inflater.inflate(resource, root, attachToRoot);
		//resource 是Fragment要加载的布局文件
		//root 加载Fragment的父ViewGroup
		//attachToRoot :false  不返回父ViewGroup
		 View view=<strong>inflater.inflate(R.layout.fragment2, container, false);</strong>
		  textView=(TextView) view.findViewById(R.id.tv11);
		 textView.setText("电子科技大学");
		 Button button=(Button) view.findViewById(R.id.but11);
		 button.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				textView.setText("你好");
			}
		});
		return view;
	}
}

fragment1.xml中的代码和上面的fragment.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="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

   
    <TextView 
        android:id="@+id/tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="" />
    <Button 
        android:id="@+id/but"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="chang" />

</LinearLayout>

对应的java代码 这里面没加点击事件所以点击按键没反应 

import android.annotation.TargetApi;
import android.app.Fragment;
import android.os.Build;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public class myFragment extends Fragment {

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		// inflater.inflate(resource, root, attachToRoot);
		// resource 是Fragment要加载的布局文件
		// root 加载Fragment的父ViewGroup
		// attachToRoot :false 不返回父ViewGroup
		View view = inflater.inflate(R.layout.fragment, container, false);
		TextView textView = (TextView) view.findViewById(R.id.tv);
		textView.setText("静态加载Fragment");
		return view;
	}
}

6.Fragment  常用的API

Fragment常用的三个类:

android.app.Fragment 主要用于定义Fragment

android.app.FragmentManager 主要用于在Activity中操作Fragment

android.app.FragmentTransaction 保证一些列Fragment操作的原子性,熟悉事务这个词,一定能明白~

a、获取FragmentManage的方式:

getFragmentManager() // v4中,getSupportFragmentManager

b、主要的操作都是FragmentTransaction的方法

FragmentTransaction transaction = fm.benginTransatcion();//开启一个事务

transaction.add() 

往Activity中添加一个Fragment

transaction.remove()

从Activity中移除一个Fragment,如果被移除的Fragment没有添加到回退栈(回退栈后面会详细说),这个Fragment实例将会被销毁。

transaction.replace()

使用另一个Fragment替换当前的,实际上就是remove()然后add()的合体~

transaction.hide()

隐藏当前的Fragment,仅仅是设为不可见,并不会销毁

transaction.show()

显示之前隐藏的Fragment

detach()

会将view从UI中移除,和remove()不同,此时fragment的状态依然由FragmentManager维护。

attach()

重建view视图,附加到UI上并显示。

transatcion.commit()//提交一个事务

注意:常用Fragment的哥们,可能会经常遇到这样Activity状态不一致:State loss这样的错误。主要是因为:commit方法一定要在Activity.onSaveInstance()之前调用。

上述,基本是操作Fragment的所有的方式了,在一个事务开启到提交可以进行多个的添加、移除、替换等操作。

值得注意的是:如果你喜欢使用Fragment,一定要清楚这些方法,哪个会销毁视图,哪个会销毁实例,哪个仅仅只是隐藏,这样才能更好的使用它们。

a、比如:我在FragmentA中的EditText填了一些数据,当切换到FragmentB时,如果希望会到A还能看到数据,则适合你的就是hide和show;也就是说,希望保留用户操作的面板,你可以使用hide和show,当然了不要使劲在那new实例,进行下非null判断。

b、再比如:我不希望保留用户操作,你可以使用remove(),然后add();或者使用replace()这个和remove,add是相同的效果。

c、remove和detach有一点细微的区别,在不考虑回退栈的情况下,remove会销毁整个Fragment实例,而detach则只是销毁其视图结构,实例并不会被销毁。那么二者怎么取舍使用呢?如果你的当前Activity一直存在,那么在不希望保留用户操作的时候,你可以优先使用detach。











  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值