设置背景颜色,并在Android中使用drawable作为背景 [英] set background color and also use drawable as background in android

查看:892
本文介绍了设置背景颜色,并在Android中使用drawable作为背景的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <stroke android:width="1px" android:color="#696969"/>
</shape>

此代码用于动态创建按钮, 问题是我想设置背景颜色并设置背景可绘制对象.

this code is used to create button dynamically, the problem is i want to set background color and also set background drawables.

Button btnTag = new Button(alltable.this);
btnTag.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, 
                       LinearLayout.LayoutParams.WRAP_CONTENT));
try {
    btnTag.setWidth(130);
    btnTag.setBackground(getResources().getDrawable(R.color.blue));

} catch (Exception e){
    e.printStackTrace();
}

这是一类,我想要设置btn的背景色,然后使用我的drawable.

this is class i want to set the background color of btn and then i want use my drawable.

推荐答案

在drawable(例如files_bg.xml)文件夹中创建资源,并将其设置为布局背景.

Create a resource in drawable(like files_bg.xml) folder and set it as background for layout.

在图层列表中使用两项,一项用于形状的纯色,另一项用于位图.

Use two item in layer list, one for solid color in shape and other one bitmap.

<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
       <shape android:shape="rectangle">
            <solid android:color="@color/totalFilesBgColor" />
       </shape>
    </item>
    <item>
       <bitmap
            android:src="@drawable/bg_icon"
            android:tileMode="disabled" />
    </item>
</layer-list> 

现在在布局中或使用的任何位置将drwable设置为bakcground.

and now set drwable as bakcground in layout or wherever you are using.

<LinearLayout
       android:layout_width="match_parent"
       android:layout_height="match_parent"
       android:background="@drawable/files_bg">

 </LinearLayout>

这篇关于设置背景颜色,并在Android中使用drawable作为背景的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆