天天看點

Android——ImageButton【圖檔按鈕】的點選事件與屬性

效果圖:

圖1:

Android——ImageButton【圖檔按鈕】的點選事件與屬性

圖2:

Android——ImageButton【圖檔按鈕】的點選事件與屬性

activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <ImageButton
        android:id="@+id/imb_queding"
        android:layout_width="250dp"
        android:layout_height="250dp"
        android:layout_centerInParent="true"
        android:background="#fa9e00"
        android:src="@drawable/ic_two"/>

</RelativeLayout>
           

MainActivity.java

public class MainActivity extends AppCompatActivity  {

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

        ImageButton imageButton = findViewById(R.id.imb_queding);
        imageButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Toast.makeText(MainActivity.this,"我叫 : ImageButton",Toast.LENGTH_LONG).show();

            }
        });
    }

}
           
總結:

常用屬性總結:

android:src		//設定顯示的圖檔,導入格式為:檔案夾名/圖檔名,例如: @drawable/ic_nature

android:scaleType		//調整圖檔縮放、位置等以滿足ImageView顯示的需要

	ScaleType.CENTER::圖檔大小為原始大小,如果圖檔大小大于ImageView控件,則截取圖檔中間部分,若小于,則直接将圖檔居中顯示。

  ScaleType.CENTER_CROP:将圖檔等比例縮放,讓圖像的短邊與ImageView的邊長度相同,即不能留有空白,縮放後截取中間部分進行顯示。

  ScaleType.CENTER_INSIDE:将圖檔大小大于ImageView的圖檔進行等比例縮小,直到整幅圖能夠居中顯示在ImageView中,小于ImageView的圖檔不變,直接居中顯示。

  ScaleType.FIT_CENTER:ImageView的預設狀态,大圖等比例縮小,使整幅圖能夠居中顯示在ImageView中,小圖等比例放大,同樣要整體居中顯示在ImageView中。

  ScaleType.FIT_END:縮放方式同FIT_CENTER,隻是将圖檔顯示在右方或下方,而不是居中。

  ScaleType.FIT_START:縮放方式同FIT_CENTER,隻是将圖檔顯示在左方或上方,而不是居中。

  ScaleType.FIT_XY:将圖檔非等比例縮放到大小與ImageView相同。

  ScaleType.MATRIX:是根據一個3x3的矩陣對其中圖檔進行縮放