【发布时间】:2019-11-21 19:37:39
【问题描述】:
当用户点击按钮时,我试图在运行时更改TextView 的文本。我从片段中的私有方法调用setText(),它应该更新我创建的Activity 使用的XML 中的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 不是重复的。如何让它更新?
【问题讨论】:
-
所以您想将文本从片段更新为活动?
-
是的,没错。
标签: java android android-activity textview updating