我正在为编程任务创建一个小型游戏。我想弄清楚如何正确设置背景,但我似乎无法弄清楚。在画布上使用布局或在画布上使用可绘制背景指定背景颜色
我有两个线性布局在我的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
指定的视图。如果我删除此代码,代码运行良好,但我得到一个黑色的背景。我试着将这个特定的代码片段移动到自定义视图中,并将背景设置为图像,但后来我得到黑色背景的图像;我真正想要的是背景颜色透明的透明图像。
我想我试图找出是如何告诉自定义视图使用我在main.xml
定义的布局,或想出一个办法来指定背景颜色和为背景绘制自定义视图。
好吧,我想通的那部分。我试图找出如何解决这个问题。 –
我已经用替代方案更新了我的答案。 – blessenm
我想我没有看到这将如何解决我的问题。我基本上试图使用我已经定义的布局,以及我拥有的自定义视图。所以我想让主布局中的背景与自定义视图一起显示。 –