当前位置: 动力学知识库 > 问答 > 编程问答 >

java - how to set different background colour for different items in a gridview?

问题描述:

I want to set different background colour for each gridview items, I have tried like this

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.places_gridview);

prepareList();

mAdapter = new PlacesGridViewAdapter(this, listTitle, listIcon);

gridview = (GridView) findViewById(R.id.gridView);

gridview.setAdapter(mAdapter);

}

public void prepareList() {

listTitle = new ArrayList<String>();

listTitle.add("Hotel");

listTitle.add("Taxi");

listTitle.add("Cafe");

listTitle.add("Train");

listTitle.add("School");

listTitle.add("Parlor");

listTitle.add("Gas");

listTitle.add("Fire");

listIcon = new ArrayList<Integer>();

listIcon.add(R.drawable.hotel);

listIcon.add(R.drawable.taxi_meter);

listIcon.add(R.drawable.cafe);

listIcon.add(R.drawable.train);

listIcon.add(R.drawable.school);

listIcon.add(R.drawable.parlor);

listIcon.add(R.drawable.gas);

listIcon.add(R.drawable.fire_station);

}

I also checked some prevoious stack overflow queries and found they are suggesting like

gridview.getChildAt(1).setBackgroundColor(

Color.parseColor("#001111"));

but it showing null pointer exception in my case

网友答案:

An NPE would suggest that you're attempting to change the background colours in your main activity, which can't be done. In order to change a View of List, or Grid types, you have to do so inside of your [custom] ArrayAdapter and within the getView method, then you'll be able to access it as/when it is inflated. Like:

public View getView(int position, View convertView, ViewGroup parent)
{
    LayoutInflater inflater = (LayoutInflater)this.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View rowView = inflater.inflate(this.layout, parent, false);

    SomeObject obj = (SomeObject)data[position];

    // Then access like so:
    SomeView sv = (SomeView)rowView.findViewById(R.id.some_view);
    // then access methods and properties as you normally would.
}

A good example can be found here: http://www.mkyong.com/android/android-gridview-example/ Hope this helps!

网友答案:

I can't agree more than what @LokiSinclair is saying. Few points to add

  1. Preferably customize your adapter by extending the BaseAdapter
  2. In getView(int position, View convertView, ViewGroup parent) method, you need to set the background resource/color to your returned view depending on your conditions like position based.

As @LokiSinclair was pointing out, the tutorial link is a nice one to start with.

分享给朋友:
您可能感兴趣的文章:
随机阅读: