使用带有片段的单选按钮实现选项卡功能
我使用 tabhost ... regular tabs 获得了此功能。
- 如图所示,是否可以使用 Fragments 来获得它
如果有怎么办?
- 一个例子会很有帮助
我使用 tabhost ... regular tabs 获得了此功能。
如果有怎么办?
尝试如下:
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// radiobutton to change Fragment
RadioButton tab1 = (RadioButton) findViewById(R.id.radioFemale);
RadioButton tab2 = (RadioButton) findViewById(R.id.radioMale);
RadioGroup tab_group = (RadioGroup) findViewById(R.id.radioSex);
// radioGroupListener
tab_group.setOnCheckedChangeListener(new OnCheckedChangeListener() {
public void onCheckedChanged(RadioGroup group, int checkedId) {
switch (checkedId) {
case R.id.radioFemale:
FragmentManager fm = getFragmentManager();
FragmentTransaction ft1 = fm.beginTransaction();
Fragment m_fragSet = new GamesFragment();
ft1.replace(R.id.frameLayout2, m_fragSet);
ft1.commit();
break;
case R.id.radioMale:
FragmentManager fmg = getFragmentManager();
FragmentTransaction ftr = fmg.beginTransaction();
Fragment m_frag = new MoviesFragment();
ftr.replace(R.id.frameLayout2, m_frag);
ftr.commit();
break;
default:
break;
}
}
});
}
布局activity_main:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<RadioGroup
android:id="@+id/radioSex"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<RadioButton
android:id="@+id/radioMale"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="true"
android:text="radiobutton1" />
<RadioButton
android:id="@+id/radioFemale"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="radiobutton2" />
</RadioGroup>
</LinearLayout>
<LinearLayout
android:id="@+id/passenger"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_marginTop="2dp"
android:orientation="horizontal"
android:weightSum="1" >
<FrameLayout
android:id="@+id/frameLayout2"
android:layout_width="0dp"
android:layout_height="fill_parent"
android:layout_weight="1"
android:background="@android:color/darker_gray" >
</FrameLayout>
</LinearLayout>
</LinearLayout>