簡體   English   中英

通過代碼動態更改活動背景

[英]Change Background of activity dynamically through code

我需要在一些用戶活動后更改當前活動的背景

跟隨我寫的代碼

Drawable d = new BitmapDrawable(getResources(),readBitmap(Uri.fromFile(new File(getFilesDir(), imageName))));
this.findViewById(android.R.id.content).setBackground(d);
this.findViewById(android.R.id.content).refreshDrawableState();
public Bitmap readBitmap(Uri selectedImage) {
    Bitmap bm = null;
    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inSampleSize = 1; // reduce quality
    ParcelFileDescriptor pFileDescriptor = null;
    try {
        //fileDescriptor = this.getContentResolver().openAssetFileDescriptor(selectedImage, "r");
        pFileDescriptor = this.getContentResolver().openFileDescriptor(selectedImage, "r");
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } finally {
        try {
            bm = BitmapFactory.decodeFileDescriptor(pFileDescriptor.getFileDescriptor(), null, options);
            pFileDescriptor.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return bm;
}

這是content.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/bg_img_body"
    tools:context=".MainActivity" >

另外,如果我刪除XML中設置的backgroung,效果很好! 很困惑

修改的XML(有效)

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"

tools:context=".MainActivity" >

任何人都可以建議。

謝謝提前

試試this.findViewById(android.R.id.content).setBackgroundDrawable(d);

首先給您的布局ID

第二個findviewbyid布局

第三版layout.setBackgroundResource(getResources()。getDrawable(R.drawable.ready));

問題解決 !!!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM