简体   繁体   English

更改Android ListActivity onListItemClick中项目的背景颜色

[英]Change background color of an item in Android ListActivity onListItemClick

I know it sounds very simple, and there are questions about this. 我知道这听起来很简单,对此有疑问。 But none of it could solve my problem. 但它都不能解决我的问题。 So here we go: 所以我们走了:

I want to change background color of a list item in a ListActivity when user clicks on it, and change it back to original color when user clicks again (ie Select/Unselect item sort of look) 我想在用户点击时更改ListActivity列表项的背景颜色,并在用户再次单击时将其更改回原始颜色(即选择/取消选择项目类型)

I tried using getChildAt, it works perfectly if I have all the items visible in one screen without having to scroll. 我尝试使用getChildAt,如果我在一个屏幕上看到所有项目而不必滚动,它就能很好地工作。

Code: 码:

getListView().getChildAt(position).setBackgroundColor(Color.CYAN);

The problem begins when I have more items in the list and user has to scroll through them. 当我在列表中有更多项目并且用户必须滚动它们时,问题就开始了。 Once background for an item is changed, The background color shows up on the newly visible items as I scroll. 一旦项目的背景发生变化,当我滚动时,背景颜色会显示在新显示的项目上。 Also, the getChildAt(position) returns null (and hence a NullPointerException ) when clicking again on the item. 此外,再次单击该项时, getChildAt(position)将返回null (因此返回NullPointerException )。

Can anyone please help me with a simple code that helps me change background color of a list item? 任何人都可以帮我一个简单的代码,帮助我改变列表项的背景颜色?

Thanks in advance! 提前致谢!

Sure thing. 当然可以。 I would do this in the getView() method of a custom ListAdapter . 我会在自定义ListAdaptergetView()方法中执行此ListAdapter

MyAdapter extends SimpleAdapter {
    private ArrayList<Integer> coloredItems = new ArrayList<Integer>();

    public MyAdapter(...) {
        super(...);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View v = super.getView(position, convertView, parent);

        if (coloredItems.contains(position)) {
            v.setBackgroundColor(Color.CYAN);
        } else {
            v.setBackgroundColor(Color.BLACK); //or whatever was original
        }

        return v;
    }
}

Update coloredItems when a list item is clicked. 单击列表项时更新coloredItems

@Override
public void onListItemClick(ListView l, View v, int position, long id) {
    if (coloredItems.contains(position)) {
        //remove position from coloredItems
        v.setBackgroundColor(Color.BLACK); //or whatever was original
    } else {
        //add position to coloredItems
        v.setBackgroundColor(Color.CYAN);
    }
}

If you are dealing with ListFragment then this code will be helpful, 如果您正在处理ListFragment那么此代码将有所帮助,

  @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        if (view != null) {
            getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
            getListView().setDescendantFocusability(ListView.FOCUS_AFTER_DESCENDANTS);
            catagoryValueListView=getListView();
            catagoryValueListView.setOnItemClickListener(new OnItemClickListener() {

             @Override
             public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                 if (ColoredView != null)
                     ColoredView.setBackgroundColor(Color.WHITE); //original color

                 view.setBackgroundColor(Color.BLUE); //selected color
                 ColoredView = view;
                                  }
        });
    }

}

What I do is I create an xml file called ie list_background and put it in the drawable folder. 我所做的是创建一个名为ie list_background的xml文件并将其放在drawable文件夹中。

The xml looks like this: xml看起来像这样:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
   <item android:drawable="@color/list_selected" android:state_pressed="true" />
   <item android:drawable="@android:color/white" />
</selector>

And in the xml code for the ListView's item I put this xml as the items background ie 在ListView的项目的xml代码中,我把这个xml作为项目背景即

item.xml: item.xml:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
          style="@style/Fill"
          android:background="@drawable/list_background">

     <!-- Your layout here -->
</RelativeLayout>

style=@style/Fill is only a short cut i made for android:layout_height="match_parent" and android:layout_width="match_parent style = @ style / Fill只是我为android制作的捷径:layout_height =“match_parent”和android:layout_width =“match_parent

Then in onListItemCLick: 然后在onListItemCLick中:

public void onListItemClick(ListView l, View v, int position, long id) {
    v.setPressed( !v.isPressed ) //Toggle between colors of the view
}

Simply you can do it like this in onListItemClick method 你可以在onListItemClick方法中这样做

@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
    super.onListItemClick(l, v, position, id);

    for (int a = 0; a < l.getChildCount(); a++) {
        l.getChildAt(a).setBackgroundColor(Color.TRANSPARENT);
    }

    ColorDrawable colorDrawable1 = new ColorDrawable(
            Color.parseColor("#A0A3A0"));
    v.setBackgroundDrawable(colorDrawable1);   

    if (position == 0) {
        Intent i = new Intent(MainActivity.this, NewActivity.class);

        startActivity(i);
    }

}

this is how I did it: 这就是我做到的:

create a global variable View ColoredView ; 创建一个全局变量View ColoredView ; then when you setOnItemClickListener for your ListView , do this: 然后当你为ListView setOnItemClickListener时,执行以下操作:

MenuList.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (ColoredView != null)
                    ColoredView.setBackgroundColor(Color.WHITE); //original color

                view.setBackgroundColor(Color.BLUE); //selected color
                ColoredView = view;
            }
        });

it's the simplest way in my opinion. 这是我认为最简单的方法。

Thanks heycosmo. 谢谢heycosmo。 your solution solved my problem. 你的解决方案解决了我的问

Have no clue why we should set background in 2 places. 不知道为什么我们应该在2个地方设置背景。

1. Adapter's getView() 1.适配器的getView()

@Override
public View getView(int position, View convertView, ViewGroup parent) {
     ....
     ....
     ....
        if(arrayBools[position]) {
            view.setBackgroundColor(Common.colorBkgroundSelected);
        }
        else{
            view.setBackgroundColor(Common.colorBkgroundNormal);            
        } 
     ....
     ....
     ....
}

2. ListActivity's onListItemClick(). 2. ListActivity的onListItemClick()。

@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
      super.onListItemClick(l, v, position, id);       
      arrayBools[position] = ( arrayBools[position] ? false : true );

     if(arrayBools[position]) {
         v.setBackgroundColor(colorBkgroundSelected);
     }
     else{
        v.setBackgroundColor(colorBkgroundNormal);          
     }    
}

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

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