确定视图的宽度和高度

时间:2012-12-28 04:18:10

标签: android

我是Android编程新手。

我的问题是确定子视图宽度和高度的最佳方法是什么?

我正在编写一个包含钢琴键盘的应用程序。

我有一个自定义视图,PianoKeyboardView。 我需要知道我的视图的尺寸才能绘制键盘。 如果我将以下代码中的宽度和高度填入我的PianoKeyboardView,我的钢琴键盘就可以了。

Display display = ((WindowManager) this 
        .getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();

    int width = display.getWidht();
    int height = display.getHeight();

显然我不想这样做。

我在Eclipse中创建了一个默认的android应用程序并选择了FullScreen选项。 onCreate的默认代码是:

@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);

当我在默认视图上调用getWidth()和getHeight()时,我得到0。

    int width = controlsView.getWidth();
    int height = controlsView.getHeight();
    width = contentView.getWidth();
    height = contentView.getHeight();

我的PianoKeyboardView宽度和高度也是0,这是我的问题。

我的activity_fullscreen.xml将所有视图的宽度和高度设置为“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"
        />

感谢。

2 个答案:

答案 0 :(得分:0)

@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);

    ViewTreeObserver viewTreeObserver = controlsView.getViewTreeObserver();
    viewTreeObserver.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
            @Override
            public boolean onPreDraw() {
                int width = controlsView.getWidth();
                int height = controlsView.getHeight();
                return true;
            }
    });

希望这可以帮助你......

答案 1 :(得分:0)

您可以尝试基于此的内容......(从my answer to a related question复制)。

我使用以下技术 - 发布将在创建视图时执行的onCreate()的runnable:

    contentView = findViewById(android.R.id.content);
    contentView.post(new Runnable()
    {
        public void run()
        {
            contentHeight = contentView.getHeight();
        }
    });

此代码将在onCreate()完成后在主UI线程上运行。那时视图有一个大小。

相关问题