【问题标题】:Change color of textview based on values from ArrayList<HashMap<String, String>>根据 ArrayList<HashMap<String, String>> 中的值更改文本视图的颜色
【发布时间】:2015-05-30 14:02:45
【问题描述】:

您好,我有以下元素的 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);


}

【问题讨论】:

  • 那段代码没有编译,对吧?
  • 能否请您展示您的stocks_def_item XML 布局?

标签: java android xml arraylist colors


【解决方案1】:

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

@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;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-10-05
    • 2014-01-02
    • 2012-07-13
    • 1970-01-01
    • 2013-07-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多