Fragment的简单使用

极客导航  2018-09-18 19:36  阅读 88 次 评论 1 条


多用几次就熟悉了。以防止忘记,因此附上代码于此。(图片来自Android官网)

零、Fragment生命周期

一、布局

<RelativeLayout 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" >

    <TextView
        android:id="@+id/main_tv_message"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:gravity="center"
        android:text="@string/hello_world"
        android:textColor="@android:color/black"
        android:textSize="30sp" />

    <LinearLayout
        android:id="@+id/main_layout"
        android:layout_width="match_parent"
        android:layout_height="80dp"
        android:layout_alignParentBottom="true"
        android:orientation="horizontal" >

        <Button
            android:id="@+id/main_bt_first"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:text="First Fragment" />

        <Button
            android:id="@+id/main_bt_second"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:text="Second Fragment" />
    </LinearLayout>

    <FrameLayout
        android:id="@+id/main_content"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_above="@id/main_layout"
        android:layout_below="@id/main_tv_message"
        android:background="@android:color/darker_gray" >
    </FrameLayout>

</RelativeLayout>

二、FirstFragment.java

public class FirstFragment extends Fragment {

	private String TAG = "fragment";

	@Override
	public void onAttach(Activity activity) {
		// TODO Auto-generated method stub
		super.onAttach(activity);
		Log.d(TAG, "--FirstFragment------onAttach---------");
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		Log.d(TAG, "--FirstFragment------onCreate---------");
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		Log.d(TAG, "--FirstFragment------onCreateView---------");
		View view = inflater.inflate(R.layout.activity_first, null);
		return view;
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		Log.d(TAG, "--FirstFragment------onActivityCreated---------");
		super.onActivityCreated(savedInstanceState);
	}

	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		Log.d(TAG, "--FirstFragment------onResume---------");
		super.onResume();
	}

	@Override
	public void onPause() {
		// TODO Auto-generated method stub
		Log.d(TAG, "--FirstFragment------onPause---------");
		super.onPause();
	}

	@Override
	public void onStart() {
		// TODO Auto-generated method stub
		Log.d(TAG, "--FirstFragment------onStart---------");
		super.onStart();
	}

	@Override
	public void onDestroyView() {
		// TODO Auto-generated method stub
		Log.d(TAG, "--FirstFragment------onDestroyView---------");
		super.onDestroyView();
	}

	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		Log.d(TAG, "--FirstFragment------onDestroy---------");
		super.onDestroy();
	}

	@Override
	public void onDetach() {
		// TODO Auto-generated method stub
		Log.d(TAG, "--FirstFragment------onDetach---------");
		super.onDetach();
	}
}

SecondFragment.java省略

三、MainActivity.java

public class MainActivity extends Activity implements OnClickListener {

	private String TAG = "fragment";
	private Fragment currentFragment = null;
	private FirstFragment firstFragment = null;
	private SecondFragment secondFragment = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		findViewById(R.id.main_bt_first).setOnClickListener(this);
		findViewById(R.id.main_bt_second).setOnClickListener(this);

		firstFragment = new FirstFragment();
		secondFragment = new SecondFragment();

		setFragment(firstFragment);
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		Log.d(TAG, "------------onClick-------------");
		switch (v.getId()) {
		case R.id.main_bt_first:
			setFragment(currentFragment, firstFragment);
			break;
		case R.id.main_bt_second:
			setFragment(currentFragment, secondFragment);
			break;
		default:
			break;
		}

	}

	/**
	 * 方法一,这种每次都添加替换,效率低
	 * 
	 * @param fragment
	 */
	private void setFragment(Fragment fragment) {
		if (null == fragment) {
			return;
		}
		// 如果相同就没必要更新了
		if (currentFragment == fragment) {
			return;
		}
		currentFragment = fragment;
		// 每次都需要重新初始化
		FragmentTransaction mFragmentTransaction = getFragmentManager()
				.beginTransaction();
		mFragmentTransaction.replace(R.id.main_content, fragment);
		mFragmentTransaction.commitAllowingStateLoss(); //

		return;
	}

	/**
	 * 方法二
	 * 
	 * @param from
	 * @param to
	 */
	private void setFragment(Fragment from, Fragment to) {
                if(null==from || null== to ){
                     return ;
                 }
		// 判断是否相同,如果是就不需要更新
		if (from == to) {
			return;
		}
		currentFragment = to;
		// 每次都需要重新初始化
		FragmentTransaction mFragmentTransaction = getFragmentManager()
				.beginTransaction();
		// 判断是否已经添加过,如果没有就先添加,在显示
		if (!to.isAdded()) {
			mFragmentTransaction.hide(from).add(R.id.main_content, to).commit();
		} else {
			mFragmentTransaction.hide(from).show(to).commit();
		}
		return;
	}
}

历史上的今天:

本文地址: https://www.125la.com/647.html
关注我们:请关注一下我们站长微信:扫描二维码125啦读书导航的微信号,微信号:yudemi(十三少)
版权声明:本文为原创或转载文章,版权归原作者所有,欢迎分享本文,转载请保留出处!
第一个读书导航

发表评论


表情

  1. 125啦读书导航
    125啦读书导航 【农民】 @回复

    MainActivity.java中需要增加null判断了
    /**
    * 方法二
    *
    * @param from
    * @param to
    */
    private void setFragment(Fragment from, Fragment to) {
    if(null==from || null== to ){
    return ;
    }
    // 判断是否相同,如果是就不需要更新
    if (from == to) {
    return;
    }
    currentFragment = to;
    // 每次都需要重新初始化
    FragmentTransaction mFragmentTransaction = getFragmentManager()
    .beginTransaction();
    // 判断是否已经添加过,如果没有就先添加,在显示
    if (!to.isAdded()) {
    mFragmentTransaction.hide(from).add(R.id.main_content, to).commit();
    } else {
    mFragmentTransaction.hide(from).show(to).commit();
    }
    return;
    }