Android Button、ImageView等自定義選中
方法一:代碼實現 1. 自定義狀態效果可以通過代碼實現,也可以通過xml定義style實現。 2. 下面先介紹代碼實現,通過StateListDrawable定義Button背景。 3. 由於View類中PRESSED_ENABLED_STATE_SET值不是公共常量,所以通過繼承來訪問了。 特註:其他控件的效果,比如ImageView,也可以通過這種方法實現,但是由於ImageView默認是沒焦點,不可點擊的,需要自己更改(需要點擊就設置android:clickable="true" , 需要能夠選中就設置android:focusable="true" )。
JAVA代碼: package com.test.TestButton; import android.app.Activity; import android.content.Context; import android.graphics.drawable.Drawable; import android.graphics.drawable.StateListDrawable; import android.os.Bundle; import android.view.View; import android.widget.Button; public class TestButton extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Integer[] mButtonState = { R.drawable.defaultbutton, R.drawable.focusedpressed, R.drawable.pressed }; Button mButton = (Button) findViewById(R.id.button); MyButton myButton = new MyButton(this); mButton.setBackgroundDrawable(myButton.setbg(mButtonState)); } class MyButton extends View { public MyButton(Context context) { super(context); } // 以下這個方法也可以把你的圖片數組傳過來,以StateListDrawable來設置圖片狀態,來表現button的各中狀態。未選 // 中,按下,選中效果。 public StateListDrawable setbg(Integer[] mImageIds) { StateListDrawable bg = new StateListDrawable(); Drawable normal = this.getResources().getDrawable(mImageIds[0]); Drawable selected = this.getResources().getDrawable(mImageIds[1]); Drawable pressed = this.getResources().getDrawable(mImageIds[2]); bg.addState(View.PRESSED_ENABLED_STATE_SET, pressed); bg.addState(View.ENABLED_FOCUSED_STATE_SET, selected); bg.addState(View.ENABLED_STATE_SET, normal); bg.addState(View.FOCUSED_STATE_SET, selected); bg.addState(View.EMPTY_STATE_SET, normal); return bg; } } }
方法二:XML自定義風格 在res/drawable下面新建mybutton_background.xml文件,內容如下: <?xml version=”1.0″ encoding=”utf-8″?> <selector xmlns:android=”http://schemas.android.com/apk/res/android“> <item android:state_focused=”true” android:state_pressed=”false” android:drawable=”@drawable/yellow” /> <item android:state_focused=”true” android:state_pressed=”true” android:drawable=”@drawable/green” /> <item android:state_focused=”false” android:state_pressed=”true” android:drawable=”@drawable/blue” /> <item android:drawable=”@drawable/grey” /> </selector> 這裡面就定義了在不同狀態下的顯示圖片,然後在layout裡面定義Button的時候,指定它的background為這個mybutton_background <?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” > <Button android:id=”@+id/btn” android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:text=”@string/mybtn” android:background=”@drawable/mybutton_background”/> </LinearLayout> 這種方式開發比較簡單,適合做一些風格一致的Button,設置成同一個background就可以了。ImageView等控件如方法一中所述。 方法三:JAVA代碼中通過監聽事件改變,這個不推薦(^o^)/~, 就不寫了。
希望对大家有所帮助 |