2015-07-22 32 views
1

我目前正在从Button1 ... button8保存文本的活动中工作。Android - 具有共享首选项值的显示按钮

但它不显示button.i的文本我不明白。

MainActivity =>

public void getName(){ 
    SharedPreferences preferences = getSharedPreferences("sample",0); 
    int a=(preferences.getInt("num",0)); 
    String ab=(preferences.getString("Name","")); 
    if(a==0){ 
     button1.setVisibility(View.GONE); 
     button1.setVisibility(View.VISIBLE); 
     button1.setText(ab); 
    } 
    if(a==1){ 
     button2.setVisibility(View.GONE); 
     button2.setVisibility(View.VISIBLE); 
     button2.setText(ab); 
    } 
    if(a==3){ 
     button3.setVisibility(View.GONE); 
     button3.setVisibility(View.VISIBLE); 
     button3.setText(ab); 
    } 
} 

SetupActivity =>

public void onClick(View v) { 
    SharedPreferences preferences = getSharedPreferences("Sample", 0); 
    SharedPreferences.Editor editor = preferences.edit(); 
    editor.putString("Name", editText.getText().toString()); 
    editor.putInt("num", myNum); 
    editor.commit(); 
    Intent intent = new Intent(Setup.this, MainActivity.class); 
    startActivity(intent); 
} 

回答

4

检查您的偏好名称,您使用的

getSharedPreferences("Sample", 0); 

getSharedPreferences("sample",0); 
+0

感谢,但它不工作。 :(,它不PRPREMEM – thang

+0

那么调试你的代码,并指定你的问题。例如有“你”期望的值?是editText.getText()。toString()不是“”。是否覆盖首选项? – FlanschiFox

1

不显示按钮

的文本,由于(preferences.getString(“姓名”,“”)返回“”作为缺省值,这大概就是这样。

另外的线路:

button_.setVisibility(View.GONE); 
button_.setVisibility(View.VISIBLE); 

实在是没有意义的。可以删除行:

button_.setVisibility(View.GONE); 
+0

谢谢,它工作,但按钮的文本不能保存。 – thang

+0

你的意思是“不是 保存”? – yshahak

+0

对不起,我垃圾英语,它的意​​思是没有保存按钮文本。 – thang

1
首先

从的getName方法

button_.setVisibility(View.GONE)除去该行;

然后检查你用来保存你的案例中的按钮名称的KEY你用Sample的名字保存并将其作为示例取回。保持关键是区分大小写。

如果您为了向我们展示问题而写了关键“示例”,现在就来另一点。在开始之前,我想问问你在mainActivity中你的方法getName在哪里。但不管怎么说这里有这样做的安全方式:

当保存按钮名称添加这些行

public void onClick(View v) { 
     SharedPreferences preferences = getSharedPreferences("Sample", 0); 
     SharedPreferences.Editor editor = preferences.edit(); 
     if(editText.getText().toString().length()>0){ 
     editor.putString("Name", editText.getText().toString()); 
     editor.putInt("num", myNum); 
     editor.commit(); 
     Intent intent = new Intent(Setup.this, MainActivity.class); 
     startActivity(intent);} 
} 

和GetName方法只是这样做

public void getName(){ 
    SharedPreferences preferences = getSharedPreferences("sample",0); 
    int a=(preferences.getInt("num",0)); 
    String ab=(preferences.getString("Name","")); 
    if(a==0){ 
     button1.setVisibility(View.VISIBLE); 
     button1.setText(ab); 
    } 
    if(a==1){ 
     button2.setVisibility(View.VISIBLE); 
     button2.setText(ab); 
    } 
    if(a==3){ 
     button3.setVisibility(View.VISIBLE); 
     button3.setText(ab); 
    } 
} 
+0

谢谢you.but我不知道,我保存button1的文本,但当我点击“编辑”按钮=> button1返回相同,button2保存。:( – thang

+0

你是什么意思,请解释一下 –

+0

什么是编辑和你想实现什么? –