在MainActivity中检查View的尺寸

我想获取在activity_main.xml中定义的View的尺寸,以Bitmap基于高度和宽度创建一个。将它们写入show textView0或停止应用。我检查了此视图是否为null,但不是。我可以这样获取视图尺寸吗?


这是代码:


@Override

protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_main);


    TextView textView = (TextView) findViewById(R.id.textView);


    View view = (View) findViewById(R.id.view);

    int x = view.getMeasuredWidth();

    int y = view.getHeight();

    int radius = 10;


    textView.setText(view.getHeight());


// if (view == null) textView.setText("View is null");

// else textView.setText("View is not null");


    Bitmap bitmap = Bitmap.createBitmap(100, 100, Bitmap.Config.ARGB_8888);

这是actvity_main.xml:


<View

    android:id="@+id/view"

    android:layout_width="400dp"

    android:layout_height="400dp"

    android:layout_marginLeft="44dp"

    android:layout_marginStart="44dp"

    android:layout_marginTop="136dp"

    android:background="@color/green"

    app:layout_constraintStart_toStartOf="parent"

    app:layout_constraintTop_toTopOf="parent" />


<TextView

    android:id="@+id/textView"

    android:layout_width="209dp"

    android:layout_height="48dp"

    android:layout_marginLeft="44dp"

    android:layout_marginStart="44dp"

    android:layout_marginTop="28dp"

    android:text="TextView"

    app:layout_constraintStart_toStartOf="parent"

    app:layout_constraintTop_toTopOf="parent" />


富国沪深
浏览 151回答 3
3回答

波斯汪

您可以尝试此解决方案int height;int width;ViewTreeObserver viewTreeObserver = view.getViewTreeObserver();&nbsp;viewTreeObserver .addOnGlobalLayoutListener(new OnGlobalLayoutListener() {&nbsp; &nbsp; @Override public void onGlobalLayout () {&nbsp; &nbsp; &nbsp; &nbsp; view.getViewTreeObserver().removeGlobalOnLayoutListener(this);&nbsp; &nbsp; &nbsp; &nbsp; height = view.getLayoutParams().height;&nbsp; &nbsp; &nbsp; &nbsp; width = view.getLayoutParams().width;&nbsp; &nbsp; }});
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java