Java 如何在Android上使用EditText更改按钮的文本
我试图在一个活动中使用EditText来更改另一个活动中按钮的文本。我知道我必须通过SharedReferences,尽管这是我被困的地方 使用按钮的活动:Java 如何在Android上使用EditText更改按钮的文本,java,android,Java,Android,我试图在一个活动中使用EditText来更改另一个活动中按钮的文本。我知道我必须通过SharedReferences,尽管这是我被困的地方 使用按钮的活动: protected void onResume() { super.onResume(); class1.setText(this.getButtonText()); } public String getButtonText() { SharedPreferences prefs = PreferenceMan
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;
}
这是我的活动,具有编辑文本和按钮,可使用按钮返回到活动:
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();
}暂时忽略共享首选项,为什么不在包含按钮的类中使用一个publicstatic字符串变量呢
public static String buttonText = "somthing";
在包含编辑文本的类中,可以调用事件处理程序(侦听编辑文本的更改)或在按下按钮时激发的事件处理程序
ButtonActivity.buttonText = text.getText();
然后在包含按钮的活动的onResume()方法中
button.setText(buttonText);
试试这个,这可能是做你想做的事情的一种更简单的方法。记住,在声明buttonText变量时,请确保记住使用static关键字。如果没有它,您将需要直接引用对象,使用static关键字,您只需引用所需的类。但是,静态按钮文本对于包含活动的按钮的所有实例都是相同的。如果你只想拥有一个活动实例,这就是你的解决方案。如果没有,那么你就必须更具创造性。应该是
String text2=text.getText().toString()
是的,我正在尝试执行多重操作,因此无法执行静态操作。然后你需要将包含按钮的对象的引用传递给包含编辑文本的对象。我建议您使用以下术语进行web搜索“在活动之间传递对象”。