Button组件是在我们在开发中最常用到的组件。Button组件,俗称“按钮”,在APP界面当中少不了按钮,那么按钮的属性和使用方法是怎么样的呢?
Button常用属性
因为Button继承TextView,所以他和TextView有很多共同的属性,下面列举一下常用的。
android:drawable //放一个drawable资源 android:drawableTop //可拉伸要绘制的文本的上面 android:drawableBottom //可拉伸要绘制的文本的下面 android:drawableLeft //可拉伸要绘制的文本的左侧 android:drawableRight //可拉伸要绘制的文本的右侧 android:text //设置显示的文本 android:textColor //设置显示文本的颜色 android:textSize //设置显示文本字体大小 android:background //可拉伸使用的背景 android:onClick //设置点击事件
Button的状态
android:state_pressed //是否按下,如一个按钮触摸或者点击。 android:state_focused //是否取得焦点,比如用户选择了一个文本框。 android:state_hovered //光标是否悬停,通常与focused state相同,它是4.0的新特性 android:state_selected //被选中状态 android:state_checkable //组件是否能被check。如:RadioButton是可以被check的。 android:state_checked //被checked了,如:一个RadioButton可以被check了。 android:state_enabled //能够接受触摸或者点击事件 android:state_activated //被激活 android:state_window_focused //应用程序是否在前台,当有通知栏被拉下来或者一个对话框弹出的时候应用程序就不在前台了
Button的点击事件(常用的两种)
一、通过实现OnClickListener接口
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
//实现OnClickListener接口
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_main);
        //找到Button,因为是返回的是VIEW,所以我们进行强转
        Button btn = (Button) findViewById(R.id.btn);
        //绑定监听
        btn.setOnClickListener(this);
    }
    
	//重写onClick()方法
    @Override
    public void onClick(View v) {
        Toast.makeText(MainActivity.this, "Clicked", Toast.LENGTH_SHORT).show();
    }
}二、使用匿名内部类
public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_main);
        Button btn = (Button) findViewById(R.id.btn);
        //使用匿名内部类
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(MainActivity.this, "Clicked", Toast.LENGTH_SHORT).show();
            }
        });
    }
}Button使用可能会遇到的情况
1.默认显示大写情况
我们在xml文件Button控件设置的文字明明是“Button”,但是最终显示在界面上面的情况是“BUTTON”,这是由于系统可能对Button中的所有英文字母自动转换成大写了,如果不是你想要的效果,就在xml文件Button控件里面设置下面的属性:
android:textAllCaps="flase";
Android TextView 常用属性,请访问:https://www.niwoxuexi.com/blog/android/article/423.html