gpt4 book ai didi

android - 我想通过我的应用程序在主布局背景中设置保存在 SD 卡上的图像

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:56:00 25 4
gpt4 key购买 nike

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

最佳答案

首先给主要的xml linearlayout分配一个id,例如在下面的情况下它被命名为“container”

    <!-- 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 代码中你可以找到布局对象并设置一个 drawable 作为它的背景:

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);
}
}

问候

陈子腾

关于android - 我想通过我的应用程序在主布局背景中设置保存在 SD 卡上的图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6262935/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com