在主UI界面中定义一个用来替代的布局(站位)
定义4个按钮具体布局如下:
<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"
tools:context="com.itloi.praceicr.MainActivity" >
<LinearLayout
android:orientation="vertical"
android:id="@+id/ll_replaced"
android:layout_width="match_parent"
android:layout_height="match_parent"
></LinearLayout>
<LinearLayout
android:layout_alignParentBottom="true"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
>
<Button
android:id="@+id/btn_wx"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:text="微信"
/>
<Button
android:id="@+id/btn_contast"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:text="联系人"
/>
<Button
android:id="@+id/btn_discover"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:text="发现"
/>
<Button
android:id="@+id/btn_me"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:text="我"
/>
</LinearLayout>
</RelativeLayout>
点击按钮后加载一个fragment;
注意commit不能多次提交,只能提交一次.
package com.itloi.praceicr;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
@SuppressLint("CommitTransaction") public class MainActivity extends Activity implements OnClickListener {
private Button btn_wx;
private Button btn_contast;
private Button btn_discover;
private Button btn_me;
private LinearLayout ll_replaced;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ll_replaced = (LinearLayout) findViewById(R.id.ll_replaced);
btn_wx = (Button) findViewById(R.id.btn_wx);
btn_contast = (Button) findViewById(R.id.btn_contast);
btn_discover = (Button) findViewById(R.id.btn_discover);
btn_me = (Button) findViewById(R.id.btn_me);
btn_wx.setOnClickListener(this);
btn_contast.setOnClickListener(this);
btn_discover.setOnClickListener(this);
btn_me.setOnClickListener(this);
}
@Override
public void onClick(View v) {
FragmentManager manager = getFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
switch (v.getId()) {
case R.id.btn_wx:
transaction.replace(R.id.ll_replaced, new WxFragment());
break;
case R.id.btn_contast:
transaction.replace(R.id.ll_replaced, new ContastFragment());
break;
case R.id.btn_discover:
transaction.replace(R.id.ll_replaced, new DiscoverFragment());
break;
case R.id.btn_me:
transaction.replace(R.id.ll_replaced, new MeFragment());
break;
}
transaction.commit();
}
}