首先是单个fragment
activityfragment.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
android:background="@color/white"
android:weightSum="2"
android:orientation="vertical"
android:layout_height="match_parent">
<FrameLayout
android:id="@+id/con11"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1">
</FrameLayout>
<FrameLayout
android:id="@+id/con222"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1">
</FrameLayout>
</LinearLayout>
MyFragment,MytwoFragment
一定要是引入:import android.support.v4.app.Fragment;
public class MyFragment extends Fragment{
protected View contentView;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
contentView = inflater.inflate(R.layout.my_fragment, container, false);
initViews();
return contentView;
}
public void initViews(){
TextView textView =(TextView)contentView.findViewById(R.id.myte11);
textView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(getContext(),"ssss",Toast.LENGTH_SHORT).show();
}
});
}
}
Activityfragment
public class Activityfragment extends FragmentActivity {
private Fragment contentFg;
@Override
protected void onCreate(Bundle arg0) {
super.onCreate(arg0);
setContentView(R.layout.activityfragment);
switchContent();
}
public void switchContent() {
//必需继承FragmentActivity,嵌套fragment只需要这行代码
getSupportFragmentManager().beginTransaction().replace(R.id.con11, new MyFragment()).commitAllowingStateLoss();
getSupportFragmentManager().beginTransaction().replace(R.id.con222, new MytwoFragment()).commitAllowingStateLoss();
}
}
my_fragment.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:background="@color/white"
android:layout_height="match_parent">
<TextView
android:id="@+id/myte11"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:text="sssssssssssssssss"/>
</LinearLayout>