2015-07-22 28 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

什麼是編輯和你想實現什麼? –