布局:
1.使用FrameLayout当做占位
<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"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
>
<TextView
android:id="@+id/tv1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="第一个fragment"
/>
<TextView
android:id="@+id/tv2"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="第二个fragment"
/>
</LinearLayout>
<FrameLayout
android:id="@+id/fl"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</LinearLayout>
代码:
1)fragment的代码:
public class Fragment1 extends Fragment{
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view=View.inflate(getActivity(), R.layout.page, null);
TextView tv=(TextView) view.findViewById(R.id.textView1);
tv.setText("这是第一个fragment");
return view;
}
}
2)MainActivity的代码:
public class MainActivity extends FragmentActivity implements OnClickListener{
private FragmentManager manager;
private Fragment1 f1;
private Fragment2 f2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//寻找控件
TextView tv1=(TextView) findViewById(R.id.tv1);
TextView tv2=(TextView) findViewById(R.id.tv2);
f1 = new Fragment1();
f2 = new Fragment2();
manager = getSupportFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.add(R.id.fl, f1, "f1");
transaction.add(R.id.fl, f2, "f2");
//一起提交
transaction.commit();
tv1.setOnClickListener(this);
tv2.setOnClickListener(this);
changePage(R.id.tv1);
}
@Override
public void onClick(View v) {
changePage(v.getId());
}
private void changePage(int id) {
FragmentTransaction transaction = manager.beginTransaction();
switch (id) {
case R.id.tv1:
transaction.show(f1);
transaction.hide(f2);
break;
case R.id.tv2:
transaction.show(f2);
transaction.hide(f1);
break;
}
transaction.commit();
}
}