如何在GridView中更改特定网格元素的颜色?

时间:2018-07-02 17:39:24

标签: android listview gridview parent-child

我正在尝试制作测验应用程序。我需要在网格视图中显示问题编号,并且如果已经尝试过,则更改问题编号的背景颜色(标志= 1)。 我从SQLite数据库中获得尝试问题的标志。如何相应地设置每个网格元素的背景。

这是我的GridView Adapter getView方法

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

    View view;

    LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    if (convertView == null) {

        view = inflater.inflate(R.layout.question_no_layout, null);

        cursor.moveToPosition(position);
        if (cursor!=null && cursor.getPosition()< cursor.getCount()){
            flag = cursor.getInt(cursor.getColumnIndex("Flag"));
           }

        if (flag == 1){
            view.setBackgroundColor(mContext.getResources().getColor(R.color.correct_answer));
        }

        TextView textView = (TextView) view.findViewById(R.id.qnonav_TV);
        textView.setText(String.valueOf(qno[position]+1));

    }
    else {
        view = (View) convertView;
    }

    return view;
}

1 个答案:

答案 0 :(得分:0)

尝试一下:

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View view;

            if (convertView == null) {
                LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                view = inflater.inflate(R.layout.question_no_layout, null);
            } else {
                view = (View) convertView;
            }

            cursor.moveToPosition(position);
            if (cursor!=null && cursor.getPosition()< cursor.getCount()){
                flag = cursor.getInt(cursor.getColumnIndex("Flag"));
            }

            if (flag == 1){
                view.setBackgroundColor(mContext.getResources().getColor(R.color.correct_answer));
            } else {
                view.setBackgroundColor(Color.TRANSPARENT);
            }

            TextView textView = (TextView) view.findViewById(R.id.qnonav_TV);
            textView.setText(String.valueOf(qno[position]+1));

            return view;
        }

希望有帮助!