想到了两种方法:
- 如果您更愿意坚持使用 XML,您可以创建 9
不同的状态列表选择器 XML(每个图像对一个),
然后将按钮正在使用的选择器文件交换为
需要。
- 您可以通过编程方式创建一个 StateListDrawable 以分配给
按钮。
选项 1:
创建一系列状态列表。
brownie_selector0.XML:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/pressedbrownie0" android:state_pressed="true"/>
<item android:drawable="@drawable/brownie0"/>
</selector>
brownie_selector1.XML:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/pressedbrownie1" android:state_pressed="true"/>
<item android:drawable="@drawable/brownie1"/>
</selector>
...等等。
然后更改分配给按钮的状态列表。例如使用开关:
...
Button brownieButton = (Button)findViewById(R.id.myBrownieButton);
switch (brownieType) { // brownieType would be an int indicating which State List is needed
case 0:
brownieButton.setBackground(getResources().getDrawable(R.id.brownie_selector0));
break;
case 1:
brownieButton.setBackground(getResources().getDrawable(R.id.brownie_selector1));
break;
...
}
选项 2
全部在代码中完成。
首先创建可绘制对象的 SparseIntArrays:
int drawableId;
String drawableName;
SparseIntArray brownieNormal = new SparseIntArray(totalNumberOfBrownies);
SparseIntArray browniePressed = new SparseIntArray(totalNumberOfBrownies);
// iterate through all the required brownie pairs
for (int i = 0; i < totalNumberOfBrownies; i++) {
// generate the required file name
drawableName = "brownie" + i;
// find the id of the required drawable using the generated file name
drawableId = getResources().getIdentifier(drawableName, "drawable", getPackageName());
// put the resulting drawable id into the SparseIntArray
brownieNormal.put(n, drawableId);
// repeat for the pressed images
drawableName = "pressedBrownie" + i;
drawableId = getResources().getIdentifier(drawableName, "drawable", getPackageName());
browniePressed.put(n, drawableId);
}
然后根据需要创建并分配一个合适的 StateListDrawable。
private StateListDrawable mBrownieStates;
...
// method to deal with when mBrownieType changes
private void changeBrownieButtonStateListDrawable(int brownieType);
// reset mBrownieStates to a fresh StateListDrawable
mBrownieStates = new StateListDrawable();
// add the drawable for the pressed state
mBrownieStates.addState(new int[] {android.R.attr.state_pressed}, browniePressed.get(brownieType));
// add the drawable for the default state
mBrownieStates.addState(new int[] {}, brownieNormal.get(brownieType));
// update the button with the newly defined StateListDrawable
Button brownieButton = (Button)findViewById(R.id.myBrownieButton);
brownieButton.setBackground(mBrownieStates);
}