当用户点击按钮时,我正在尝试在运行时更改TextView
的文本。我从片段中的私有方法调用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不是重复的。如何更新?
尝试使用如下所示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);
}