在android中为textview设置值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23990165/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 07:41:46  来源:igfitidea点击:

Setting value to textview in android

androidtextview

提问by user3453575

How to assign a value to a textview?

如何为文本视图赋值?

<TextView
    android:id="@+id/hName"
    android:layout_width="match_parent"
    android:layout_height="50dp"
    android:textSize="25sp" 
    android:text = "@string/hName"/>

<LinearLayout 
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content">

    <ListView
        android:id="@+id/list"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

</LinearLayout>

This is the structure of one of the views I am creating. Now I want to assign value which comes from the previous activity to hname .I am able to get it from the previous activity but I am not able to set it to the textview. When I use setText(), it shows null pointer exception. How can I assign value to that text field. Thanks in advance.

这是我正在创建的视图之一的结构。现在我想将来自上一个活动的值分配给 hname 。我可以从上一个活动中获取它,但我无法将其设置为 textview。当我使用 setText() 时,它显示空指针异常。如何为该文本字段赋值。提前致谢。

This is the corresponding java code.

这是对应的java代码。

    Intent intent = getIntent();
    String host_name = intent.getStringExtra(ConnectionsActivity.HOST_NAME);
    TextView tvName = (TextView)findViewById(R.id.hName);
    tvName.setText(host_name);
    setContentView(R.layout.sharedfiles);

采纳答案by Pragnesh Ghoda シ

There is problem with your structure..

你的结构有问题。。

its giving you a null-pointer exception because it can't find text-view...

它给你一个空指针异常,因为它找不到文本视图......

put setContentView(R.layout.sharedfiles);above intent...

setContentView(R.layout.sharedfiles);上面的意图...

try this..

尝试这个..

setContentView(R.layout.sharedfiles);
Intent intent = getIntent();
String host_name = intent.getStringExtra(ConnectionsActivity.HOST_NAME);
TextView tvName = (TextView)findViewById(R.id.hName);
tvName.setText(host_name);

回答by marshallino16

@string/hName is accesible everywhere in your application code by

@string/hName 在你的应用程序代码中随处可见

getString(R.string.hName);

The null exception comes from something else, you'd better to post your logcat.

空异常来自其他方面,您最好发布您的 logcat。