java - 根据 ArrayList<HashMap<String, String>> 中的值更改 TextView 的颜色

标签 java android xml arraylist colors

您好,我有以下元素的 ArrayList,它从 xml 文件中获取值。之后,数据被馈送到一个简单的适配器并显示它。我希望 R.id.stock_mov 的颜色根据值而改变。如果是负值->红色,如果是正值则绿色。我找不到如何做到这一点的方法

         ArrayList<HashMap<String, String>> stackItems = new ArrayList<HashMap<String, String>> ();
    // final HashMap<String, String> dspStack = new HashMap<String, String>();

     NodeList stock = doc.getElementsByTagName("stock");
        for (int i=0; i<stock.getLength(); i++){
            HashMap<String, String> map = new HashMap<String, String>();
            Node nodeCurr = stock.item(i);
             Element currElmnt = (Element) nodeCurr;
             map.put("name", parser.getValue(currElmnt, "name"));
             map.put("val", parser.getValue(currElmnt, "val"));
             map.put("mov", parser.getValue(currElmnt, "mov"));
             stackItems.add(map);

        }

        ListAdapter adapter = new SimpleAdapter(this, stackItems,
                R.layout.stocks_def_item,
                new String[] { "name", "val", "mov"}, new int[] {
                        R.id.stock_name,

                        if(stackItems.get(i)>0)
                        R.id.stock_val,
                        R.id.stock_mov,});

        setListAdapter(adapter);


}

最佳答案

您需要在适配器getView()方法中执行此操作。让它检查股票的值(value),然后相应地设置其各自的颜色:

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    // use the ------- ^position^ parameter to access the current stock's value
    double currentStockValue = ...;

    TextView stockMove = (TextView)convertView.findViewById(R.id.stock_mov);

    if( currentStockValue > 0) // if the current stock's value is positive
        stockMove.setTextColor(Color.parseColor("#6AC36A")); // set text color to green
    else
        stockMove.setTextColor(Color.parseColor("#FF3300")); // set text color to red   

    ...
    return convertView;
}

关于java - 根据 ArrayList<HashMap<String, String>> 中的值更改 TextView 的颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29280423/

相关文章:

android - 如果我放置支持更高 API 11+ 的 XML 属性,API 8 会发生什么

xml - 为什么 XSD 说我的元素不完整?

xml - XQuery:同一模块中有两个 namespace ?

java - 如何在 PHP 中并行发出多个 HTTP 请求?

java - 无法运行循环 HashMap 的方法

java - 在java中使用变量创建随机整数

java - 尽管优先级设置为最高,但在 Android 4.4 及更高版本上消息不会被阻止。有解决方法吗?

Java:如何将值从类/bean 传递到 servlet

android - 部署到 App Engine 问题 - 您必须登录才能执行此操作

xml - 对 Perl Handlers 有很好的介绍吗?