开发者

Android listview, change attributes of particular view

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|cent开发者_如何转开发er_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?


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


getChildAt needs an index, not a scrollpostion.

Regards, Stphane

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜