【问题标题】:How set background drawable programmatically in Android如何在 Android 中以编程方式设置背景可绘制对象
【发布时间】:2012-09-13 10:22:13
【问题描述】:

设置背景:

RelativeLayout layout =(RelativeLayout)findViewById(R.id.background);
layout.setBackgroundResource(R.drawable.ready);

这是最好的方法吗?

【问题讨论】:

  • 谢谢!您的问题和所有有用的答案帮助我在 widget 中设置了图像按钮的背景资源。如果有人感兴趣,这里有一个示例代码:remoteViews.setInt(R.id.btn_start,"setBackgroundResource", R.drawable.ic_button_start);
  • 可能需要 Kotlin 解决方案的人:stackoverflow.com/a/54495750/6247186

标签: java android background drawable


【解决方案1】:

layout.setBackgroundResource(R.drawable.ready); 是正确的。
实现它的另一种方法是使用以下方法:

final int sdk = android.os.Build.VERSION.SDK_INT;
if(sdk < android.os.Build.VERSION_CODES.JELLY_BEAN) {
    layout.setBackgroundDrawable(ContextCompat.getDrawable(context, R.drawable.ready) );
} else {
    layout.setBackground(ContextCompat.getDrawable(context, R.drawable.ready));
}

但我认为出现问题是因为您正在尝试加载大图像。
Here 是一个很好的教程如何加载大位图。

更新:
API 级别 22 中不推荐使用 getDrawable(int)


getDrawable(int ) 现在 API 级别 22 中不推荐使用。 您应该改用支持库中的以下代码:

ContextCompat.getDrawable(context, R.drawable.ready)

如果你参考ContextCompat.getDrawable的源代码,它会给你这样的东西:

/**
 * Return a drawable object associated with a particular resource ID.
 * <p>
 * Starting in {@link android.os.Build.VERSION_CODES#LOLLIPOP}, the returned
 * drawable will be styled for the specified Context's theme.
 *
 * @param id The desired resource identifier, as generated by the aapt tool.
 *            This integer encodes the package, type, and resource entry.
 *            The value 0 is an invalid identifier.
 * @return Drawable An object that can be used to draw this resource.
 */
public static final Drawable getDrawable(Context context, int id) {
    final int version = Build.VERSION.SDK_INT;
    if (version >= 21) {
        return ContextCompatApi21.getDrawable(context, id);
    } else {
        return context.getResources().getDrawable(id);
    }
}

关于ContextCompat的更多详情

从 API 22 开始,您应该使用 getDrawable(int, Theme) 方法而不是 getDrawable(int)。

更新:
如果您使用的是 support v4 库,以下内容对于所有版本就足够了。

ContextCompat.getDrawable(context, R.drawable.ready)

您需要在您的应用 build.gradle 中添加以下内容

compile 'com.android.support:support-v4:23.0.0' # or any version above

或在任何 API 中使用 ResourceCompat,如下所示:

import android.support.v4.content.res.ResourcesCompat;
ResourcesCompat.getDrawable(getResources(), R.drawable.name_of_drawable, null);

【讨论】:

  • 'getDrawable(int)' 已弃用。
  • 嘿,我正在尝试仅当图像按钮的背景图像是某个可绘制资源时才执行任务。我该如何比较...我试过if(buttonBackground.equals(R.drawable.myDrawable))Drawable buttonBackground = myButton.getBackground();我得到这个错误:snag.gy/weYgA.jpg
  • 对于最新版本的方法,您还需要myActivity.getTheme(),而不是空参数:myView.setBackground( getResources().getDrawable(R.drawable.my_background, activity.getTheme()));
  • 或者你可以使用AppCompatResources.getDrawable(this.getContext(), resId)代替,谷歌已经在AppCompat*小部件/视图中实现了它,例如:android.support.v7.widget.AppCompatCheckBox
【解决方案2】:

试试这个:

layout.setBackground(ContextCompat.getDrawable(context, R.drawable.ready));

对于 API 16<:>

layout.setBackgroundDrawable(ContextCompat.getDrawable(context, R.drawable.ready));

【讨论】:

  • 但这和艾哈迈德是一回事 :)
  • 嗯好的,那我参考懒人忍者的回答。
  • 您不需要getResources().getDrawable()。正确的代码是layout.setBackgroundResource(R.drawable.ready);,就像使用的 OP 一样。这里的问题来自位图的大小。
  • setBackground 仅 API 级别 16 或以上。
【解决方案3】:
RelativeLayout relativeLayout;  //declare this globally

现在,在 onCreate、onResume 等任何函数中

relativeLayout = new RelativeLayout(this);  
relativeLayout.setBackgroundResource(R.drawable.view); //or whatever your image is
setContentView(relativeLayout); //you might be forgetting this

【讨论】:

    【解决方案4】:

    您还可以设置任何图像的背景:

    View v;
    Drawable image=(Drawable)getResources().getDrawable(R.drawable.img);
    (ImageView)v.setBackground(image);
    

    【讨论】:

    • 这解决了我的问题,但我需要在代码中实现(.SDK_INT &gt;= Build.VERSION_CODES.JELLY_BEAN)
    • 现在已弃用
    【解决方案5】:

    我正在使用 minSdkVersion 16 和 targetSdkVersion 23。
    以下对我有用,它使用

    ContextCompat.getDrawable(context, R.drawable.drawable);
    

    而不是使用:

    layout.setBackgroundResource(R.drawable.ready);
    

    相当使用:

    layout.setBackground(ContextCompat.getDrawable(this, R.drawable.ready));
    

    getActivity() 用于片段中,如果从活动调用使用this

    【讨论】:

      【解决方案6】:

      如果你使用 AndroidX,你应该使用:

      AppCompatResources.getDrawable(context, R.drawable.your_drawable)
      

      之前列出的方法已弃用。

      【讨论】:

        【解决方案7】:

        如果您的背景现在在 drawable 文件夹中,请尝试将图像从 drawable 移动到项目中的 drawable-nodpi 文件夹。这对我有用,似乎其他图像是由他们自己重新调整的..

        【讨论】:

        • 好吧,如果您没有需要在项目中以高清质量使用的图像的副本,为什么要让 android 使用普通的可绘制文件夹将它们重新缩放到糟糕的质量。即使这个问题已经过时了,如果它仍然出现在 Google 中,而不是在其中发布新内容,恕我直言。
        【解决方案8】:

        使用butterknife 将可绘制资源绑定到一个变量,方法是将它添加到类的顶部(在任何方法之前)。

        @Bind(R.id.some_layout)
        RelativeLayout layout;
        @BindDrawable(R.drawable.some_drawable)
        Drawable background;
        

        然后在您的一种方法中添加

        layout.setBackground(background);
        

        这就是你所需要的

        【讨论】:

          【解决方案9】:
          if (android.os.Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN)
               layout.setBackgroundDrawable(getResources().getDrawable(R.drawable.ready));
          else if(android.os.Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP_MR1)
               layout.setBackground(getResources().getDrawable(R.drawable.ready));
          else
               layout.setBackground(ContextCompat.getDrawable(this, R.drawable.ready));
          

          【讨论】:

            【解决方案10】:

            试试这个。

             int res = getResources().getIdentifier("you_image", "drawable", "com.my.package");
             preview = (ImageView) findViewById(R.id.preview);
             preview.setBackgroundResource(res);
            

            【讨论】:

              【解决方案11】:

              试试ViewCompat.setBackground(yourView, drawableBackground)

              【讨论】:

                【解决方案12】:
                setBackground(getContext().getResources().getDrawable(R.drawable.green_rounded_frame));
                

                【讨论】:

                • 请解释一下广告。
                【解决方案13】:

                试试这个代码:

                Drawable thumb = ContextCompat.getDrawable(getActivity(), R.mipmap.cir_32);
                mSeekBar.setThumb(thumb);
                

                【讨论】:

                  【解决方案14】:

                  我有 4 个用于启动画面的片段。 我可以通过此代码更改片段来更改背景

                  screen_main=(ConstraintLayout)view.findViewById(R.id.screen_main);
                      screen_main.setBackground(getContext().getResources().getDrawable(R.color.bg_screen1));
                  

                  【讨论】:

                    【解决方案15】:

                    在 app/res/your_xml_layout_file.xml

                    1. 为您的父布局指定一个名称。
                    2. 转到您的 MainActivity 并通过调用 findViewById(R.id."given_name") 找到您的 RelativeLayout。
                    3. 通过调用 setBackgroundColor() 方法,将布局用作经典对象。

                    【讨论】:

                      猜你喜欢
                      • 1970-01-01
                      • 1970-01-01
                      • 2013-11-07
                      • 2023-03-02
                      • 2011-10-19
                      • 1970-01-01
                      • 1970-01-01
                      • 1970-01-01
                      • 1970-01-01
                      相关资源
                      最近更新 更多