سؤال

I have the following code:

llColors = (LinearLayout) findViewById(R.id.llColorSpect);
    llColors.setOnTouchListener(llTouch);

    width = llColors.getWidth();
    height = llColors.getHeight();

    Log.i("LAYOUT WIDTH", "width" +width); //shows 0
    Log.i("LAYOUT HEIGHT", "height" +h); //shows the correct height

What makes me confused is why is the LAYOUT WIDTH is 0. In the XML, I set the layout width to match_parent and height to wrap_content.

How do I take the Bitmap that I am decoding below and fill in the layout above width fill_parent? Do I use LayoutParams?

bitmap = BitmapFactory.decodeResource(this.getResources(), R.drawable.palette2);

The XML code is this:

<LinearLayout
    android:id="@+id/llColorSpect"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:background="@drawable/palette2"
    android:layout_alignParentBottom="true" >
</LinearLayout>

What I am trying to accomplish is lehman term is, take the layout and fill it with a background image and use the pixel to get X and Y coordinate.

هل كانت مفيدة؟

المحلول

You are calling getWidth() too early. The UI has not been sized and laid out on the screen yet.

Try getting size after overriding the onWindowFocusChanged() function:

@Override
 public void onWindowFocusChanged(boolean hasFocus) {
  super.onWindowFocusChanged(hasFocus);
  //Here you can get the size!
 }

Have a look at this discussion

If you want your bitmap to match parent height and width you can use this:

LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
imageView.setImageBitmap(bitmap);
imageView.setLayoutParams(params);

Hope this helps :)

نصائح أخرى

As far as the width being 0, the layout may not be finished being drawn yet. I used OnGlobalLayoutListener to know when it had been drawn. Here is a bit of code how I have done it to make my layout a Bitmap so I could print it. A little different but same concept.

@Override 
public void onGlobalLayout() 
{
    String path = null;
        try {
            path = Environment.getExternalStorageDirectory().getPath().toString();
            FileOutputStream out = new FileOutputStream(path + "/testPrint" + "0" + ".png");
            Bitmap bm = Bitmap.createBitmap(root.getDrawingCache(), 0, 0, 
                    root.getWidth(), root.getHeight());                             
            bm.compress(Bitmap.CompressFormat.PNG, 90, out);                
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }   

where root is the inflated layout that I needed to get the width of.

and you can set the listener with something like

ViewTreeObserver vto = view.getViewTreeObserver();
vto.addOnGlobalLayoutListener((OnGlobalLayoutListener) root.getContext());

OnGlobalLayoutListener Docs

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top