1

我有以下代码:

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

让我困惑的是为什么是LAYOUT WIDTH0。在 XML 中,我将布局宽度设置为match_parent,高度设置为wrap_content

如何获取Bitmap下面正在解码的内容并填写宽度 fill_parent 以上的布局?我使用 LayoutParams 吗?

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

XML 代码是这样的:

<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>

我想要完成的是雷曼术语,采用布局并用背景图像填充它,并使用像素来获取 X 和 Y 坐标。

4

2 回答 2

1

至于为width0,layout可能还没有画完。我OnGlobalLayoutListener以前知道它是什么时候画的。这里有一些代码我是如何做layout的,Bitmap所以我可以打印它。有点不同但相同的概念。

@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();
        }   

我需要得到root的膨胀在哪里。layoutwidth

你可以listener用类似的东西设置

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

OnGlobalLayoutListener 文档

于 2014-01-30T19:06:51.607 回答
1

你打电话getWidth()太早了。UI 尚未在屏幕上调整大小和布局。

覆盖onWindowFocusChanged()函数后尝试获取大小:

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

看看这个讨论

如果你想让你的位图匹配父级的高度和宽度,你可以使用这个:

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

希望这可以帮助 :)

于 2014-01-30T18:59:57.260 回答