New Layout
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/RelativeLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="@+id/L1" >
<fragment
android:id="@+id/fragment_place"
android:name="com.javacodegeeks.android.fragmentstest.HomeFrag"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</FrameLayout>
<RelativeLayout
android:id="@+id/L1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true" >
<ImageView
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/home"
android:onClick="selectFrag"
android:layout_alignParentLeft="true"/>
<ImageView
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/search"
android:onClick="selectFrag"
android:layout_toRightOf="@+id/button1"/>
<ImageView
android:id="@+id/button3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/map"
android:onClick="selectFrag"
android:layout_toRightOf="@+id/button2"/>
</RelativeLayout>
</RelativeLayout>
我正在学习使用FragmentManager在ImageView点击时更改片段。当我点击第一个imageView时,主片段布局显示为“home”,效果良好。但是当我点击其他ImageView以更改片段页面时,它会更改到新的片段页面,但不会删除先前的页面。结果,先前的页面与新页面混合在一起。 这是它的样子。 屏幕截图显示带有文本“home”的主页,这是先前的页面,以及带有文本“search”的新页面。如何在单击新的ImageView时删除先前的页面?
MainActivity
public class MainActivity extends Activity {
private static final int RESULT_SETTINGS = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.demo);
}
public void selectFrag(View view) {
Fragment fr = null;
if(view == findViewById(R.id.button1)) {
fr = new HomeFrag();
}else if(view == findViewById(R.id.button2)){
fr = new SearchFrag();
}else if(view == findViewById(R.id.button3)){
fr = new MapFrag();
}
FragmentManager fm = getFragmentManager();
FragmentTransaction fragmentTransaction = fm.beginTransaction();
fragmentTransaction.replace(R.id.fragment_place, fr);
fragmentTransaction.commit();
}
}