android converting XML View to Bitmap without showing it

后端 未结 1 1234
栀梦
栀梦 2021-01-05 04:12

i\'m trying to set a view to my map cluster. i\'m inflating a view from an XML and setting the Text according to cluster size and i want to show that view. in the following

1条回答
  •  天涯浪人
    2021-01-05 05:00

    Your cluster.getLayoutParams() is probably null. First, you need to measure the width/height of your inflated view and then assign to it. Do it as below:

    private Bitmap createClusterBitmap(int clusterSize) {
        View cluster = LayoutInflater.from(context).inflate(R.layout.map_cluster,
                null);
    
        TextView clusterSizeText = (TextView) cluster.findViewById(R.id.map_cluster_text);
        clusterSizeText.setText(String.valueOf(clusterSize));
    
        cluster.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED),
                MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
        cluster.layout(0, 0, cluster.getMeasuredWidth(),cluster.getMeasuredHeight());
    
        final Bitmap clusterBitmap = Bitmap.createBitmap(cluster.getMeasuredWidth(),
                cluster.getMeasuredHeight(), Bitmap.Config.ARGB_8888);
    
        Canvas canvas = new Canvas(clusterBitmap);
        cluster.draw(canvas);
    
        return clusterBitmap;
    }
    

    0 讨论(0)
提交回复
热议问题