Android之Fragment动态添加和移除Fragment

fragment_demo.xml

<?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" >
    
	<TextView 
	    android:id="@+id/tv_text"
	    android:layout_width="wrap_content"
	    android:layout_height="wrap_content"
	    android:text="你好,欢迎你"/>
</LinearLayout>

MyFragment

package com.example.test27;

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


public class MyFragment extends Fragment{
	private TextView text;
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view=inflater.inflate(R.layout.fragment_demo, null);
		return view;
	}
	
	@Override
	public void onViewCreated(View view, Bundle savedInstanceState) {
		text=(TextView) view.findViewById(R.id.tv_text);
	}
}
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" >

   <FrameLayout 
       android:id="@+id/layout"
       android:layout_width="match_parent"
       android:layout_height="wrap_content">
       
   </FrameLayout>
   <Button 
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:onClick="btn"/>
   <Button 
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:onClick="btnRemove"/>

</LinearLayout>

MainActivity.java


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

   <FrameLayout 
       android:id="@+id/layout"
       android:layout_width="match_parent"
       android:layout_height="wrap_content">
       
   </FrameLayout>
   <Button 
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:onClick="btn"/>
   <Button 
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:onClick="btnRemove"/>

</LinearLayout>

猜你喜欢

转载自blog.csdn.net/qq_38922435/article/details/80861064