简体   繁体   English

如何按位置设置列表视图中特定项目的背景颜色?

[英]How to set the background color of a specific item in listview by position?

I want to set the background color of a specific item in the listview. 我想在列表视图中设置特定项目的背景颜色。

My listview is generated by ArrayAdapter using a ArrayList. 我的listview是由ArrayAdapter使用ArrayList生成的。

I have a specific item in the listview that I plan to change the background color. 我在listview中有一个特定的项目,我计划更改背景颜色。

I know the item's position in the list. 我知道该项目在列表中的位置。

This is my code for generating the listview. 这是我生成列表视图的代码。

respondMessageListView = (ListView) findViewById(R.id.respondMessageListView);
respondMessageListView.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, autoRespondMessages.getMessages()));

Thank you! 谢谢!

[edit] [编辑]

According to this post , using setSelection makes no effect if is used in onCreate(), the work around is "remove the method onAttachedToWindow in PullToRefreshListView ". 根据这篇文章 ,如果在onCreate()中使用setSelection没有任何效果,解决方法是“删除onAttachedToWindow中的PullToRefreshListView方法”。 I am not quite understanding the solution. 我不太了解解决方案。 May I ask how should I accomplish this? 请问我应该怎样做到这一点? I am a subclass of Activity , so I cannot subclass any other class anymore. 我是Activity的子类,所以我不能继承任何其他类的子类。

You will have to subclass ArrayAdapter and override the getView(...) method. 您必须ArrayAdapter并覆盖getView(...)方法。 For simplicity's sake you could just call through to the base class implementation and set the background color for the returned View . 为简单起见,您可以调用基类实现并为返回的View设置背景颜色。

Edit: The following example colors the items' backgrounds alternating black and white. 编辑:以下示例将项目的背景颜色交替为黑色和白色。

private class MyAdapter extends ArrayAdapter {

    ...

    public View getView(int position, View convertView, ViewGroup parent) {
        View v = super.getView(position, convertView, parent);
        v.setBackgroundColor(position % 2 == 0 : 0xff000000, 0xffffffff);
    }
}

This code is for the when you select the listitem. 此代码适用于您选择listitem的时间。

Try this code... 试试这个代码......

listview.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> myAdapter, View myView, int pos, long mylng) {

             if( pos == 1) {
                   // to change the listview background
                   listview.setBackgroundColor(getResources().getColor(R.color.your_color_id));

                   // to change the selected item background color
                   myView.setBackgroundColor(getResources().getColor(R.color.your_color_id));
             }
            }
          });

Good luck. 祝好运。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM