Android Button 常用屬性設定,圓角,邊框,點選事件
阿新 • • 發佈:2019-02-14
<Button
<!--設定代表此button的id-->
android:id="@+id/btn"
android:layout_width="200dp"
android:layout_height="200dp"
<!--設定btn上顯示的文字-->
android:text="QQ"
<!--設定btn上文字大小-->
android:textSize="16sp"
<!--設定btn文字顏色-->
android:textColor="#000000"
<!--設定btn的內邊距-->
android:padding="20dp"
<!--button是通過drawable來引入圖片的-->
android:drawableTop="@drawable/a"
<!--btn引如背景圖,background即可以是顏色,也可以是圖片-->
android:background="@drawable/shape"
/>
其中屬性說明:
- android:layout_width 表示控制元件寬度, wrap_content, match_parent,以及具體的值; 長度單位為dp;
- android:layout_height 表示控制元件高度, wrap_content,match_parent,以及具體的值; 長度單位為dp;
- android: text 在button上要顯示的文字
- android:textSize 在button上要顯示的字型大小
- android:textColor 在button上要顯示的字型的顏色
- android:padding 設定內邊距
- android:drawableTop
- android:drawableBottom
- android:drawableLeft
- android:drawableRight 這四個值表示引入圖片,且該圖片與文字排列的規則
- android:background 表示button的背景色或者背景圖片 (即可以接圖片,又可以接顏色值)
圓角,邊框
其實android的圓角邊框是通過背景圖片來設定的.
那麼需要現在drawable資料夾中建立一個shape.xml的檔案
<?xml version="1.0" encoding="utf-8" ?>
<!--相當於做了一張圓角的圖片,然後給button作為背景圖片-->
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<!--設定背景色-->
<solid android:color="#FF0000" />
<!--設定圓角-->
<corners android:radius="105dip" />
<!--<padding-->
<!--android:bottom="10dp"-->
<!--android:left="10dp"-->
<!--android:right="10dp"-->
<!--android:top="10dp"-->
<!--/>-->
<!--設定邊框線的寬度和顏色-->
<stroke android:width="3dp" android:color="#00ff00" />
</shape>
其中:
1. solid 表示背景顏色。
2. corners 表示圓角程度。
3. stroke表示邊框線,可以設定邊框和背景色
將這張shape的圖片資源匯入到Button的background就會出現圓角,以及邊框了。
Button新增點選事件的方式
public class MainActivity extends AppCompatActivity implements OnClickListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 1.採用匿名物件新增時間
Button btn = (Button) this.findViewById(R.id.btn);
ButtonListener listener = new ButtonListener();
btn.setOnClickListener( listener );
// btn.setOnClickListener(new OnClickListener() {
// @Override
// public void onClick(View v) {
// System.out.println( "haha\n" );
// }
// });
}
// 第二種新增點選時間的方法,用來給多種btn同時新增點選時間
public void onClick(View v){
System.out.println( "hehe\n" );
}
}
class ButtonListener implements OnClickListener {
public void onClick( View view ){
System.out.println( "xixi" );
}
}
方式一: 匿名類的方式. new OnClickListener(){ public void onClick( View v ){ } }
方式二: 實現介面 OnClickListener 介面,並實現 public void onClick( View v ){}方法
方式三: 自定義類並且實現 OnClickListener介面;