6

我正在创建一个应用程序,我想在主 xml 线性布局中设置不同的背景图像。我在 sd 卡上存储了 5 个图像文件。现在我想选择一个图片并将其设置为我的 maim xml 线性布局背景。所以它将替换以前的图像并将新图像显示为背景。

4

1 回答 1

17

首先为主xml线性布局分配一个id,例如在下面的情况下它被命名为“容器”

    <!-- main.xml -->
<?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:id="@+id/container">
    <TextView  
        android:layout_width="fill_parent" 
        android:layout_height="wrap_content" 
        android:text="@string/hello"
        />
</LinearLayout>

然后在 .java 代码中,您可以找到布局对象并将可绘制对象设置为其背景:

package org.example.app;

import android.app.Activity;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;

public class Main extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        String pathName = "/sdcard/gif001.gif";
        Resources res = getResources();
        Bitmap bitmap = BitmapFactory.decodeFile(pathName);
        BitmapDrawable bd = new BitmapDrawable(res, bitmap);
        View view = findViewById(R.id.container);
        view.setBackgroundDrawable(bd);
    }
}

问候

陈子腾

于 2011-06-07T09:29:39.477 回答