RadioGroup+Fragment 实现简单选项卡切换

开发过程中,类似新浪,淘宝,实现底部选项卡简单切换,简单的了解下。 



1.首先是 XML  style drawable

1.首先是 Main.xml 




    
    

    

        
        
        
        
    
 
  




    
    
    

2.MainActivity。 replace实现替换,当然也可以使用show,hide等,看开发者个人爱好。

public class MainActivity extends FragmentActivity implements RadioGroup.OnCheckedChangeListener{


    private static final int RESULT_LOGIN = 1;

    @ViewInject(R.id.radioGroup)
    RadioGroup radioGroup;

    Fragment fragment;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(1);
        setContentView(R.layout.main);
        ViewUtils.inject(this);

        radioGroup.setOnCheckedChangeListener(this);
        fragment = getSupportFragmentManager().findFragmentById(R.id.fragment);

        if (fragment == null) {
            fragment = WaggonFragment.newInstance();
            getSupportFragmentManager().beginTransaction().add(R.id.fragment, HomeFragment.newInstance()).commit();
        }
    }


    @Override
    public void onCheckedChanged(RadioGroup radioGroup, int i) {
        switch (i){
            case R.id.tab_one:{
                fragment = ContentFragment.newInstance();
            }
            break;
            case R.id.tab_two:{
                fragment = ContentFragment.newInstance();
            }
            break;
            case R.id.tab_three:{
                fragment = ContentFragment.newInstance();
            }
            break;
            case R.id.tab_four:{
                fragment = ContentFragment.newInstance();
            }
            break;
        }
        if(fragment != null){
            getSupportFragmentManager().beginTransaction().replace(R.id.fragment, fragment).commit();
        }
    }
}

3. ContentFragment,里面布局 main_content自己随意写个。

public class ContentFragment extends Fragment {

    public static Fragment newInstance() {
        ContentFragment f = new ContentFragment();
        return f;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {


        View v = inflater.inflate(R.layout.main_content, container, false);
        ViewUtils.inject(this, v);

        return v;
    }
}

以后只是实现选项卡简单的切换。如果实现动画,或者滑动,重写Fragment实现想要的功能即可。

你可能感兴趣的:(Android)