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