没有正确加载按钮

时间:2013-11-27 18:16:12

标签: android sharedpreferences

嗨,任何人都可以帮助我,我很难做到这一点,并且尝试了很多方法来完成这项工作,但每次运行此代码时,即使我将布尔值设置为true,它也只会显示beginner1Check。有人可以帮我吗?

这是我的代码

的.java

public void initialize(){

    SharedPreferences beginner1Prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
    boolean beginner1_pref = beginner1Prefs.getBoolean("Beginner1", false);

    if (beginner1_pref == false){
        beginner1Check = (Button) findViewById(R.id.btnBeginner1Check);
        beginner1Check.setOnClickListener(myOnlyhandler);
    } else if (beginner1_pref == true){
        beginner1 = (Button) findViewById(R.id.btnBeginner1);
        beginner1.setOnClickListener(myOnlyhandler);
    }

    btnLogo = (Button) findViewById(R.id.btnLogo);
    beginner2 = (Button) findViewById(R.id.btnBeginner2);
    beginner3 = (Button) findViewById(R.id.btnBeginner3);
    beginner4 = (Button) findViewById(R.id.btnBeginner4);
    beginner5 = (Button) findViewById(R.id.btnBeginner5);
    beginner6 = (Button) findViewById(R.id.btnBeginner6);
    beginner7 = (Button) findViewById(R.id.btnBeginner7);
    beginner8 = (Button) findViewById(R.id.btnBeginner8);
    beginner9 = (Button) findViewById(R.id.btnBeginner9);


    btnLogo.setOnClickListener(myOnlyhandler);
    beginner2.setOnClickListener(myOnlyhandler);
    beginner3.setOnClickListener(myOnlyhandler);
    beginner4.setOnClickListener(myOnlyhandler);
    beginner5.setOnClickListener(myOnlyhandler);
    beginner6.setOnClickListener(myOnlyhandler);
    beginner7.setOnClickListener(myOnlyhandler);
    beginner8.setOnClickListener(myOnlyhandler);
    beginner9.setOnClickListener(myOnlyhandler);

}

xml>的prefs.xml

<CheckBoxPreference
    android:title="Beginner1"
    android:defaultValue="false"
    android:key="Beginner1"
    android:summary="Beginner1" />

1 个答案:

答案 0 :(得分:0)

问题是你没有让第二个Button不可见。您刚刚初始化了第一个Button,但您的第二个Button显然存在于您的布局中。除非您明确隐藏它,否则它不会隐藏。像这样修改你的代码:

if (beginner1_pref == false){
        beginner1Check = (Button) findViewById(R.id.btnBeginner1Check);
        beginner1 = (Button) findViewById(R.id.btnBeginner1);
        beginner1.setVisibility(View.INVISIBLE);//You can replace it with VIEW.GONE depending on your needs.
        beginner1Check.setOnClickListener(myOnlyhandler);
    } else if (beginner1_pref == true){
        beginner1 = (Button) findViewById(R.id.btnBeginner1);
        beginner1Check = (Button) findViewById(R.id.btnBeginner1Check);
        beginner1Check.setVisibility(View.INVISIBLE);
        beginner1.setOnClickListener(myOnlyhandler);
    }