我想获取在activity_main.xml中定义的View的尺寸,以Bitmap基于高度和宽度创建一个。将它们写入show textView0或停止应用。我检查了此视图是否为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贡献1811条经验 获得超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
提交
取消