Android:如何以编程方式更改其他活动的背景?

时间:2015-04-26 21:31:57

标签: android xml uri background-image programmatically-created

我正在尝试通过将他们从手机照片库中选择的照片传递到布局来更改其他活动的背景。但是我一直收到错误:

Caused by: java.lang.NullPointerException
        at com.example.shawn.slidingexample.BackgroundOptionSlider.onActivityResult(BackgroundOptionSlider.java:105)
        at android.app.Activity.dispatchActivityResult(Activity.java:5778)
        at android.app.ActivityThread.deliverResults(ActivityThread.java:3710)

我不明白为什么我会收到这个错误,因为我对我当前的活动做了同样的事情并且它工作正常......

InputStream inputStream = getContentResolver().openInputStream(selectedImage);
                Drawable uploadedPic = Drawable.createFromStream(inputStream, selectedImage.toString());
                RelativeLayout layout = (RelativeLayout) findViewById(R.id.updated_background);
                layout.setBackground(uploadedPic);//this works
                RelativeLayout home = (RelativeLayout) findViewById(R.id.home);
                home.setBackground(uploadedPic);//error here

这是我的片段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:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
android:id="@+id/home"
tools:context=".MainActivity$PlaceholderFragment">

<TextView android:id="@+id/menu_home" android:layout_width="wrap_content"
    android:layout_height="wrap_content" android:text="MENU HOME PAGE"/>

这是活动XML:

  <android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:id="@+id/drawer_layout"
android:layout_width="match_parent" android:layout_height="match_parent"
tools:context=".MainActivity">

<FrameLayout android:id="@+id/container" android:layout_width="match_parent"
    android:layout_height="match_parent" />

    <fragment android:id="@+id/navigation_drawer"
    android:layout_width="@dimen/navigation_drawer_width" android:layout_height="match_parent"
    android:layout_gravity="start"
    android:name="com.example.shawn.slidingexample.NavigationDrawerFragment"
    tools:layout="@layout/fragment_navigation_drawer" />

1 个答案:

答案 0 :(得分:0)

试试这个

Android