简体   繁体   中英

How can I get the background color of an item from gridview in Android?

I need to get the background color of an item programmatically, in Java, to do more things. Is there any possibility to do so?

This is my code:

        gridView = findViewById(R.id.gridViewServices);
        listView = findViewById(R.id.listViewServices);

        // Grid View
        GridAdapter adapter = new GridAdapter(ServicesActivity.this, serviceList);
        txtService = findViewById(R.id.textServices);
        gridView.setAdapter(adapter);

        // List View
        serviceListAdd = new ArrayList<String>();
        arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, serviceListAdd);
        listView.setAdapter(arrayAdapter);

        ColorDrawable gridViewColor = (ColorDrawable) gridView.getBackground();
        int colorId = gridViewColor.getColor();
        System.out.println("Colour: " + colorId);

Edit: Your solution, @majuran, throws Exception:

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'int android.graphics.drawable.ColorDrawable.getColor()' on a null object reference

To be honest, I don't know why, because I am using gridView before this line to set the Adapter and it works fine.

Update for NullPointerException

    int color = Color.TRANSPARENT;
    Drawable background = gridView.getBackground();
    if (background instanceof ColorDrawable)
        color = ((ColorDrawable) background).getColor();

Getting colour in gridview

GridView gridView = findViewById(R.id.my_grid_view);
ColorDrawable gridViewColor = (ColorDrawable) gridView.getBackground();
int colorId = gridViewColor.getColor();

see Ans 1 , Ans 2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM