【问题标题】:Updating a textview in different layout xml from the MainAcivity.java?从 MainAcivity.java 更新不同布局 xml 中的文本视图?
【发布时间】:2013-01-29 15:33:53
【问题描述】:

我在名为 game.xml 的布局文件夹中创建了一个新的 .xml 文件。它包含一个 TextView。

是否可以在我的主要活动中位于 game.xml 中的 textview 上设置文本?

game.xml(文本视图部分)

<TextView
    android:id="@+id/tV1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignLeft="@+id/imageView1"
    android:layout_centerVertical="true"
    android:text="TextView" />

MainActivity.java

    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    setImageArray();
    String actualword = chooseWord(words);
    createLetterArray(actualword);
    TextView textView1 = (TextView) findViewById(R.id.tV1); //get a reference to the textview on the game.xml file.
    textView1.setText(actualword);

}
    ...

我试过这样。但它不起作用。谁能帮帮我?

【问题讨论】:

    标签: android android-layout android-emulator android-widget textview


    【解决方案1】:

    你不能设置一个视图,TextView 这里不是通过充气器或setContentView() 对布局进行充气创建的。您可以通过 Intent 将值传递给实际使用 TextView 的类

    Intent intent = new Intent(MainActivity.this, NextActivity.class); 
    intent.putExtra("key", actualword);
    startActivity(intent);
    

    NextActivity 是显示文本视图的活动

    然后您可以获取该值并将其设置在您的其他活动中

    Intent recIntent = getIntent();
    String text = recIntent.getStringExtra("key");
    TextView textView1 = (TextView) findViewById(R.id.tV1); //get a reference to the textview on the game.xml file.
    textView1.setText(text);
    

    在您的第二个活动的onCreate() 中使用setContentView(R.layout.game); 之后

    【讨论】:

      【解决方案2】:

      简答,否

      布局文件只是一个蓝图。在布局膨胀(变成视图)之前,实际的 textview 不存在。

      我的问题,(如何)你没有使用这个 game.xml?是在其他活动中吗?

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-07-21
        • 1970-01-01
        • 2023-03-26
        • 2016-08-18
        • 1970-01-01
        • 2013-04-10
        • 2015-02-26
        相关资源
        最近更新 更多