前言
Button组件是在我们在开发中最常用到的组。Button组件,俗称“按钮”,在APP界面当中少不了按钮,那么按钮的属性和使用方法是怎么样的呢?
Button常用属性
因为Button继承TextView,所以他和TextView有很多共同的属性,下面列举一下常用的。如果想要更深入了解可以点击这个网址https://blog.csdn.net/chengxu_kuangrexintu/article/details/79582934 去了解有关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();
}
});
}
}