[英]Android Studio: TextView in Second Activity not Updating
当用户点击按钮时,我正在尝试在运行时更改TextView
的文本。 我从 Fragment 中的私有方法调用setText()
,它应该更新我创建的Activity
使用的TextView
中的 TextView。 片段是由导航抽屉活动预设生成的片段之一,以防万一。 这是 Fragment 内部的方法:
private void openGameActivity(List<Game> currentYearCategory, int gameNum){
LayoutInflater layoutInflater = LayoutInflater.from(getActivity());
View view = layoutInflater.inflate(R.layout.activity_game, null, false);
TextView textView = view.findViewById(R.id.refereeAndDate);
String string = "test string";
textView.setText(string);
Intent intent = new Intent(getActivity(), GameActivity.class);
startActivity(intent);
}
活动正确打开并且没有错误。 findViewById
能够找到TextView
并且调用setText()
必须更改文本,因为我尝试在TextView
上调用getText()
并返回更新的值。 问题是当我运行该应用程序时, TextView
文本不会在视觉上更新。 这是有用的活动代码:
public class GameActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setSubtitle(R.string.page_game_details);
}
}
public boolean onOptionsItemSelected(MenuItem item){
finish();
return true;
}
}
来自activity_game
布局的TextView
XML 代码:
<TextView
android:id="@+id/refereeAndDate"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="The match was refereed by Brown on 16/04/12." />
我确定这个TextView
的 ID 不是重复的。 如何让它更新?
尝试使用Intent
将String
从Fragment
传递到Activity
,如下所示:
private void openGameActivity(List<Game> currentYearCategory, int gameNum){
....
String string = "test string";
textView.setText(string);
Intent intent = new Intent(getActivity(), GameActivity.class);
intent.putExtra("SHARED_CONTENT", string);
startActivity(intent);
}
然后在您的GameActivity
中进行如下更改:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
....
TextView refereeAndDate = findViewById(R.id.refereeAndDate);
String string = getIntent().getStringExtra("SHARED_CONTENT");
refereeAndDate.setText(string);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.