如何通过编程设置背景图片?

3

我在以编程方式设置背景图像方面遇到了问题,但我无法解决。

这是我的主题类。代码中有一些单选按钮应该可以更改主要背景。到目前为止,我已经实现了两个单选按钮(即radioButtonMountains和radioButtonSea),它们应该加载两张不同的图片(即mountains.png和sea.png)。

public class ThemeActivity extends BasicActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_theme);

        ActionBar actionBar = getActionBar();
        actionBar.setDisplayHomeAsUpEnabled(true);
        actionBar.setTitle("Motywy");
        
        setAction();
    }
    
    private void setAction(){
        
        relativeLayout=(RelativeLayout) findViewById(R.id.relativeLayoutid);
        
        radioGroup=(RadioGroup) findViewById(R.id.radioGroup);
        radioButtonMountains=(RadioButton) findViewById(R.id.radioMountains);
        radioButtonCity=(RadioButton) findViewById(R.id.radioCity);
        radioButtonSea=(RadioButton) findViewById(R.id.radioSea);
        radioButtonNature=(RadioButton) findViewById(R.id.radioNature);
        
        radioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() {
            
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {

                if(radioButtonMountains.isChecked()){
                
                    //relativeLayout.setBackgroundDrawable(getResources().getDrawable(R.drawable.mountains));
                    //relativeLayout.setBackground(getResources().getDrawable(R.drawable.mountains));
                    relativeLayout.setBackgroundResource(R.drawable.mountains);                 
            }
            else if(radioButtonCity.isChecked()){
                
            }
            else if(radioButtonSea.isChecked()){
                relativeLayout.setBackgroundResource(R.drawable.sea);
            }
            else if(radioButtonNature.isChecked()){
                
            }

        }
    });             
}

这是我的activity_main.xml文件,用于我的主类(如果您想要,我可以粘贴我的主类代码)。我已经添加了“android:id =”@+id/relativeLayoutid“”,它在上面被引用。
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/relativeLayoutid" 
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@drawable/sea"
    android:orientation="vertical" >

// other things like a ImageButton, a TextView etc

</RelativeLayout>

最后,当我点击时,其中一个单选按钮被替换为:
11-11 21:28:34.172: D/AndroidRuntime(22316): Shutting down VM
11-11 21:28:34.172: W/dalvikvm(22316): threadid=1: thread exiting with uncaught exception (group=0x411162a0)
11-11 21:28:34.202: E/AndroidRuntime(22316): FATAL EXCEPTION: main
11-11 21:28:34.202: E/AndroidRuntime(22316): java.lang.NullPointerException
11-11 21:28:34.202: E/AndroidRuntime(22316):    at com.example.runapp.ThemeActivity$1.onCheckedChanged(ThemeActivity.java:43)
11-11 21:28:34.202: E/AndroidRuntime(22316):    at android.widget.RadioGroup.setCheckedId(RadioGroup.java:174)
11-11 21:28:34.202: E/AndroidRuntime(22316):    at android.widget.RadioGroup.access$600(RadioGroup.java:54)
11-11 21:28:34.202: E/AndroidRuntime(22316):    at android.widget.RadioGroup$CheckedStateTracker.onCheckedChanged(RadioGroup.java:358)
11-11 21:28:34.202: E/AndroidRuntime(22316):    at android.widget.CompoundButton.setChecked(CompoundButton.java:140)
11-11 21:28:34.202: E/AndroidRuntime(22316):    at android.widget.CompoundButton.toggle(CompoundButton.java:92)
11-11 21:28:34.202: E/AndroidRuntime(22316):    at android.widget.RadioButton.toggle(RadioButton.java:76)
11-11 21:28:34.202: E/AndroidRuntime(22316):    at android.widget.CompoundButton.performClick(CompoundButton.java:104)
11-11 21:28:34.202: E/AndroidRuntime(22316):    at android.view.View$PerformClick.run(View.java:17082)
11-11 21:28:34.202: E/AndroidRuntime(22316):    at android.os.Handler.handleCallback(Handler.java:615)
11-11 21:28:34.202: E/AndroidRuntime(22316):    at android.os.Handler.dispatchMessage(Handler.java:92)
11-11 21:28:34.202: E/AndroidRuntime(22316):    at android.os.Looper.loop(Looper.java:137)
11-11 21:28:34.202: E/AndroidRuntime(22316):    at android.app.ActivityThread.main(ActivityThread.java:4867)
11-11 21:28:34.202: E/AndroidRuntime(22316):    at java.lang.reflect.Method.invokeNative(Native Method)
11-11 21:28:34.202: E/AndroidRuntime(22316):    at java.lang.reflect.Method.invoke(Method.java:511)
11-11 21:28:34.202: E/AndroidRuntime(22316):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1007)
11-11 21:28:34.202: E/AndroidRuntime(22316):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:774)
11-11 21:28:34.202: E/AndroidRuntime(22316):    at dalvik.system.NativeStart.main(Native Method)

然后应用程序关闭了。我尝试使用这种方式:

relativeLayout.setBackgroundResource(R.drawable.mountains);

还有这种方式:

relativeLayout.setBackground(getResources().getDrawable(R.drawable.mountains));

还有这种方式:

relativeLayout.setBackgroundDrawable(getResources().getDrawable(R.drawable.mountains));

它们都不起作用。

我该如何解决这个问题?我应该纠正什么?

解决方案:

  1. 将relativeLayout=(RelativeLayout) findViewById(R.id.relativeLayoutid)和setBackgroundResource()方法移动到setContentView()方法后面的主活动中。
  2. 创建一个静态变量,并将此变量放入setBackgroundResource()方法中作为参数。
  3. 在您拥有单选按钮的主题活动中更改静态变量。

MainActivity类:

@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
public class MainActivity extends BasicActivity implements OnClickListener {

    public final static String EXTRA_MESSAGE = "com.example.helloworld.MESSAGE";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        //other things
        
        setContentView(R.layout.activity_main);
        
        relativeLayout=(RelativeLayout) findViewById(R.id.relativeLayoutid);
        
        if(image==0) relativeLayout.setBackgroundResource(R.drawable.mountains);
        else relativeLayout.setBackgroundResource(image);

        //other things
    }

    //other things
    
    public RelativeLayout relativeLayout;
    public static int image;
}

MainActivity类的activity_main.xml:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/relativeLayoutid" 
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@drawable/sea"
    android:orientation="vertical" >

// other things like a ImageButton, a TextView etc

</RelativeLayout>

ThemeActivity类,我在其中更改主要背景:

public class ThemeActivity extends BasicActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_theme);

        ActionBar actionBar = getActionBar();
        actionBar.setDisplayHomeAsUpEnabled(true);
        actionBar.setTitle("Theme");

        setAction();
    }
    
    private void setAction(){
        
        radioGroup=(RadioGroup) findViewById(R.id.radioGroup);
        radioButtonMountains=(RadioButton) findViewById(R.id.radioMountains);
        radioButtonCity=(RadioButton) findViewById(R.id.radioCity);
        radioButtonSea=(RadioButton) findViewById(R.id.radioSea);
        radioButtonNature=(RadioButton) findViewById(R.id.radioNature);

        setRadioChoose();
        
        radioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() {
            
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                
                if(radioButtonMountains.isChecked()){
                    
                    MainActivity.image=R.drawable.mountains;
                }
                else if(radioButtonCity.isChecked()){
                    
                    MainActivity.image=R.drawable.city;
                }
                else if(radioButtonSea.isChecked()){
                    
                    MainActivity.image=R.drawable.sea;                  
                }
                else if(radioButtonNature.isChecked()){

                    MainActivity.image=R.drawable.nature;   
                }

                saveRadioChoose(checkedId);
            }
        });
        
    }
    
    private void setRadioChoose(){
        
        radioChoose=PreferenceManager.getDefaultSharedPreferences(getBaseContext());
        radioChooseEdit=radioChoose.edit();
        
        int radio=radioChoose.getInt("RADIO", 0);
        
        if(radio==radioButtonMountains.getId()) radioButtonMountains.setChecked(true);
        else if(radio==radioButtonCity.getId()) radioButtonCity.setChecked(true);
        else if(radio==radioButtonSea.getId()) radioButtonSea.setChecked(true);
        else if(radio==radioButtonNature.getId()) radioButtonNature.setChecked(true);
        else if(radio==0) radioButtonMountains.setChecked(true);
    }
    
    private void saveRadioChoose(int checkedId){
        
        radioChooseEdit.putInt("RADIO", checkedId);
        radioChooseEdit.commit();
    }
    
    private RadioGroup radioGroup;
    private RadioButton radioButtonMountains;
    private RadioButton radioButtonCity;
    private RadioButton radioButtonSea;
    private RadioButton radioButtonNature;
    
    private SharedPreferences radioChoose;
    private SharedPreferences.Editor radioChooseEdit;
}

在 onCheckedChanged() 监听器中设置一个调试断点,当它被触发时,检查所有 RadioButton 对象是否被正确设置。 - James Cross
你的ThemeActivity的第43行是什么? - Houcine
@Houcine:第43行是:relativeLayout.setBackgroundResource(R.drawable.mountains); - Robert
@Houcine:感谢你的建议,我会尝试一下并告诉你结果。刚才我检查了一下relativeLayout变量。你说得对,它是空的。你有什么想法为什么会这样吗?我已经写了"relativeLayout=(RelativeLayout) findViewById(R.id.relativeLayoutid);" 这段代码,所以这个变量不应该是空的。 - Robert
@Houcine:谢谢你的帮助。它起作用了!我在我的主活动中添加了relativeLayout=(RelativeLayout) findViewById(R.id.relativeLayoutid)和setBackgroundResource()方法,而不是在我的主题活动中。我把这些东西移到了setContentView()方法后面。最后,我创建了一个静态变量,将其放置为setBackgroundResource()方法的参数,并在我的主题活动中更改此静态变量,其中我有单选按钮。我编辑了我的主贴并在那里放了一个解决方案。 - Robert
显示剩余4条评论
2个回答

1

我在购物车/目录应用程序中使用了这段代码。单选按钮用于保存产品颜色信息,因此用户选择一个带有不同颜色背景的单选按钮,就可以确定图像的产品颜色。

 color[i] = new RadioButton(getActivity());
 color[i].setButtonDrawable(R.drawable.color_radio_button);
 if (sdkVersion < 16) {
    color[i].setBackgroundDrawable(bkg);
 } else {
    color[i].setBackground(bkg);
 }

Drawable

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

<item android:drawable="@drawable/color_radio_selected" android:state_focused="true"/>
<item android:drawable="@drawable/color_radio_selected" android:state_pressed="true"/>
<item android:drawable="@drawable/color_radio_selected" android:state_selected="true"/>
<item android:drawable="@drawable/color_radio_selected" android:state_checked="true"/>
<item android:drawable="@drawable/color_radio_unselected"/>

</selector>

图片

enter image description here


1

最终的RelativeLayout imageView = (RelativeLayout) mLockscreenView.findViewById(R.id.mainImage); imageView.setBackgroundResource(R.drawable.bgg);


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接