#Android学习#Fragment简单切换及常用控件用法

今天主要学习了日期选择器、时间选择器、单项选择、多项选择这几个常用控件的用法,同时也回顾了一下之前Fragment的一些简单使用。
新建一个Android Studio Project,选择一个Blank Activity,这里也可以勾选use a Fragment,这样子,Android Studio就会为我们自动建立一个带有Fragment的Activity,不过这次我们并不勾选这个选项,而是自己来建立一个Fragment,来了解它的用法。
新建一个项目后,我们建立一个主Fragment,用于显示Button,点击不同的Button可跳转到不同常用控件简单用法的Fragment页面。

// MainFragment extends Fragment
// 在onCreate函数中,通过findViewById找到对应的Button
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.fragment_main,container, false);
        initView();
        initListener();
        return rootView;
    }

    public void initView(){
        btnStartChooseDate = (Button) rootView.findViewById(R.id.btnStartChooseDate);
        btnStartChooseTime = (Button) rootView.findViewById(R.id.btnSTartChooseTime);
        btnStartRadio = (Button) rootView.findViewById(R.id.btnStartRadio);
        btnStartCheckbox = (Button) rootView.findViewById(R.id.btnStartCheckbox);
    }
    public void initListener(){
        btnStartChooseDate.setOnClickListener(this);
        btnStartChooseTime.setOnClickListener(this);
        btnStartRadio.setOnClickListener(this);
        btnStartCheckbox.setOnClickListener(this);
    }
    // 复写onclick函数
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.btnStartChooseDate:
                // fragment之间的切换
                getFragmentManager().beginTransaction()
                        .addToBackStack(null)
                        .replace(R.id.container, new ChooseDateFragment())
                        .commit();
                break;
            case R.id.btnSTartChooseTime:
                getFragmentManager().beginTransaction()
                        .addToBackStack(null)
                        .replace(R.id.container, new ChooseTimeFragment())
                        .commit();
                break;
            case R.id.btnStartRadio:
                getFragmentManager().beginTransaction()
                        .addToBackStack(null)
                        .replace(R.id.container, new ChooseRadioFragment())
                        .commit();
                break;
            case R.id.btnStartCheckbox:
                getFragmentManager().beginTransaction()
                        .addToBackStack(null)
                        .replace(R.id.container, new ChooseCheckboxFragment())
                        .commit();
                break;
        }
    }

这里还需要一个fragment_main的布局文件,布局文件的代码很简单,使用一个线性布局,然后把添加几个Button进去即可,这里就不给出相关源码了
接下来我们看看MainActivity的代码,其实就只是在Activity增加了一句代码,用于显示Fragment

// MainActivity
@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        // 使用的是FrameLayout布局,不是fragment,因此下面的这行代码用于将fragment显示出来
        // 如果使用的是fragment,则不需要下面的这行代码,也可以将fragment显示出来
        getSupportFragmentManager().beginTransaction().add(
                R.id.container, new MainFragment()).commit();


    }

需要注意的是,当我们在新建Activity时,勾选了use a Fragment的话,MainActivity里面是没有getSupportFragmentManager().beginTransaction().add(R.id.container, new MainFragment()).commit(); 这行代码的。那它是怎么实现的,通过对比,我们发现系统自动建立的Fragment,它在布局容器里,使用的是<fragment>标签,并且有个android:name 的属性,这个属性的值指向我们的MainFragment类,如com.cyfloel.learncommoncontrol.MainFragment ,而这里我们自己建立的布局容器,使用的是FrameLayout 因此,需要上面那行代码才能将Fragment的内容显示出来。
另外,切换到其他Fragment的时候,我们使用的是getFragmentManager 这里是需要注意的,至于原因现在还没搞清楚,之后再来补充。

日期和时间选择器

日期和时间选择器的用法很相似,日期使用的是DatePickerDialog ,时间使用的是TimePickerDialog ,我们新建了各自的Fragment后,看看里面的onCreateView函数

// ChooseDateFragment
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        rootView = inflater.inflate(R.layout.fragment_choose_date, container, false);
        textView = (TextView) rootView.findViewById(R.id.textView);
        rootView.findViewById(R.id.btnChooseDate).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // 日期选择器
                new DatePickerDialog(getActivity(), new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker datePicker, int year, int month, int day) {
                        textView.setText(String.format("%d-%d-%d", year, month+1,day));
                    }
                }, 2016,02,04).show();
            }
        });
        return rootView;
    }
// ChooseTimeFragment
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.fragment_choose_time, container,false);
        textView = (TextView) rootView.findViewById(R.id.textView);
        rootView.findViewById(R.id.btnChooseTime).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // 时间选择器
                new TimePickerDialog(getActivity(), new TimePickerDialog.OnTimeSetListener() {
                    @Override
                    public void onTimeSet(TimePicker timePicker, int hourOfDay, int minute) {
                        textView.setText(String.format("%d:%d", hourOfDay, minute));
                    }
                }, 0,0,true).show();
            }
        });
        return rootView;
    }

这里有一点需要注意的,就是DatePickerDialog中需要传入一个context对象和一个listener对象,其中,listener对象需要复写它的onDateSet函数,里面有个month的变量,这个变量的值是从0开始的,也就是说,如果我们在输出的时候,想要得到与选择器同样的月份,输出是需要将month+1。

单项选择和多项选择

单项选择需要使用RadioGroup和RadioButton,而多项选择使用的是CheckBox

// ChooseRadioFragment
@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.fragment_choose_radio, container, false);
        rootView.findViewById(R.id.btnSend).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                RadioButton radioButton = (RadioButton) rootView.findViewById(R.id.rb1);
                if (radioButton.isChecked()){
                    Toast.makeText(getActivity(), "选择正确", Toast.LENGTH_SHORT).show();
                }else {
                    Toast.makeText(getActivity(), "选择错误", Toast.LENGTH_SHORT).show();
                }
            }
        });
        return rootView;
    }
// ChooseCheckBoxFragment
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.fragment_choose_checkbox, container, false);
        textView = (TextView) rootView.findViewById(R.id.textView);
        checkBox1 = (CheckBox) rootView.findViewById(R.id.checkbox1);
        checkBox2 = (CheckBox) rootView.findViewById(R.id.checkbox2);
        checkBox3 = (CheckBox) rootView.findViewById(R.id.checkbox3);
        checkBox4 = (CheckBox) rootView.findViewById(R.id.checkbox4);
        checkBox5 = (CheckBox) rootView.findViewById(R.id.checkbox5);
        checkBox1.setOnCheckedChangeListener(this);
        checkBox2.setOnCheckedChangeListener(this);
        checkBox3.setOnCheckedChangeListener(this);
        checkBox4.setOnCheckedChangeListener(this);
        checkBox5.setOnCheckedChangeListener(this);
        return rootView;
    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        String str = "你选择的是:";
        if (checkBox1.isChecked()){
            str = str + checkBox1.getText() + ",";
        }
        if (checkBox2.isChecked()){
            str = str + checkBox2.getText() + ",";
        }
        if (checkBox3.isChecked()){
            str = str + checkBox3.getText() + ",";
        }
        if (checkBox4.isChecked()){
            str = str + checkBox4.getText() + ",";
        }
        if (checkBox5.isChecked()){
            str = str + checkBox5.getText() + ",";
        }
        textView.setText(str);
    }

注意到,监听CheckBox的时候,使用setOnCheckedChangeListener以及复写onCheckedChanged 布局方面CheckBox没什么特殊的地方,Radio需要使用到RadioGroup,这里给下fragment_choose_radio的布局代码

// fragment_choose_radio
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="单项选择"/>
    <RadioGroup
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">
        <RadioButton
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/rb1"
            android:text="选项1"/>
        <RadioButton
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/rb2"
            android:text="选项2"/>
        <RadioButton
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/rb3"
            android:text="选项3"/>
        <RadioButton
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/rb4"
            android:text="选项4"/>
    </RadioGroup>
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/btnSend"
        android:text="提交"/>

</LinearLayout>
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值