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

时间:2015-06-08 11:47:25

标签: android assets

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

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

2 个答案:

答案 0 :(得分:3)

您不需要使用InputStream来执行此操作。只需使用以下内容:

btn.setBackgroundResource(R.drawable.my_icon);

答案 1 :(得分:1)

你的activity.xml:

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

    />

将此添加到activity.java:

Button mBtn= (Button) findViewById(R.id.background);
        mBtn.setBackgroundResource(R.drawable.my_icon);
相关问题