我有一个扩展ListActivity
的Activity。
ListView 使用默认主题的颜色。如何将我自己的颜色状态列表资源设置为 ListView?
我在onCreate()
中尝试过:
getListView().setBackgroundResource(R.drawable.background_listview);
这是background_listview
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true"
android:color="#ff000000"/> <!-- pressed -->
<item android:state_focused="true"
android:color="#ff000000"/> <!-- focused -->
<item android:color="#ff000000"/> <!-- default -->
</selector>
但我只得到错误
Caused by: org.xmlpull.v1.XmlPullParserException: Binary XML file line #4: <item> tag
requires a 'drawable' attribute or child tag defining a drawable.
最佳答案
您必须创建自己的自定义适配器,该适配器将从 ListAdapter 扩展,并在重写的 getView() 方法中为每个列表项扩展您的自定义布局。在此布局中,您应该将选择器设置为背景。实际上你的选择器看起来不错。
UDP日期:
看看这个简单的代码:
Activity :
public class YourActivity extends Activity {
private CustomAdapter customAdapter;
private ArrayList<ExampleObject> listObjects;
private ListView listView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_layout);
listView = (ListView) findViewById(R.id.activity_listview);
listObjects = new ArrayList<ExampleObjects>();
customAdapter = new CustomAdapter(this, R.layout.list_item, listObjects);
listView.setAdapter(customAdapter);
}
适配器:
public class CustomAdapter extends ArrayAdapter<ExampleObject> {
private LayoutInflater inflater;
public NoteAdapter(Context context, int textViewResourceId, List<ExampleObject> objects) {
super(context, textViewResourceId, objects);
inflater = LayoutInflater.from(context);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
return inflater.inflate(R.layout.list_item, parent, false);
}
}
您的list_item.xml:
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@drawable/your_selector">
</RelativeLayout>
希望对您有帮助。也许我犯了错误,因为我编写的代码没有编译器。
再次更新:
根据您的情况,将 android:color="#ff000000"
更改为 android:drawable="#ff000000"
。我希望这会有所帮助。
祝你好运!
关于Android:将背景颜色状态列表设置为ListActivitiy,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14127488/