【问题标题】:Creating a ListView and setting the background color of a view in each row创建 ListView 并在每一行中设置视图的背景颜色
【发布时间】:2010-04-04 19:17:32
【问题描述】:

我正在尝试实现一个 ListView,它由包含左侧 View 和右侧 TextView 的行组成。我希望能够根据它在 ListView 中的位置来更改第一个视图的背景颜色。以下是我目前所拥有的,但似乎没有任何原因。

public class Routes extends ListActivity {
    String[] ROUTES;
    TextView selection;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        ROUTES = getResources().getStringArray(R.array.routes);

        setContentView(R.layout.routes);
        setListAdapter(new IconicAdapter());
        selection=(TextView)findViewById(R.id.selection);

    }

    public void onListItemClick(ListView parent, View v, int position, long id) {
        selection.setText(ROUTES[position]);

    }

    class IconicAdapter extends ArrayAdapter<String> {
        IconicAdapter() {
            super(Routes.this, R.layout.row, R.id.label, ROUTES);
        }
    }

    public View getView(int position, View convertView, ViewGroup parent) {

        LayoutInflater inflater = getLayoutInflater();
        View row = inflater.inflate(R.layout.row, parent, false);
        TextView label = (TextView) row.findViewById(R.id.label);

        label.setText(ROUTES[position]);

        View icon = (View) row.findViewById(R.id.icon);

        switch(position){

        case 0:
            icon.setBackgroundColor(R.color.Red);
            break;
        case 1:
            icon.setBackgroundColor(R.color.Red);
            break;
        case 2:
            icon.setBackgroundColor(R.color.Green);
            break;
        case 3:
            icon.setBackgroundColor(R.color.Green);
            break;
        case 4:
            icon.setBackgroundColor(R.color.Blue);
            break;
        case 5:
            icon.setBackgroundColor(R.color.Blue);
            break;
        }

        return(row);
    }

}

感谢您的任何意见,如果您有任何问题,请随时提问!

谢谢, 抢

【问题讨论】:

    标签: android


    【解决方案1】:

    发现两个问题:

    1) getView() 方法不在我创建的内部类中,因此它甚至没有被调用。

    2) 我需要调用 setBackgroundResource(),而不是调用 setBackgroundColor()。

    它现在可以工作了。

    【讨论】:

      【解决方案2】:

      也许图标完全不透明?没有任何背景可见,因此更改背景颜色将无效?

      【讨论】:

      • 感谢您的建议,这不是问题,但我一直很感激任何意见。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-05-09
      • 1970-01-01
      • 1970-01-01
      • 2011-11-18
      • 1970-01-01
      • 2012-05-15
      • 2016-05-31
      相关资源
      最近更新 更多