在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>

这是我正在创建的视图之一的结构.现在我想将来自先前活动的值分配给hname.我能够从先前活动中获取它,但无法将其设置为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);

解决方法:

您的结构有问题.

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

把setContentView(R.layout.sharedfiles);高于意图…

尝试这个..

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性能优化——之控件的优化 前面讲了图像的优化,接下...
前言 上一篇已经讲了如何实现textView中粗字体效果,里面主要...
最近项目重构,涉及到了数据库和文件下载,发现GreenDao这个...
WebView加载页面的两种方式 一、加载网络页面 加载网络页面,...
给APP全局设置字体主要分为两个方面来介绍 一、给原生界面设...
前言 最近UI大牛出了一版新的效果图,按照IOS的效果做的,页...