【发布时间】: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