我想獲取在activity_main.xml中定義的View的尺寸,以Bitmap基于高度和寬度創(chuàng)建一個。將它們寫入show textView0或停止應(yīng)用。我檢查了此視圖是否為null,但不是。我可以這樣獲取視圖尺寸嗎?這是代碼:@Overrideprotected 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" />
3 回答

波斯汪
TA貢獻(xiàn)1811條經(jīng)驗 獲得超4個贊
您可以嘗試此解決方案
int height;
int width;
ViewTreeObserver viewTreeObserver = view.getViewTreeObserver();
viewTreeObserver .addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
@Override public void onGlobalLayout () {
view.getViewTreeObserver().removeGlobalOnLayoutListener(this);
height = view.getLayoutParams().height;
width = view.getLayoutParams().width;
}
});
添加回答
舉報
0/150
提交
取消