I have a few fragment which need to show after check RadioButton. How to realize add/replace fragment if I didn't know which fragment was previosly? And How to do default show fragment?
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
If I understood you correctly,
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();
}
});
}
}
Fragment1:
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>