动态/以编程方式设置具有可绘制背景的按钮的大小

use*_*030 2 java xml size android drawable

我有一个具有以下属性的按钮:

circle_normal.xml(在res / drawable中)

<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:padding="10dp"
    android:shape="oval" >

    <solid android:color="#FF6347" />

    <size
        android:height="325dp"
        android:width="325dp" />
</shape>
Run Code Online (Sandbox Code Playgroud)

circle.xml(在res / drawable中)

<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:drawable="@drawable/circle_pressed" android:state_pressed="true"/>
    <item android:drawable="@drawable/circle_normal"></item>

</selector>
Run Code Online (Sandbox Code Playgroud)

activity_main.xml(在res / layout中)

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/layout_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".Main" >

    <Button
        android:id="@+id/button_study"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:background="@drawable/circle"
        android:gravity="center" />
</RelativeLayout>
Run Code Online (Sandbox Code Playgroud)

Main.java(在src中)

buttonStudy = (Button) findViewById(R.id.button_study);
Run Code Online (Sandbox Code Playgroud)

最终的结果是我得到一个圆形的按钮。但是,由于不同的Android设备上的屏幕尺寸不同,因此这一圆圈大小不足。我看过其他一些与此类似的问题,但是他们的解决方案对我没有太大帮助。如何在Java代码中动态更改其大小?

Din*_*ris 5

尝试这种方式

final Button buttonStudy = (Button) findViewById(R.id.button_study);
buttonStudy.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        ViewGroup.LayoutParams params = buttonStudy.getLayoutParams();
        params.width = 100;//change the width size
        params.height= 100;//change the hight size
        buttonStudy.setLayoutParams(params);
    }
});
Run Code Online (Sandbox Code Playgroud)

啦啦队

  • 完美的!:D 这也是一个简单的解决方案;我不敢相信我在其他地方找不到它。非常感谢。(PS,我对其进行了一些编辑,使其与我自己的代码更加一致。) (2认同)