【问题标题】:How to set the background image programmatically?如何以编程方式设置背景图像?
【发布时间】:2017-08-24 16:18:51
【问题描述】:

我在以编程方式设置背景时遇到问题。我做不到。

这是我的主题课。代码中有应该更改主背景的单选按钮。到目前为止,我已经为两个单选按钮(即 radioButtonMountains 和 radioButtonSea)编写了实现,它们应该加载两个不同的图像(即 mountain.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;
}

【问题讨论】:

  • 查看以下 SO 答案... [希望对您有所帮助][1] [1]:stackoverflow.com/questions/12678949/…
  • 在 onCheckedChanged() 监听器中粘贴一个调试点,当它被命中时查看所有 RadioButton 对象是否设置正确。
  • 你的 ThemeActivity 的第 43 行是什么?
  • @Houcine:在第43行是:relativeLayout.setBackgroundResource(R.drawable.mountains);
  • relativeLayout 变量为空。因为你有一个 NullPointerException。检查 relativeLayout 是否不同于 null 并显示日志,或尝试调试它。在此之前,请清理您的项目。

标签: java android


【解决方案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);
 }

可绘制

<?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>

图片

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2016-06-12
      • 2011-10-08
      • 2012-02-02
      • 2011-04-13
      • 2023-03-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多