使用多状态按钮ToggleButton

  1. ToggleButton
     ToggleButton有两种状态:选中和未选中状态,并且需要为不同的状态设置不同的文本
  1. ToggleButton属性:
      android:checked="true"
      android:textOff="关"
      android:textOn="开"


import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.ToggleButton;

public class MainActivity extends AppCompatActivity {

    private ToggleButton toggleButton;
    private ImageView imageView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        toggleButton = (ToggleButton) findViewById(R.id.toggleButton);
        imageView = (ImageView) findViewById(R.id.imageView);

        toggleButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                imageView.setBackgroundResource(b?R.mipmap.on:R.mipmap.off);
            }
        });
    }
}




    

    







你可能感兴趣的:(android)