Androidプログラミング 動的に生成したViewの大きさを他のViewに合わせたい
ITCreate Advent Calendar 15日目
本題
Viewを生成する
private TextView textview; . . . textview = new TextView(this); textView.setId(text_view); textViewID = textView.getId(); textView.setText("てきとうなもじ");
TextViewにしてあるが、なんでもいける(はず)
合わせたいViewをxmlファイルで生成
<TextView android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/size_view">
widthとheightはお任せ
xmlファイルで生成したViewの大きさを取得する
@Override public void onWindowFocusChanged(boolean hasFocus) { TextView tx = (Textview) findViewById(R.id.size_text); int txWidth = tx.getWidth(); int txHeight = tx.getHeight(); }
注意しないといけないのは、onCreateの中でやってしまうとレイアウトが生成される前に、getWidthがはしるので0が代入される
onWindowFocusChangedはレイアウト生成後に実行されるので、この中で
合わせる
@Override public void onWindowFocusChanged(boolean hasFocus) { TextView tx = (Textview) findViewById(R.id.size_text); int txWidth = tx.getWidth(); int txHeight = tx.getHeight(); textView.setWidth(txWidth); textView.setHeight(txHeight); }
これでたぶんいける(簡単)
TextViewでやる分には楽だが、popupWindowでやろうとしたときに大変な目にあったのでAdvent Calendarついでにメモ
popupWindowでやるにはtextView.setWidthあたりのところを
popupWindow(txWindth, txHeight)
こうしたらいける(はず)
以上