我正在写我的第一个android应用程序,我有一个EditText对象,我想在我的整个程序(多个活动)中读取。我想在一个屏幕/活动/布局上采取用户的名字,并在其他几个人中读取它来操纵或显示它,所以我发现字符串需要是公共的和静态的,并且应该有一个类与我的全局变量。正确的做法是什么?我试过使用捆绑包和其他几种方法,但似乎都不起作用。
应该通过intent传递这个值。
Intent intent = new Intent(getApplicationContext(),NEXTCLASS.class);
intent.putExtra("username",mEditText1.getText().toString());
startActivity(intent);
,然后在下一个类
中接收它 Bundle extras = intent.getExtras();
mEditText1.setText(extras.getString("username"))
你也可以使用共享偏好,但我认为这对你的情况来说是不必要的,因为你不需要在应用程序关闭时保留用户名。
更新:使用共享参数。
SharedPreferences sharedPreferences = getSharedPreferences("myprefs", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("username", myusername);
从共享首选项读取…
SharedPreferences sharedPreferences = getSharedPreferences("myprefs", MODE_PRIVATE);
String username = sharedPreferences.getString("username", "");
一个使用静态属性
的例子public class utility {
public static String USERNAME = "username";
}
调用时不需要实例化类,只需从需要它的每个类执行此操作
String username = sharedPreferences.getString(utility.USERNAME, "")
可以使用SharedPreferences
存储该值。