【问题标题】:Opacity on a background Drawable image in View (using XML Layout)视图中背景可绘制图像的不透明度(使用 XML 布局)
【发布时间】:2011-06-25 12:41:51
【问题描述】:

我只是想知道是否有办法更改View(即TextView 等)的背景图像的不透明度。

我知道我可以这样设置背景图片:

android:background="@drawable/my_drawable_image"

或者我可以使用这样的 alpha 设置来设置特定的背景颜色:

android:background="#10f7f7f7"

如果我将背景设置为可绘制图像,是否有办法控制不透明度(设置 alpha)?我想在 XML 布局中做到这一点。我已经知道我可以抓取 Drawable 对象并以编程方式设置 alpha,但我想看看我是否可以在布局中做到这一点。

【问题讨论】:

标签: android layout view opacity drawable


【解决方案1】:

我最终选择了编程解决方案,因为它看起来无法通过 XML 布局完成。

Drawable rightArrow = getResources().getDrawable(R.drawable.green_arrow_right_small);

// setting the opacity (alpha)
rightArrow.setAlpha(10);

// setting the images on the ImageViews
rightImage.setImageDrawable(rightArrow);

【讨论】:

  • @mohammadsadeghsaati #setAlpha(int)Drawable 上的 API 级别 1 可用。
【解决方案2】:

您给出的答案并没有完全回答您提出的问题。这就是我所做的。

    Drawable login_activity_top_background = getResources().getDrawable(R.drawable.login_activity_top_background);
    login_activity_top_background.setAlpha(127);
    LinearLayout login_activity_top = (LinearLayout) findViewById(R.id.login_activity_top);
    login_activity_top.setBackgroundDrawable(login_activity_top_background);

【讨论】:

  • 好吧,我的问题是它是否可以在 XML 布局中设置,而不是通过编程方式。
【解决方案3】:

这可能会让你的工作更简单

View backgroundimage = findViewById(R.id.background);
Drawable background = backgroundimage.getBackground();
background.setAlpha(80);

Alpha 值 0-255,0 表示完全透明,255 表示完全不透明

来自:This Answer

【讨论】:

    【解决方案4】:

    您可以将图像嵌入到 xml 中,这样您就可以在图形布局中看到它

    <LinearLayout
            style="@style/LoginFormContainer"
            android:id="@+id/login_layout"
            android:orientation="vertical" 
            android:background="@drawable/signuphead">
    

    并像这样更改代码以使其透明:

    Drawable loginActivityBackground = findViewById(R.id.login_layout).getBackground();
    loginActivityBackground.setAlpha(127);
    

    【讨论】:

      【解决方案5】:

      你也可以使用 XML 来改变透明度:

      android:alpha = "0.7"

      alpha的取值范围是0到1

      【讨论】:

      • 这会将 alpha 应用于视图,而不是背景
      猜你喜欢
      • 1970-01-01
      • 2016-09-06
      • 2011-10-16
      • 2011-11-10
      • 2019-04-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-18
      相关资源
      最近更新 更多