Android listview, change attributes of particular view

孤人 提交于 2020-01-26 02:17:27

问题


on my listview I am scrolling to a particular position of it like this

getListView().smoothScrollToPosition(scrollposition+1);

but I also want to "highlight" this view. How do I access the attributes of this particular view to change the background color of this position.

Here is the listview code

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent" android:layout_height="wrap_content" android:id="@+id/currentText"
    android:padding="10dp" android:textSize="24sp" android:textColor="#000000" android:background="@drawable/bglistitem"
    android:gravity="center_vertical|center_horizontal">
</TextView>

It is just a textview with a background. I tried doing this:

View highlightView = getListView().getChildAt(scrollposition);
highlightView.setDrawingCacheBackgroundColor(Color.parseColor("#2580b0"));
TextView currentText = (TextView)highlightView.findViewById(R.id.currentText);
currentText.setTextColor(Color.parseColor("#ffffff"));

but it always crashes! I can understand why setDrawingCacheBackgroundColorcrashes, but even getting the textview from that view crashes.

Help?


回答1:


I ran into this issue a few weeks ago.

You should not use the getChildAt() function of the ListView. If you use getChildAt(5), for example, it will pull the 5th view that is visible.

To solve the issue, I had to create a custom adapter that overrode getView() and set the colors based on what I sent across.

  public class RunAdapter extends SimpleAdapter {

public RunAdapter(Context context, List<HashMap<String, String>> items,
        int resource, String[] from, int[] to) {
    super(context, items, resource, from, to);
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    View view = super.getView(position, convertView, parent);
    TextView txtView = (TextView) view.findViewById(R.id.lstTurnout);
        if (txtView.getText().toString().contains("BLU")) {
            txtView.setBackgroundColor(Color.rgb(0x00, 0x00, 0xaa));
            txtView.setText(txtView.getText().toString().replace("BLU", ""));
        } else {
            txtView.setBackgroundColor(Color.rgb(0xaa, 0x00, 0x00));
            txtView.setText(txtView.getText().toString().replace("RED", ""));
        }
  }

It isn't the prettiest method, but it works! Depending on what color I wanted the TextView to be, I passed 'BLU', or 'RED' Then in the getView, I check to see which the string contains and change the color accordingly.

Hope I was some help, Good Luck!

Edit Constructor as per request




回答2:


getChildAt needs an index, not a scrollpostion.

Regards, Stphane



来源:https://stackoverflow.com/questions/7086133/android-listview-change-attributes-of-particular-view

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!