【问题标题】:Changing textview color in listview item dynamically动态更改列表视图项中的文本视图颜色
【发布时间】:2013-02-16 12:40:31
【问题描述】:

我正在使用简单的光标适配器从具有自定义布局的列表视图中的视图中获取所有记录。我想显示优先级文本视图以根据文本更改颜色,例如,如果优先级高,则为红色,如果优先级高,则为绿色,如果优先级低,则为黄色。有什么方法可以做到。我对 android 很陌生

我的列表视图代码

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 工作正常,但如何编写代码来更改 listview 项中的 textview 颜色

提前致谢

【问题讨论】:

    标签: android sqlite


    【解决方案1】:

    您需要使用自定义光标适配器,因为您可以动态更改内容

    这里我举个例子,在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;
    }
    

    }

    【讨论】:

    • 先生,我正在从 SQlite 数据库视图中获取数据到列表视图中,我想通过代码更改优先级文本颜色
    • 先生,对不起,我无法理解这个概念
    • 不要使用 SimpleCusrsorAdapter,而是使用扩展 CursorAdapter 的 cusom adpater
    • 我使用光标适配器完成我的工作,非常感谢 Kapil 大桶
    【解决方案2】:

    我会考虑使用BaseAdapter。这将使您对每一行有更多的控制。

    【讨论】:

    • 先生有没有办法根据文本在列表视图项中更改文本视图颜色
    • 是的,使用 BaseAdapter,您可以更改显示的视图以及您对视图的操作。
    • sir from view i 表示 SQlite 数据库视图,我从中获取数据到列表视图
    • By View 我指的是Android Views,比如TextView。使用 BaseAdapter,您将能够动态设置 TextView 的颜色。
    • 是否有一些代码 sn-p 我真的不理解这个概念
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多