I am new to Android programming.
My question is what is the best way to determine the width and height of a subview?
I am writing an application which includes a piano keyboard for input.
I have a custom view, PianoKeyboardView. I need to know the dimensions of my View in order to draw the keyboard. If I stuff the width and height from the following code into my PianoKeyboardView my piano keyboard draws OK.
Display display = ((WindowManager) this
.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
int width = display.getWidht();
int height = display.getHeight();
Obviously I don’t want to do this.
I created a default android application in Eclipse and selected the FullScreen option. The default code for onCreate is:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fullscreen);
final View controlsView = findViewById(R.id.fullscreen_content_controls);
final View contentView = findViewById(R.id.fullscreen_content);
When I call getWidth() and getHeight() on the default Views, I get 0’s.
int width = controlsView.getWidth();
int height = controlsView.getHeight();
width = contentView.getWidth();
height = contentView.getHeight();
My PianoKeyboardView width and height is also 0, and that is my problem.
My activity_fullscreen.xml sets the width and height for all the views as “match_parent”
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true" >
<LinearLayout
android:id="@+id/fullscreen_content_controls"
style="?buttonBarStyle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom|center_horizontal"
android:background="@color/black_overlay"
android:orientation="horizontal"
tools:ignore="UselessParent" >
<com.application.piano.PianoKeyboardView
android:id="@+id/keyboard_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
/>
Thanks.