android - 在android中将值设置为textview

标签 android textview

如何给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>

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

这是对应的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);

最佳答案

你的结构有问题..

它给你一个空指针异常,因为它找不到 TextView ...

setContentView(R.layout.sharedfiles); 置于 Intent 之上...

试试这个..

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);

关于android - 在android中将值设置为textview,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23990165/

相关文章:

Android AutoCompleteTextView 作为 ListView header

android - 使用 Cordova 的后台服务

android - 为什么 Active Android 不适用于 gradle 2.0?

java - 由于整数赋值导致的 Android 迭代错误

html - 我可以获取某个 ID 中每个 <p> 和 </p> 之间的所有文本吗

Android 将 TextView 保持在 ImageView 内的固定位置

android - 将 View 向下推到屏幕的布局

java - 获取同一个对象到Android ListView

android - 由于 Google Play 服务版本问题,无法将新 APK 上传到 Google Play

android - 我可以在 TextView 中设置文本以在多行时先填充下行吗