简体   繁体   English

如何从 Android 中的 gridview 获取项目的背景颜色?

[英]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.我需要在 Java 中以编程方式获取项目的背景颜色,以执行更多操作。 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:编辑:您的解决方案@majuran 抛出异常:

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'int android.graphics.drawable.ColorDrawable.getColor()' on a null object reference引起: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.老实说,我不知道为什么,因为我在这一行之前使用了 gridView 来设置 Adapter 并且它工作正常。

Update for NullPointerException更新 NullPointerException

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

Getting colour in gridview在gridview中获取颜色

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

see Ans 1 , Ans 2答案 1 ,答案 2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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