按鈕:
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/buttonId"
android:text="button"
android:textColor="#ffffff"
android:textSize="20sp"
android:gravity="center|right"
android:layout_gravity="center"
android:background="#111111"
android:onClick="btnClick"
android:textAllCaps="false"/>
<!--
layout_width="match_parent: 表示當前元素的寬度和父元素一樣寬
layout_width="wrap_content: 表示當前元素的寬度只要能剛好包含里面的內(nèi)容就行了
layout_height="match_parent: 表示當前元素的高度和父元素一樣高
layout_height="wrap_content: 表示當前元素的高度只要能剛好包含里面的內(nèi)容就行了
id: 唯一標識符
text: 設置button內(nèi)容
textSize: 設置button的大小。
textColor: 設置button的顏色。
background: 設置button背景顏色
gravity: 設置button內(nèi)容的對齊方式,可選值有 top、bottom、left、right、center 等,可以用豎線來同時指定多個值。center 效果等同于 "center_vertical 加 center_horizontal"
layout_gravity: 設置button對齊方式, 可選值有 top、bottom、left、right、center 等,可以用豎線來同時指定多個值。center 效果等同于 "center_vertical 加 center_horizontal"
onClick: 設置button的點擊事件
textAllCaps: 所有英文字母是否進行大寫轉(zhuǎn)換,默認為 true
-->
效果:
屏幕快照 2018-11-09 下午2.54.32.png
button點擊事件:
第一種:
給xml中給button增加了android:onClick="btnClick"屬性,然后在該布局文件對應的Acitivity中實現(xiàn)該方法。需要注意的是這個方法必須符合三個條件:
1).方法的修飾符是 public
2).返回值是 void 類型
3).只有一個參數(shù)View,這個View就是被點擊的這個控件。
public void btnClick(View v) {
Toast.makeText(MainActivity.this, "點擊了按鈕", Toast.LENGTH_SHORT).show();
}
第二種:
在該布局文件對應的Acitivity中為 Button 的點擊事件注冊一個監(jiān)聽器:
findViewById(R.id.buttonId).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(MainActivity.this, "點擊了按鈕", Toast.LENGTH_SHORT).show();
}
});