Start a picture

The purpose of this article is to introduce Button and its subclasses.

Button

Button A user interface element that a user can click or long-press. It has a normal state and a clickstate. A Button inherits from a TextView, so it can use those properties of a TextView.

In actual development, it is nothing more than to do corresponding operations on several states of the button, such as: button pressed with one color, up with another color, or button is not available with one color.

The instance

Let’s say we have 1 basic Button and 2 advanced buttons.

Basic version Button

Add a Button to the layout file

 <Button
        android:id="@+id/btn_1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Basic Button" />
Copy the code

Not only is the style ugly but the text appears as an uppercase BUTTON.

Premium Button

Add some XML attributes to the base version of Button.

1. Create a file bg_btn_frame_gradient.xml in the res/drawable directory


      
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <! - The four RADIUS rounded corners can be set uniformly. You can also set a single radius rounded corner. Example: topLeftRadius -- >
    <corners android:radius="8dp"/>
    <! Width, color-->
    <stroke android:width="1dp" android:color="@color/color_ff0000" />
    <gradient
        android:startColor="@color/color_188FFF"
        android:centerColor="@color/color_FF773D"
        android:endColor="@color/color_ff0000"
        android:type="linear"
        />
</shape>
Copy the code

2. Create file bg_btn_selector_bg. XML in the res/drawable directory


      
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <! Android :radius="8dp" -->
    <! -- Unclicked show color -->
    <item android:drawable="@color/color_FF773D" android:state_pressed="false" />
    <! -- Go to Show Color -->
    <item android:drawable="@color/color_188FFF" android:state_pressed="true" />

    <! -- Complex version with rounded corners -->
    <! -- Unclicked show color -->
    <item android:state_pressed="false">
        <shape>
            <solid  android:color="@color/color_FF773D" />
            <corners android:radius="8dp" />
        </shape>
    </item>
    <! -- Go to Show Color -->
    <item android:state_pressed="true">
        <shape>
            <solid  android:color="@color/color_188FFF" />
            <corners android:radius="8dp" />
        </shape>
    </item>
</selector>
Copy the code

3. Modify the layout file to add two buttons

<Button
        android:id="@+id/btn_2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="@dimen/dimen_20"
        android:background="@drawable/bg_btn_frame_gradient"
        android:padding="@dimen/dimen_10"
        android:text="Button with background gradient"
        android:textAllCaps="false"
        android:textColor="@color/white"
        android:textSize="@dimen/text_size_18" />

    <Button
        android:id="@+id/btn_3"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="@dimen/dimen_20"
        android:background="@drawable/bg_btn_selector_bg"
        android:onClick="btn3OnClick"
        android:padding="@dimen/dimen_10"
        android:textAllCaps="false"
        android:text="Button with press effect"
        android:textColor="@color/white"
        android:textSize="@dimen/text_size_18" />
Copy the code

Let’s see how it works

XML summary

At this point, the above renderings have been completed. Setting the Android: Background property of a Button to the drawable resource makes it easy to change the color or background of the Button when it is pressed

  • Btn_2 because it uses drawable directly and does not use selector. So no clicks. Gradients are always displayed whether clicked or not.

StateListDrawable is a Drawable resource that can be set to different image effects depending on the state, key nodes < selector >

  • Btn_3 uses selector to set the background color and rounded corners to different states on the item tag under Android: state_Pressed. Display according to whether the control is pressed (color_FF773D/color_188FFF)

Interaction events

The core of a Button is the interaction with the user. Otherwise, use TextView.

1.Activity implements the view. OnClickListener method

public class ButtonActivity extends AppCompatActivity implements View.OnClickListener {
    private Button btn_1;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.view_button);// Load the layout file
        initViewButton();
    }
    private void initViewButton(a){
        btn_1 = findViewById(R.id.btn_1);
        btn_1.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.btn_1:
                Toast.makeText(this."Btn_1 Click Event",Toast.LENGTH_SHORT).show();
                break;
            default:
                break; }}}Copy the code

2. Declare it in the layout file

  • Add android:onClick=”btn3OnClick” property to button
  • Add a method with the corresponding name to the activity if the following conditions are met
    • Method modifier is public;
    • The return value is void;
    // No associated controls are required
    public void btn3OnClick(View view){
        Toast.makeText(this."Btn_3 Click Event",Toast.LENGTH_SHORT).show();
    }
Copy the code

3. Anonymous inner class implementation

A long-click anonymous inner class is attached. Note that if onLongClick returns false, the onClick event will continue. If onLongClick returns true, the onClick event will not be executed.

btn_2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(ButtonActivity.this."Btn_2 Click Event",Toast.LENGTH_SHORT).show(); }}); btn_2.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                Toast.makeText(ButtonActivity.this."Btn_2 Long Click Event",Toast.LENGTH_SHORT).show();
                return false; }});Copy the code

4. Inner class implementation

/ / use
    btn_1.setOnClickListener(new MyOnClickListener());
    // The inner class implements the OnClickListener interface
    class MyOnClickListener implements View.OnClickListener{

        @Override
        public void onClick(View v) {
            Toast.makeText(ButtonActivity.this."Btn_1 Click event MyOnClickListener",Toast.LENGTH_SHORT).show(); }}Copy the code

Summary of interactive events

  • Button’s setOnClickListener has a higher priority than android:onClick in XML. If the click event is set at the same time, only setOnClickListener is valid.
  • TextView can also implement onClick event, if part of the Button use trouble can consider using TextView instead.

Button Displays letters in uppercase

Set android:textAllCaps=”false” to fix this

Button sets background to invalid

Solution: The default color Settings come from res/values/themes.xml.

Will be the Theme of the inside the parent = “Theme. MaterialComponents. DayNight. DarkActionBar”

Instead (other topics can also be) parent = “Theme. MaterialComponents. DayNight. DarkActionBar. Bridge”

That’s all for Button in this article. Let’s look at its subclasses.

RadioButton

RadioButton RadioButton, inherited from a Button, so it has all the exposed properties and methods of a Button. RadioButton has only two states, checked and unchecked, so only one property is the most important. That’s Android: Checked (setting or getting the checked state of a RadioButton).

The instance

Add the RadioButton to the layout file

<RadioButton
            android:id="@+id/rb_red"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Red"
            android:textColor="@color/color_ff0000"
            android:textSize="@dimen/text_size_18" />
Copy the code

Add an OnCheckedChangeListener event handler to your Activity

rb_red.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                //isChecked is used to check whether RadioButton is selected
                if(isChecked){
                    MLog.e("Selected");
                }else{
                    MLog.e("Not selected"); }}});Copy the code

IsChecked checks whether the RadioButton isChecked.

Let’s see how it works

Then you’ll notice that you can only select but not cancel, that the radio button is now a select button, and that both colors are selected in the renderer. That just means we implement radio buttons, not radio functionality.

The implementation of the radio function of the scheme

  • 1. Uncheck the status of other buttons based on the code.
  • 2. Introduce the RadioGroup

RadioGroup Group of radio buttons

RadioGroup is used to group several radiobuttons together to form a group of radio buttons to achieve radio function, that is, if one is selected, the other options will be unselected.

RadioGroup can be initialized with all options unchecked, but once selected, there is no way to uncheck one unless you manually call the clearCheck() method.

To change the placement of radiobuttons in a RadioGroup, use the Android: Orientation attribute.

Add controls to the layout file

Add 1 RadioGroup and 2 radiobuttons, add an ID for each RadioButton, otherwise the radio function will take effect

    <RadioGroup
        android:id="@+id/rg"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:orientation="horizontal">

        <RadioButton
            android:id="@+id/rb_liangpi"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Liangpi"
            android:textSize="@dimen/text_size_18" />

        <RadioButton
            android:id="@+id/rb_roujiamo"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Rou jia mo"
            android:textSize="@dimen/text_size_18" />
    </RadioGroup>
Copy the code

Add an OnCheckedChangeListener event handler to your Activity

This OnCheckedChangeListener from RadioGroup, rather than a RadioButton CompoundButton. OnCheckedChangeListener.

rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if(checkedId==R.id.rb_liangpi){
                    MLog.e("Chose cold skin.");
                }else{
                    MLog.e("Chose the rou jia mo"); }}});Copy the code

Let’s see how it works

So that’s the radio button function, let’s take a look at its brother CheckBox.

CheckBox

CheckBox A CheckBox has no properties of its own other than those inherited from a Button, but it inherits a property from CompoundButton that Android: Checked uses to say whether it’s checked or not.

You can put multiple checkboxes together to check multiple items at the same time, but there is no relationship between them, and the checking of one does not affect the checking or unchecking of the other.

The instance

Add a few checkboxes to your layout file

<LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <CheckBox
            android:id="@+id/cb_yan"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:checked="true"
            android:text="Salt"
            android:textSize="@dimen/text_size_18" />

        <CheckBox
            android:id="@+id/cb_cu"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Vinegar"
            android:textSize="@dimen/text_size_18" />

        <CheckBox
            android:id="@+id/cb_lajiao"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Add pepper"
            android:textSize="@dimen/text_size_18" />
    </LinearLayout>
Copy the code

Add an OnCheckedChangeListener event handler to your Activity for each CheckBox

cb_cu.setChecked(true);
cb_yan.setOnCheckedChangeListener(this);
cb_cu.setOnCheckedChangeListener(this);
cb_lajiao.setOnCheckedChangeListener(this);

@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        switch (buttonView.getId()){
            case R.id.cb_yan:
                if(isChecked){
                    MLog.e("Select salt");
                }else{
                    MLog.e("Salt not selected");
                }
                break;
            case R.id.cb_cu:
                if(isChecked){
                    MLog.e("Selected with vinegar.");
                }else{
                    MLog.e("Vinegar not selected");
                }
                break;
            case R.id.cb_lajiao:
                if(isChecked){
                    MLog.e("Select pepper");
                }else{
                    MLog.e("Chillies not selected");
                }
                break; }}Copy the code

Let’s see how it works

And then you’ll see that there’s no relationship between them, and the fact that one is selected doesn’t affect whether the other is selected or not. It’s an individual.

With the CheckBox function in place, let’s take a look at its sibling, the Switch.

Switch

  • Switch inherits from Button and CompoundButton, so it has their properties, methods, and events;
  • Like ToggleButton, both Switch and ToggleButton allow us to Switch between two states, a bit like the popular slide to unlock;
  • The difference between a Switch and a ToggleButton is that it appears to display both on and off text, which is helpful for guiding user operations. For example, a ToggleButton only displays the open text when it is on, but it is not clear what happens when you click on it. I’ll tell you exactly what happens when you order it.

The XML attribute of the Switch

The instance

Add switches to the layout file

<Switch
    android:id="@+id/switch_power"
    android:layout_width="wrap_content"
    android:layout_height="50dp"
    android:textOn="Agree"
    android:textOff="Disagree"
    android:text="Rights"
    android:showText="true"
    android:checked="true"
    android:textSize="@dimen/text_size_18" />
Copy the code

Add the OnCheckedChangeListener event handler to the Activity for the Switch


      switch_power.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
          @Override
          public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
              if(isChecked){
                  MLog.e("Agreed");
              }else{
                  MLog.e("No consent."); }}});Copy the code

Let’s see how it works

If you’re not happy with the native buttons, you can customize the Switch’s appearance. We can customize the Switch’s background image and slider image with the Android: Track and Android: Thumb properties

Note, however, that each image has two states, on and off, and the problem is that the Switch is as large as the image resource. If you need to change the size, you need to get a Drawable object from Java and then change the size.

With the Switch function in place, let’s look at its sibling, the ToggleButton.

ToggleButton

A ToggleButton allows us to switch between two states, a bit like a light switch. ToggleButton and Switch both inherit from CompoundButton, so they have the properties and methods of a Button, and they have the properties of CompoundButton android: Checked

The instance

Add ToggleButton to the layout file

<ToggleButton
    android:id="@+id/tb_power"
    android:text="Power"
    android:textOn="Light"
    android:textOff="Turn off the lights"
    android:checked="true"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

<ToggleButton
    android:id="@+id/tb_power2"
    android:text="Power"
    android:textOn="Light"
    android:textOff="Turn off the lights"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />
Copy the code

Add the OnCheckedChangeListener event handler to the Activity for the Switch

tb_power.setOnCheckedChangeListener(this);
tb_power2.setOnCheckedChangeListener(this);
  case R.id.tb_power:
  case R.id.tb_power2:
    if(isChecked){
      MLog.e(buttonView.getId()+"Open");
    }else{
      MLog.e(buttonView.getId()+"Closed");
    }
    break;
Copy the code

Let’s see how it works

That’s all for this article. I hope it will help and inspire you to learn Android Button and its subclasses.