Android的碎片(片段)Fragment

1、在activity_main.xml布局文件上,添加Fragment控件

<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"
    tools:context=".MainActivity" >
    <fragment
        android:id="@+id/frag"
        android:layout_width="fill_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:name="com.t20.fragment.FragFragment"
        />
    <!-- android:name指向对应fragment类的全路径名 -->      
</LinearLayout>

2、新建一个frag.xml布局文件,用于展示Fragment碎片需要加载的内容

<?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:background="#BED4F1"
    android:orientation="vertical" >

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="按钮" />

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="18sp"
        android:text="文本" />

</LinearLayout>

3、Fragment的类文件FragFragment.java,用来加载布局

package com.t20.fragment;

import com.t20.MainActivity;
import com.t20.R;

import android.R.integer;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
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;

public class FragFragment extends Fragment {
	
	private Button btn;
	private TextView tv;
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		//加载布局方式一
		View v1= View.inflate(getActivity(), R.layout.frag, null);
		//加载布局方式二
		View v2=inflater.inflate(R.layout.frag, container, false);
		
		//获取布局上的控件
		btn= (Button) v1.findViewById(R.id.button1);
		tv=(TextView) v1.findViewById(R.id.textView1);		
		
		return v1;
	}
}


猜你喜欢

转载自blog.csdn.net/qq15577969/article/details/80704046