简体   繁体   English

动态更改列表视图项中的文本视图颜色

[英]Changing textview color in listview item dynamically

im using simple cursor adapter to fetch all records from a view in listview with custom layout. 我使用简单的光标适配器从具有自定义布局的listview中的视图中获取所有记录。 i want to show the priority textview to change color according to text such as red if priority is high,green if medium and yellow if low.is there some way to do it.im quite new to android 我想显示优先级textview根据文本更改颜色,例如优先级高时为红色,中等时为绿色,如果低则为黄色。有什么方法可以做到这一点。

my code for listview 我的列表视图代码

myList=(ListView) findViewById(R.id.listView1);
    myAdapter.open();

    Cursor cursor = myAdapter.fetchAllView();

    startManagingCursor(cursor);
String []from=new String[]{ DbAdapter.KEY_DESCRIPTION,DbAdapter.KEY_TITLE,DbAdapter.KEY_TASK_PRIORITY,DbAdapter.KEY_CATEGORY_NAME,DbAdapter.KEY_TIME,DbAdapter.KEY_DATE };
int[] to=new int[] { R.id.txtdescription,R.id.txtitem,R.id.txtPriority,R.id.txtcategory,R.id.txttimeOne,R.id.txtDateOne}; 
 myCursorAdapter = new SimpleCursorAdapter(ListItems.this, R.layout.items, cursor,from, to);
myList.setAdapter(myCursorAdapter);

listview works fine but how to write a code to change textview color in listview item listview工作正常,但是如何编写代码以更改listview项目中的textview颜色

thanks in advance 提前致谢

I'd look into using a BaseAdapter . 我会考虑使用BaseAdapter This will give you much more control over each row. 这将使您对每一行有更多的控制。

you need to use use your custom cursor adapter, in that you can change things dyanamically 您需要使用自定义光标适配器,因为您可以动态更改

here I am giving an example, in bindView method change the color of text 这里我举一个例子,在bindView方法中更改文本的颜色

public class MessageAdapter extends CursorAdapter {
private Cursor mCursor;
private Context mContext;
private final LayoutInflater mInflater;


public MessageAdapter(Context context, Cursor c) {
    super(context, c);
    mInflater=LayoutInflater.from(context);
mContext=context;
}

@Override
public void bindView(View view, Context context, Cursor cursor) {

    TextView mobileNo=(TextView)view.findViewById(R.id.mobileNolistitem);
    mobileNo.setText(cursor.getString(cursor.getColumnIndex(TextMeDBAdapter.KEY_MOBILENO)));

    TextView frequency=(TextView)view.findViewById(R.id.frequencylistitem);
    frequency.setText(cursor.getString(cursor.getColumnIndex(TextMeDBAdapter.KEY_FREQUENCY)));

    TextView rowid=(TextView)view.findViewById(R.id.rowidlistitem);
    rowid.setText(cursor.getString(cursor.getColumnIndex(TextMeDBAdapter.KEY_ID)));

}

@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
    final View view=mInflater.inflate(R.layout.message_list_item,parent,false); 
    return view;
}

} }

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

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