【问题标题】:Android Studio: TextView in Second Activity not UpdatingAndroid Studio:第二个活动中的 TextView 未更新
【发布时间】: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


【解决方案1】:

尝试使用IntentStringFragment 传递到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);
}

【讨论】:

  • 嗨@Cameron,你检查了吗?
  • 谢谢你的回答,我现在不在,但我明天回来看看!
  • 是的@Md。 Asaduzzaman 效果很好!感谢您的帮助和快速回复! :)
猜你喜欢
  • 2016-04-18
  • 2019-04-27
  • 1970-01-01
  • 2020-04-19
  • 2023-04-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多