【问题标题】:Using a Layout with a Canvas or specifying a background color with a background drawable on a canvas将 Layout 与 Canvas 一起使用,或在 Canvas 上使用可绘制的背景指定背景颜色
【发布时间】:2011-10-23 08:23:39
【问题描述】:

我正在为一项编程任务创建一个小游戏。我正在尝试弄清楚如何正确设置背景,但我似乎无法弄清楚。

我的main.xml 中有两个线性布局;一个具有背景颜色,而其中的另一个布局具有背景图像(透明 PNG)。当我启动应用程序时,它显示得很好:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="#aacceeff"
    >

 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/background"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    >

 </LinearLayout>

</LinearLayout>

但是,我现在必须添加动画。为此,我创建了一个 View 对象来加载图像并为其设置动画。但是,我现在必须将主要活动的内容视图设置为这个新视图对象的实例。当我这样做时,我得到一个空指针异常,因为它找不到 id background 的线性布局:

BitmapDrawable tiledBackground = new BitmapDrawable(BitmapFactory.decodeResource(getResources(), R.drawable.background));
LinearLayout backgroundLayout = (LinearLayout) findViewById(R.id.background);
tiledBackground.setTileModeX(Shader.TileMode.REPEAT);
backgroundLayout.setBackgroundDrawable(tiledBackground); //backgroundLayout is null

我认为这是因为视图不再是main.xml 中指定的视图。如果我删除此代码,代码运行良好,但我得到黑色背景。我尝试将这个特定的 sn-p 移动到自定义视图并将背景设置为图像,但随后我得到了具有黑色背景的图像;我真正想要的是一个透明的图像,背景颜色显示出来。

我想我想弄清楚的是如何告诉自定义视图使用我在main.xml 中定义的布局,或者找出一种指定背景颜色的方法 自定义视图的背景可绘制对象。

【问题讨论】:

    标签: android layout canvas background


    【解决方案1】:

    我可以通过使用滤色器解决这个问题:

    super(context);
    
    BitmapDrawable tiledBackground = new BitmapDrawable(BitmapFactory.decodeResource(getResources(), R.drawable.background));
    tiledBackground.setTileModeX(Shader.TileMode.REPEAT);
    
    //I determined the PorterDuff.Mode value mainly through trial and error
    tiledBackground.setColorFilter(0xaacceeff, PorterDuff.Mode.DARKEN);
    
    this.setBackgroundDrawable(tiledBackground)
    

    【讨论】:

      【解决方案2】:

      当您使用 findViewById 方法时,您正在从您在 setContentView 方法中指定的 layout.xml 中查找布局或视图。

      所以如果你调用 setContentView 并设置另一个 xml 文件作为布局,那么你将无法从之前的布局中找到视图。

      在理想情况下,setContentView 只为一个活动调用一次。为不同的屏幕调用新的活动。但是您调用也使用 ViewFlipper 类,您可以将两个布局都添加为其子级。它一次只会显示 1 个孩子。要显示下一个孩子,您可以使用

      viewflipper.setDisplayChild(1);
      

      【讨论】:

      • 对,我想通了。我正在想办法解决这个问题。
      • 我想我没有看到这将如何解决我的问题。我基本上是在尝试使用我已经定义的布局以及我拥有的自定义视图。所以我希望主布局中的背景与自定义视图一起显示。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多