1. 程式人生 > >Android中的Button自定義點選效果

Android中的Button自定義點選效果

原來聽很多人說Button不能使用自定義的點選或選中效果,所以做下測試

結果顯示Button很強大

完全可以使用這種靈活的方法

 方法一

1.放在drawable下的selector.xml檔案

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
 <item android:state_pressed="true" android:drawable="@drawable/temp1" />
 <item android:state_pressed="false" android:state_focused="false"
  android:drawable="@drawable/temp2" />
 <item android:state_focused="true" android:drawable="@drawable/temp3" />
 <item android:state_focused="false" android:drawable="@drawable/temp4" />
</selector>

2.佈局檔案main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<TextView 
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="@string/hello"
    />
<Button
 android:drawableTop="@drawable/shouru"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:text="@string/button"
 android:background="@drawable/selector"/>
</LinearLayout>

3.只是為了測試,所以效果不是很好,Button部分狀態效果圖如下:

①初始化的時候預設顯示的按鈕效果:

②點選後釋放顯示的效果

③點選不放時的效果

 方法二

1.佈局檔案main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<TextView 
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="@string/hello"
    />
<Button
 android:id="@+id/button"
 android:drawableTop="@drawable/shouru"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:text="@string/button"
 android:background="@drawable/temp4"/>
</LinearLayout>

2.主要的java程式碼,實現點選效果:
   Button button = (Button) this.findViewById(R.id.button);
   button.setOnTouchListener(new Button.OnTouchListener(){
   @Override
   public boolean onTouch(View v, MotionEvent event) {
    if(event.getAction() == MotionEvent.ACTION_DOWN){  
                    v.setBackgroundResource(R.drawable.temp1);  
                    Log.i("TestAndroid Button", "MotionEvent.ACTION_DOWN");
                }  
                else if(event.getAction() == MotionEvent.ACTION_UP){  
                    v.setBackgroundResource(R.drawable.temp2);
                    Log.i("TestAndroid Button", "MotionEvent.ACTION_UP");
                }
    return false;
   }
  });

這個方法實現的效果和上面的一樣,大家可以視具體情況來選擇