当用户点击按钮时,我试图在运行时更改TextView的文本。我从Fragment中的私有方法调用setText(),该方法应该更新我创建的Activity使用的XML中的TextView。碎片是由“导航抽屉活动”预设生成的碎片之一,以备不时之需。这是片段内部的方法:
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不是重复的。我到处寻找类似的问题,但是找不到任何解决方案。任何帮助将不胜感激,因为我是Android Studio的新手!预先感谢!
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);
}