简体   繁体   English

如何在TextView中设置文本?

[英]How to set text in TextView?

I have 2 Activities, this is the layout from the second one (extract): 我有2个活动,这是第二个活动的布局(摘录):

<TextView
            android:id="@+id/user"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
<TextView
            android:id="@+id/city"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

The corresponding values are being parsed from JSON in the first Activity and the function setValues within the second Activity is called: 在第一个Activity中从JSON解析相应的值,并在第二个Activity中调用setValues函数:

String user = oj.getString("user");
String city = oj.getString("city");

act2.setValues(user, city);

In the second Activity the code looks as follows: 在第二个活动中,代码如下所示:

user = (TextView) findViewById(R.id.user);
city = (TextView) findViewById(R.id.city);

public void setValues(String user, String city) {
    Log.d("user", user); // THIS IS BEING RETURNED
    this.user.setText(user);
    this.city.setText(city);
}

This function is being called and the "user" is being returned, but the text in the TextView s is not changed. 正在调用此函数并返回“用户”,但TextView的文本未更改。

With Runnable: 使用Runnable:

Intent intent = new Intent(this, Act2.class);
startActivity(intent);
run();

public void run() {
    Log.d("run", "it's running"); // IS RETURNED
    desc.setValues(user, city);
}


// SECOND ACTIVITY
public void setValues(String user, String city) {
    Log.d("user", user); // IS RETURNED

    this.user.setText(user);
    this.city.setText(city);
}

Unfortunately the result is still the same: The TextViews remain empty. 不幸的是结果还是一样:TextViews保持为空。

can't here we use intent in your scenario ? 我们不能在您的情况下使用intent吗?

android using intent.... android使用意图...

Vogella Ariticle Vogella Ariticle

in activity 1- 在活动1中

Intent i = new Intent(this, ActivityTwo.class);
i.putExtra("Value1", "This value one for ActivityTwo ");
i.putExtra("Value2", "This value two ActivityTwo");

startActivity(i);

In activity 2 - in onCreate finction 在活动2中-在onCreate函数中

Bundle extras = getIntent().getExtras();

if (extras == null) {
        return;
        }
// Get data via the key
String value1 = extras.getString(Intent.EXTRA_TEXT);
if (value1 != null) {
    // Do something with the data
}

Make sure the setValues() method is running on the UIThread . 确保setValues()方法正在UIThread上运行。 See: Painless Threading and Processes and Threads . 请参阅: 无痛线程进程和线程

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM