Android 如何以编程方式重写XML高度属性?

Android 如何以编程方式重写XML高度属性?,android,android-layout,Android,Android Layout,我有一个线性布局的活动。它有两个视图-一个按钮和下面的一个自定义视图。我希望能够以编程方式设置自定义的高度(它将在启动期间从绘制在上面的图像计算)。我想让它上面的按钮填满剩余的空间。如何做到这一点? 到目前为止,我有以下XML代码: <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/too

我有一个线性布局的活动。它有两个视图-一个按钮和下面的一个自定义视图。我希望能够以编程方式设置自定义的高度(它将在启动期间从绘制在上面的图像计算)。我想让它上面的按钮填满剩余的空间。如何做到这一点? 到目前为止,我有以下XML代码:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              xmlns:tools="http://schemas.android.com/tools"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:background="#0099cc"
              android:orientation="vertical"
              tools:context="eu.example.app.PianoActivity">

    <Button
        android:id="@+id/dummy_button"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:text="@string/dummy_button"/>

    <eu.example.app.PianoView
        android:id="@+id/pianoView"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:keepScreenOn="true"/>

</LinearLayout>
但不管我把它放在哪里,它都没有做任何事情——不管是在视图的构造函数中还是在onDraw()方法中

//编辑: 附加信息:自定义视图直接从视图继承,并仅重写onDraw()方法,以便在自身上绘制一些内容。

您应该使用

public void onWindowFocusChanged(boolean hasFocus) {}

方法设置高度和宽度。

在xml中为线性布局添加id属性,如下所示:-

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              xmlns:tools="http://schemas.android.com/tools"
              android:id="@+id/liLay"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:background="#0099cc"
              android:orientation="vertical"
              tools:context="eu.example.app.PianoActivity">
<Button ---/>
<eu.example.app.PianoView---/>
</LinearLayout>
现在以编程方式设置布局参数

LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(100, 100);
liLay.setLayoutParams(layoutParams);
这将对您有所帮助。

使用以下方法:

layoutParams.height = 130;
yourLayout.setLayoutParams(layoutParams);

旁注:如果您的
PianoView
扩展了
ImageView
,那么您可以完全用XML来完成这项工作。请看详细信息。事实上,更多关于PianoView的信息可能会有所帮助。你能公布消息来源吗?它从何而来?这是什么习俗?它是否覆盖onMeasure()或onLayout()?请参考此线程@Fabian Tamp,因为没有具有任何附加信息值的源。它直接从视图继承,到目前为止只重写onDraw()方法在其上绘制某些内容。
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(100, 100);
liLay.setLayoutParams(layoutParams);
layoutParams.height = 130;
yourLayout.setLayoutParams(layoutParams);