我在将一些工作 XML 文件转换为代码时遇到了一些麻烦。我有一个 ListView,我需要能够在运行时从高级未知的资源(因此为什么不使用 XML)切换其按下/检查的可绘制对象;
以下配置效果很好:
主.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<ListView
android:id="@+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:choiceMode="singleChoice" >
</ListView>
</LinearLayout>
选择器.xml:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/blue" android:state_pressed="true"/>
<item android:drawable="@drawable/green" android:state_checked="true"/>
<item android:drawable="@drawable/orange"/>
</selector>
list_row.xml:
<?xml version="1.0" encoding="utf-8"?>
<CheckedTextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="@drawable/selector"
android:padding="10dp" />
主.java:
public class Main extends Activity {
StateListDrawable selector;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ListView listView1 = (ListView) findViewById(R.id.listView1);
StringAdapter adapter = new StringAdapter(this, R.layout.list_row);
adapter.add("one"); adapter.add("two"); adapter.add("three"); adapter.add("four");
adapter.add("five"); adapter.add("six"); adapter.add("seven"); adapter.add("eight");
adapter.add("nine"); adapter.add("ten"); adapter.add("eleven"); adapter.add("twelve");
listView1.setAdapter(adapter);
}
private class StringAdapter extends ArrayAdapter<String>{
public StringAdapter(Context context, int textViewResourceId) {
super(context, textViewResourceId);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final CheckedTextView tv = (CheckedTextView ) inflater.inflate(R.layout.list_row, parent, false);
tv.setText(getItem(position));
return tv;
}
}
}
结果是这样的,非常棒(按下:蓝色,选中:绿色,否则:橙色):
但是,如果我删除
android:background="@drawable/selector
从 list_row_xml,并通过代码应用它:
Drawable blue = getResources().getDrawable(R.drawable.blue);
Drawable green = getResources().getDrawable(R.drawable.green);
Drawable orange = getResources().getDrawable(R.drawable.orange);
selector = new StateListDrawable();
selector.addState(new int[] { android.R.attr.state_pressed }, blue);
selector.addState(new int[] { android.R.attr.state_checked }, green);
selector.addState(new int[] { }, orange);
tv.setBackgroundDrawable(selector);
我得到以下信息(一切都得到 state_pressed 可绘制,蓝色):
什么地方出了错?我很确定我已将选择器适当地转换为代码。