-1

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.

Stephan Hogenboom
  • 1,543
  • 2
  • 17
  • 29
Tomas
  • 13
  • 6

1 Answers1

0

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

Community
  • 1
  • 1
majurageerthan
  • 2,169
  • 3
  • 17
  • 30
  • .getBackground returns a Drawable, not a ColorDrawable, so never joins in if, color always be 0 – Tomas Dec 04 '19 at 16:39
  • It means your layout do not have any color, set any color and check again – majurageerthan Dec 04 '19 at 16:45
  • Correct, my layout does not have any color because I set a color when I click, I want to get the color of an item. For example, I put a color when click with this: ```gridView.getChildAt(i).setBackgroundResource(R.drawable.background_border_selected);``` And when click again, i put default color:````gridView.getChildAt(i).setBackgroundResource(R.drawable.background_border); ``` Now, I need how to get that color with a if/else sentence to do other things. For example: if(gridView.getChildAt(i).what-i-need-to-put-here.equals("red)) { // do some things } else { // do other things } – Tomas Dec 04 '19 at 16:50