使用可能なスペースを埋めるために線形レイアウトで画像をスケーリングしようとしていますが、レイアウトの幅に対して取得している値がわかりません。main.xml レイアウト ファイルの関連部分は次のとおりです。
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/LeftButtonsLayout"
android:layout_width="0dip"
android:layout_height="fill_parent"
android:layout_weight="10"
android:orientation="vertical" >
<TextView
android:id="@+id/Jump"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/jump"
android:textStyle="bold"
android:padding="5dip"
/>
<ImageView
android:id="@+id/JumpButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:adjustViewBounds="true"
android:src="@drawable/jump"
android:contentDescription="@string/jump"
android:padding="5dip"
/>
<LinearLayout
デバッグ出力がある私のアクティビティの onCreate() メソッドは次のとおりです。
public void onCreate (Bundle savedInstanceState) {
setContentView(R.layout.main);
LinearLayout leftButtonsLayout = (LinearLayout) findViewById(R.id.LeftButtonsLayout);
imageView = (ImageView) findViewById(R.id.ResetButton);
Log.d("DEBUG", CLASS_NAME + "scaleLeftButtonsLayoutContents: \n" +
"linear layout height: " + leftButtonsLayout.getHeight() + "\n" +
"text height: " + ((TextView)findViewById(R.id.Jump)).getHeight() + "\n" +
"image height: " + imageView.getLayoutParams().height);
}
1) Log.d() デバッグ出力の後に setContentVew() 呼び出しを配置すると、Null Pointer Exception が発生します。なんで?ビューで使用される前に LinearLayout にメモリが割り当てられていませんか?
2) 私が見るプリントは次のとおりです: 線形レイアウトの高さ: 0 テキストの高さ: 0 画像の高さ: -2 ここで何が間違っていますか? デバイスの画面に imageView が表示されているので、ここで適切な値が表示されることを期待していました。
3) imageView.getLayoutParams().height = newHeight を使用して画像をスケーリングすることを計画していました。そうする権利はありますか?これを行うと、画面上の imageView が自動的に更新されますか、それとも setContentView() を再度実行する必要がありますか?
よろしくお願いします。
アップデート
皆様、ご回答ありがとうございます。アクティビティの onWindowFocusChanged() メソッドをオーバーライドしましたが、以下のネストされた ImageView のサイズを確認すると、-2 と報告されます。サイズ変更は機能しますが、正常な値であるはずなのになぜ -2 なのか不思議です。私のコードは次のとおりです。
@Override
public void onWindowFocusChanged (boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
if (hasFocus)
scaleLeftButtonsLayoutContents();
}
private void scaleLeftButtonsLayoutContents () {
LinearLayout leftButtonsLayout = (LinearLayout)findViewById(R.id.LeftButtonsLayout);
imageView = (ImageView) findViewById(R.id.JumpButton);
Log.d("TAG", CLASS_NAME + "JumpButton.height " + imageView.getLayoutParams().height);
imageView.getLayoutParams().height = verticalSpaceAvailable;
imageView.getLayoutParams().width = verticalSpaceAvailable;
leftButtonsLayout.requestLayout();
}
これにより次の出力が生成されます: JumpButton.height -2
サイズを変更すると正常な画像が生成されますが、最初の高さが -2 なのはなぜですか?