【问题标题】:Textview Text Color Inside ListviewListview内的Textview文本颜色
【发布时间】:2012-09-23 22:58:19
【问题描述】:

我正在编写一个应用程序来检查我们的“网络服务”并返回“托管”或“非托管”状态,我在列表视图中保留了一个正在运行的搜索历史记录(直到用户清除它),这一切正常。

我想做的是,如果状态是“托管”,我希望单个 textview 项目为绿色,如果它是“未托管”,我希望单个项目为红色。

    //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); 

上面的代码实际上把整个listview变成了最后一个搜索项的颜色。 (例如,如果最后一个搜索结果为“托管”结果 - 整个项目列表变为绿色,而不仅仅是单个项目)。

谁能指出我正确的方向。

【问题讨论】:

  • 也许我遗漏了一些东西,但我不明白为什么 _currentStatus 对于不同的视图会有所不同。似乎它必须始终返回“托管”
  • 您说得对,先生,我需要从传递给列表视图的字符串中解析出托管或非托管。

标签: android listview colors textview android-arrayadapter


【解决方案1】:

在我看来你的问题的根源是这个电话:

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

此调用中没有任何内容表明您正在检查哪个列表元素,因此它总是会为列表中的每个视图返回相同的结果。您应该传入 position 参数并使用它来获取相关列表条目的状态(您如何执行此操作取决于您实际获取列表元素状态的方式,但这应该不会太难)。

【讨论】:

  • 你是对的。它在列表中运行并更改所有项目,因为 sharedpref 是“托管的”,所以所有项目都是绿色的。我需要对每个项目进行评估,我会解析出字符串并修复它。谢谢!!!
【解决方案2】:

试试下面的代码

if (_currentStatus.equals("Managed")){
        textView.setTextColor(0xFF008B45);
    } else {
        textView.setTextColor(0xFFB0171F);
    }

【讨论】:

    【解决方案3】:

    试试下面的代码:

           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;
    

    【讨论】:

    • 这如何解决问题? getView 为列表中的每个元素单独调用,将 setTextColor 调用移至 if 语句不会改变任何内容。
    • 是的 getView 是为列表中的每个元素单独调用的。上面的代码对我有用,
    猜你喜欢
    • 1970-01-01
    • 2015-10-24
    • 1970-01-01
    • 2011-05-30
    • 2015-07-12
    • 1970-01-01
    • 2014-02-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多