列表视图中的文本视图文本颜色

3
我正在编写一个应用程序,用于检查我们的“webservice”并返回“Managed”或“Unmanaged”状态,我在listview中保留了一个运行搜索历史记录(直到用户清除它),这一切都很正常。如果状态是“Managed”,我希望单个文本视图项目为绿色,如果是“Unmanaged”,我希望单个项目为红色。
    //This is the String Array which gets populated later.
    ArrayList<String> _searchHistoryList = new ArrayList<String>();

    //Here is where I override the getView to try to change the color.
    listAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, _searchHistoryList) {
    @Override
    public View getView(int position, View convertView,  ViewGroup parent) {
        TextView textView = (TextView) super.getView(position, convertView, parent);

        String _currentStatus = appSettings.getString("current_status", "na");

        int textColor;
        if (_currentStatus.equals("Managed")){
            textColor = R.color.green_text;
        } else {
            textColor = R.color.red_text;
        }
        textView.setTextColor(getResources().getColor(textColor));

        return textView;
    }
};
lvSearchHistory.setAdapter(listAdapter); 

上述代码实际上将整个列表视图变成了最后一个搜索项的颜色。(例如,如果最后一次搜索结果是“已管理”的结果,则整个项目列表将变为绿色,而不仅仅是单个项目)。

有人能指导我正确的方向吗?


1
也许我错了,但我不明白为什么对于不同的视图,_currentStatus会有所不同。看起来它必须始终返回“Managed”。 - digidigo
先生,您说得对。我需要从传递给列表视图的字符串中解析出托管或非托管。 - mr.sean.r
3个回答

2

我认为你问题的根源在于这个调用:

String _currentStatus = appSettings.getString("current_status", "na");

这个调用中没有指示你要检查哪个列表元素,因此它将始终为列表中的每个视图返回相同的结果。你应该传递位置参数并使用它来获取相关列表条目的状态(如何实际获取列表元素的状态取决于具体情况,但不应该太困难)。


你说得对。它正在遍历列表并更改所有项目,因为sharedpref是“管理的”,所以所有项目都是绿色的。我需要逐个评估它,我会解析字符串并修复它。谢谢! - mr.sean.r

1
请尝试以下代码。
if (_currentStatus.equals("Managed")){
        textView.setTextColor(0xFF008B45);
    } else {
        textView.setTextColor(0xFFB0171F);
    }

0

请尝试以下代码:

       int textColor;
    if (_currentStatus.equals("Managed")){
        textColor = R.color.green_text;
     textView.setTextColor(getResources().getColor(textColor));
    } else {
        textColor = R.color.red_text;
       textView.setTextColor(getResources().getColor(textColor));
    }


    return textView;

1
这怎么能修复问题呢?getView会为列表中的每个元素单独调用,将setTextColor调用移动到if语句中也不会改变任何东西。 - Xono
是的,getView方法会为列表中的每个元素单独调用。以上代码对我有效。 - G M Ramesh

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接