我有一个由登录和主文件组成的android表单。 我想问的是如何获取当前用户名并将其显示在主xml文件中。
例如,我以“james01”身份登录,当我点击登录按钮时,我将被重定向到下一页,在下一页中会出现“Welcome james01”
我需要你的帮助。
总是欢迎回答^^
答案 0 :(得分:2)
将有两个选项
使用Intent
使用偏好
使用Intent
将参数传递给下一个动作
Intent n = new Intent(login.this, Home.class);
n.putExtra("UserName", _username);
startActivity(n);
在您的主页:
Bundle extras = getIntent().getExtras();
if(extras!=null)
{
userName.setText("Welcome to "+extras.getString("UserName"));
}
使用偏好设置
在您的登录页面
preferences = PreferenceManager.getDefaultSharedPreferences(this);
Editor edit = preferences.edit();
edit.putString("pref_userName", userName);
edit.commit();
在您的主页
pref_userName = preferences.getString("pref_userName", "n/a");
userName.setText("Welcome to "+pref_userName);
如果你有更多的活动,并希望在所有活动中显示用户名,那么我建议使用Preferences.
所以这将是简单的,还有一件事是
如果您正在使用首选项,那么当您从应用程序注销时不要忘记puttring null
答案 1 :(得分:1)
LoginAcvtivity.java
intent.putExtra("USERNAME",_userText.getText().toString());
Destinantion class.java
String username = getIntent().getStringExtra("USERNAME");
final TextView textViewToChange = (TextView) findViewById(R.id.username);
textViewToChange.setText(username);
在你的xml中创建一个< texview
android:id="@+id/username"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:textStyle="normal|bold|italic" />
这是我正在处理的应用程序的示例。
答案 2 :(得分:0)
最简单的方法是将用户名传递给您用于启动活动的意图中的第二个活动:
Intent intent = new Intent(getBaseContext(), SecondActivity.class);
intent.putExtra("USERNAME", username);
startActivity(intent);
然后在第二项活动中:
String username = getIntent().getStringExtra("USERNAME");
检查How do I pass data between Activities in Android application?
答案 3 :(得分:0)
Intent i = new Intent(currentActivity.this,NextActivity.class);
i.putExtra("name",name.getText.toString());
StartActivity(i);
获取名称NextActivity.class
Intent i = getIntent();
String name = i.getStringExtra("name");
并将此名称设置为textview或toast。