fragment点击切换

protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
frag_layout = findViewById(R.id.fragment_layout);
radio_group = findViewById(R.id.radio_group);
oneFragment = new OneFragment();
twoFragment = new TwoFragment();
threeFragment = new ThreeFragment();
manager = getSupportFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.replace(R.id.fragment_layout,oneFragment).commit();
radio_group.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup radioGroup, int i) {
FragmentTransaction transaction = manager.beginTransaction();
switch (i){
case R.id.rb1:
transaction.replace(R.id.fragment_layout,oneFragment);
break;
case R.id.rb2:
transaction.replace(R.id.fragment_layout,twoFragment);

            case R.id.rb3:
                transaction.replace(R.id.fragment_layout,threeFragment);
                break;
        }
        transaction.commit();
    }
});
}

}

<FrameLayout
    android:id="@+id/fragment_layout"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="9">
</FrameLayout>

 <RadioGroup
     android:layout_width="match_parent"
     android:layout_height="0dp"
     android:layout_weight="1"
     android:id="@+id/radio_group"
     android:orientation="horizontal"
     >
<RadioButton
    android:layout_width="0dp"
    android:layout_height="match_parent"
    android:layout_weight="1"
    android:id="@+id/rb1"
    android:textSize="20sp"
    android:padding="10dp"
    android:text="首页"
    android:checked="true"
    android:background="@drawable/selector"
    android:button="@null"
    android:gravity="center"
    />
     <RadioButton
         android:layout_width="0dp"
         android:layout_height="match_parent"
         android:layout_weight="1"
         android:id="@+id/rb2"
         android:textSize="20sp"
         android:padding="10dp"
         android:text="附近"
         android:background="@drawable/selector"
         android:button="@null"
         android:gravity="center"
         />
     <RadioButton
         android:layout_width="0dp"
         android:layout_height="match_parent"
         android:layout_weight="1"
         android:id="@+id/rb3"
         android:textSize="20sp"
         android:padding="10dp"
         android:text="发现"
         android:background="@drawable/selector"
         android:button="@null"
         android:gravity="center"
         />
 </RadioGroup>

猜你喜欢

转载自blog.csdn.net/yzt10444/article/details/81841403