【问题标题】:Change background color of ListView specific row without CustomAdapter在没有 CustomAdapter 的情况下更改 ListView 特定行的背景颜色
【发布时间】:2017-04-15 07:13:43
【问题描述】:

我正在尝试更改 ListView 中特定行的背景颜色以匹配我的 List<String> hexcodeList 中的特定颜色,其中包含颜色十六进制代码。但是,我没有为此使用 CustomAdapter,而是从ArrayAdapter 覆盖getView。我希望第一行有我列表的第一种颜色,第二行有第二种颜色,依此类推。我对 Java 很陌生,我的第一个想法是使用 for 语句,所以下面的代码是我尝试但没有成功的代码,因为这会使用 hexcodeList 的最后一种颜色更改所有行的背景颜色。

ListView CoresListView = (ListView) findViewById(R.id.ListViewId);  
final ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, hexcodeList){
    @Override
    public View getView(int position, View convertView, ViewGroup parent){
        View view = super.getView(position,convertView,parent);
        for (position = 0; position < hexcodeList.size(); position++) {
            view.setBackgroundColor(Color.parseColor(hexcodeList.get(position)));
        }
        return view;
    }
};

CoresListView.setAdapter(adapter);

【问题讨论】:

  • 在循环中它将为所有项目设置颜色,因此您需要使用 if 语句。具体职位。

标签: java android listview


【解决方案1】:

在创建的每个视图上,您​​都在循环遍历列表并设置所有颜色,以便为每个视图设置最后一种颜色。

去掉循环,只写这个:

view.setBackgroundColor(Color.parseColor(hexcodeList.get(position)));

getView(...) 为每个视图调用,因此需要一个循环。

【讨论】:

    【解决方案2】:

    您不需要 for 循环,因为 getView() 总是为每个行项目视图调用。

    试试这个:

    ListView CoresListView = (ListView) findViewById(R.id.ListViewId);  
    final ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, hexcodeList){
        @Override
        public View getView(int position, View convertView, ViewGroup parent){
            View view = super.getView(position,convertView,parent);
            view.setBackgroundColor(Color.parseColor(hexcodeList.get(position)));
    
            return view;
        }
    };
    
    CoresListView.setAdapter(adapter);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-10-13
      • 1970-01-01
      • 1970-01-01
      • 2012-04-06
      • 2019-06-14
      • 2021-05-04
      • 1970-01-01
      相关资源
      最近更新 更多