[英]How to Change the Text of a button using EditText on Android
我試圖使用一個EditText一個活動來更改另一個按鈕的文本。 我知道我必須經歷SharedPreferences,盡管這是我遇到的問題。
帶按鈕的活動:
protected void onResume() {
super.onResume();
class1.setText(this.getButtonText());
}
public String getButtonText()
{
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
String buttonText = prefs.getString("ButtonText", "Default button text"); // I am not sure how to get the button text here. This is what someone was trying to have me do?
return buttonText;
}
這是我的活動,具有EditText和按鈕,可使用按鈕返回活動:
public class EditClass1 extends Activity implements OnClickListener{
Button class1;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.editclass1);
SettingButtons();
class1.setOnClickListener(this);
}
private void SettingButtons() {
// TODO Auto-generated method stub
class1 = (Button) findViewById(R.id.edittoclass1);
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch(v.getId()){
case R.id.edittoclass1:
startActivity(new Intent("com.clayton.calendar.TOCLASS"));
break;
}
}
@Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
Editor editor = prefs.edit();
editor.putString("ButtonText", // This is not working
((TextView)findViewById(R.id.edittoclass1)).getText().toString());
editor.commit();
}
}
嘗試這個:
@Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
EditText text = (EditText)findViewById(R.id.Setclass);
String text2 = text;
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
Editor editor = prefs.edit();
editor.putString("ButtonText", // This is not working
((TextView)findViewById(R.id.edittoclass1)).getText().toString());
editor.commit();
}
暫時忽略共享首選項,為什么不只在包含按鈕的類中具有公共靜態 String變量。
public static String buttonText = "somthing";
在包含編輯文本的類中時,您可以調用事件處理程序(偵聽對編輯文本的更改)或事件處理程序,該事件處理程序在按下按鈕時觸發。
ButtonActivity.buttonText = text.getText();
然后在包含按鈕的活動的onResume()方法中
button.setText(buttonText);
嘗試此操作,這可能是執行所需操作的更簡單方法。 請記住,在聲明buttonText變量時,請確保記住使用static關鍵字。 沒有它,您將需要使用static關鍵字直接引用該對象,只需引用所需的類即可。 但是,作為靜態按鈕文本,包含活動的按鈕的所有實例都相同。 如果您只打算擁有一個活動實例,那么這就是您的解決方案。 如果不是這樣,那么您就必須變得更有創意。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.