Android---fragment动态切换简单使用

public class MainActivity extends AppCompatActivity implements View.OnClickListener {


    private FragmentManager manager;
    private FragmentTransaction transaction;
    private RadioButton rb_shoprank, rb_share, rb_gift, rb_order;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initView();

        manager = getSupportFragmentManager();
        transaction = manager.beginTransaction();
        transaction.add(R.id.content_layout, new ShoprankFragment());
        transaction.commit();

    }

    // 初始化视图
    public void initView() {
        rb_shoprank = (RadioButton) findViewById(R.id.rb_shoprank);
        rb_share = (RadioButton) findViewById(R.id.rb_sharerank);
        rb_gift = (RadioButton) findViewById(R.id.rb_shopgift);
        rb_order = (RadioButton) findViewById(R.id.rb_shoporder);

        rb_shoprank.setOnClickListener(this);
        rb_share.setOnClickListener(this);
        rb_gift.setOnClickListener(this);
        rb_order.setOnClickListener(this);

    }
    
    // 点击方法
    @Override
    public void onClick(View v) {
        // 点击时启动trancaction事件
        transaction = manager.beginTransaction();
        
        switch (v.getId()) {
            case R.id.rb_shoprank:
                transaction.replace(R.id.content_layout, new ShoprankFragment());
                break;
            case R.id.rb_sharerank:
                transaction.replace(R.id.content_layout, new ShopshareFragment());
                break;
            case R.id.rb_shopgift:
                transaction.replace(R.id.content_layout, new ShopgiftFragment());
                break;
            case R.id.rb_shoporder:
                transaction.replace(R.id.content_layout, new ShoporderFragment());
                break;
            default:
                break;
        }

        transaction.commit();
    }
}

 

你可能感兴趣的:(Android,学习笔记)