简单的实现点击互相切换Fragment,最老的实现方式
MainActivity.java
public class MainActivity extends FragmentActivity implements OnClickListener {
private LinearLayout mFrag;
private Button mBtn,mBtn2;
private Fragment1 frag1;//声明碎片
private Fragment2 frag2;
private FragmentManager manager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
manager=getSupportFragmentManager();
initView();
hideFrag();
FragmentTransaction ft = manager.beginTransaction();//默认在首页
frag1=new Fragment1();
ft.add(R.id.mFrag, frag1);
ft.commit();
}
private void initView() {
mFrag=(LinearLayout) findViewById(R.id.mFrag);
mBtn=(Button) findViewById(R.id.mBtn);
mBtn2=(Button) findViewById(R.id.mBtn2);
mBtn.setOnClickListener(this);
mBtn2.setOnClickListener(this);
}
@Override
public void onClick(View v) {
int Id = v.getId();
hideFrag();
selectFrag(Id);
}
//隐藏所有的碎片
private void hideFrag(){
//获取事务
FragmentTransaction ft = manager.beginTransaction();
if (frag1!=null) {
ft.hide(frag1);}if (frag2!=null) {ft.hide(frag2);}ft.commit();}
private void selectFrag(int Id) {
FragmentTransaction ft = manager.beginTransaction();
switch (Id) {
case R.id.mBtn:
if (frag1!=null) {
ft.show(frag1);
}
ft.commit();
break;
case R.id.mBtn2:
if (frag2==null) {
frag2=new Fragment2();
ft.add(R.id.mFrag, frag2);
}else {
ft.show(frag2);
}
ft.commit();
break;
}
}
}
Fragment1.java
package com.example.fragemts;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class Fragment1 extends Fragment{
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// TODO Auto-generated method stub
TextView tv=new TextView(getActivity());
tv.setText("我是Fragment1");
return tv;
}
}
Fragment2.java
同上
activity_main.xml
<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.example.fragemts.MainActivity" >
<LinearLayout
android:id="@+id/Lin"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:orientation="horizontal" >
<Button
android:id="@+id/mBtn"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="Framgent1" />
<Button
android:id="@+id/mBtn2"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="Framgent2" />
</LinearLayout>
<LinearLayout
android:id="@+id/mFrag"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="@id/Lin"
android:orientation="vertical" >
</LinearLayout>
</RelativeLayout>