Android 以编程方式更改按钮背景图像

Android 以编程方式更改按钮背景图像,android,assets,Android,Assets,我在Android上写一些应用程序。我需要通过代码更改我的按钮背景。我有这样的东西,但背景保持透明。利用某些图像并将其转化为代码的最佳方法是什么 InputStream is = getClass().getClassLoader().getResourceAsStream("/res/drawable/my_icon.png"); this.btn.setBackground(Drawable.createFromStream(is, "")); 您不需要使用InputStrea

我在Android上写一些应用程序。我需要通过代码更改我的按钮背景。我有这样的东西,但背景保持透明。利用某些图像并将其转化为代码的最佳方法是什么

   InputStream is = getClass().getClassLoader().getResourceAsStream("/res/drawable/my_icon.png");
   this.btn.setBackground(Drawable.createFromStream(is, ""));

您不需要使用InputStream来实现这一点。只需使用以下命令:

btn.setBackgroundResource(R.drawable.my_icon);

您不需要使用InputStream来实现这一点。只需使用以下命令:

btn.setBackgroundResource(R.drawable.my_icon);
您的activity.xml:

<Button
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@drawable/ic_launcher"
    android:id="@+id/background"

    />
您的activity.xml:

<Button
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@drawable/ic_launcher"
    android:id="@+id/background"

    />

定义自定义选择器。定义自定义选择器。