通过容器方式添加 fragment的删除

来源:互联网 发布:网络销售话术流程 编辑:程序博客网 时间:2024/06/07 06:13
<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"    android:gravity="center"    tools:context="${relativePackage}.${activityClass}" >    <Button         android:id="@+id/btnMain"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="@string/btnmain"/>        <Button         android:id="@+id/btn2"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="@string/btnmain"        android:layout_below="@id/btnMain"        android:onClick="btn2_click"/>           <TextView        android:id="@+id/tvcenter"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="@string/hello_world"        android:layout_centerHorizontal="true"         android:layout_below="@id/btn2"/>         <FrameLayout     android:id="@+id/ly1"    android:layout_width="wrap_content"    android:layout_height="wrap_content"    android:layout_centerHorizontal="true"    android:layout_below="@id/tvcenter"    /><FrameLayout     android:id="@+id/ly2"    android:layout_width="wrap_content"    android:layout_height="wrap_content"    android:layout_centerHorizontal="true"    android:layout_below="@id/ly1" /></RelativeLayout>


package com.pipashu.todolist;import android.os.Bundle;import android.support.v4.app.Fragment;import android.support.v4.app.FragmentActivity;import android.support.v4.app.FragmentManager;import android.support.v4.app.FragmentTransaction;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;public class MainActivity extends FragmentActivity {FragmentManager fm;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);fm=getSupportFragmentManager();Button btn=(Button)findViewById(R.id.btnMain);btn.setOnClickListener(new OnClickListener(){@Overridepublic void onClick(View v) {// TODO Auto-generated method stub//增FragmentTransaction fts= fm.beginTransaction();fts.add(R.id.ly1,new Fragment1());fts.commit();}});}public void btn2_click(View v){//删FragmentTransaction fts= fm.beginTransaction();Fragment fratemp=fm.findFragmentById(R.id.ly1); //通过查找容器的id来找到该fratempfts.remove(fratemp);fts.commit();}}


0 0