我有需要检查单选后显示几个片段。 如何实现添加/替换片段,如果我不知道哪个片段previosly? 怎么办展默认片段?
Answer 1:
如果我理解正确的话,
MainActivity:
public class MainActivity extends FragmentActivity {
FragmentTransaction ft;
Fragment1 frg1;
Fragment2 frg2;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
frg1 = new Fragment1();
frg2 = new Fragment2();
RadioButton btn1 = (RadioButton) findViewById(R.id.radio1);
btn1.setChecked(true);
getSupportFragmentManager().beginTransaction().add(R.id.frame, frg1).commit();
// set listener
((RadioGroup) findViewById(R.id.radio_group)).setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
ft = getSupportFragmentManager().beginTransaction();
switch (checkedId) {
case R.id.radio1:
ft.replace(R.id.frame, frg1);
break;
case R.id.radio2:
ft.replace(R.id.frame, frg2);
break;
}
ft.commit();
}
});
}
}
片段1:
public class Fragment1 extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
container.removeAllViews();
return inflater.inflate(R.layout.fragment1, null);
}
}
Fragment2:
public class Fragment2 extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
container.removeAllViews();
return inflater.inflate(R.layout.fragment2, null);
}
}
activity_main:
<RadioGroup
android:id="@+id/radio_group"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<RadioButton
android:id="@+id/radio1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="fragment1" />
<RadioButton
android:id="@+id/radio2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="fragment2" />
</RadioGroup>
<FrameLayout
android:id="@+id/frame"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</FrameLayout>
fragment1.xml:
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="Fragment1" >
</TextView>
fragment2.xml:
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="Fragment2" >
</TextView>
文章来源: Change a fragment