【问题标题】:textView.setText(); crashestextView.setText();崩溃
【发布时间】:2011-07-16 04:01:56
【问题描述】:

setText() 方法在我的应用程序中返回 null 为什么?

public class GetValue extends Activity {
    char letter = 'g';
    int ascii = letter;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        TextView textView = (TextView)findViewById(R.id.txt_1);
            textView.setText(ascii);
    }
}

无论我输入什么文本,它都会崩溃。为什么 setText() 一直返回 null?

提前谢谢你

解决方案:我的错误在 xml 文件中。我写: android:text="@+id/txt_1" 当它应该说: android:id="@+id/txt_1"

非常感谢所有的答案和cmets!

【问题讨论】:

  • 你确定 textView 不是 null 吗?你能提供一条错误信息吗?
  • 可能 findViewById() 不起作用。你确定你定义了一个名为 txt_1 的 TextView 吗?
  • 发布您的 main.xml 文件。

标签: android debugging null return settext


【解决方案1】:

您尝试将整数作为参数传递给 setText,它假定它是资源 ID。要显示计算文本,请将其作为字符串传递:textView.setText("g");

已编辑:检查您的 XML 文件,我用一些非常基本的东西进行了测试,它可以工作

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <TextView
        android:id="@+id/txt_1"
        android:layout_width="fill_parent" 
        android:layout_height="wrap_content" 
        android:text="myTextView"/>
</LinearLayout>

也许尝试清理你的项目(Project->Clean in Eclipse),我最近在上一个 ADT 版本上生成 R 时遇到了一些问题。

【讨论】:

  • 我试图放入平面文本。我唯一知道的是 setText() 行使我的程序崩溃。我知道我的 xml 文件没有问题。 logcat 说 textView 变量返回 null。我认为我使用 setText() 方法错误。
【解决方案2】:

试试这个:

textView.setText(Integer.toString(ascii)); 

还要确保你的布局 xml 有 TextView txt_1

【讨论】:

    【解决方案3】:

    我试过了:

    Integer.toString(char) and String.valueOf(char)
    

    两者都没有工作。 唯一的解决办法是:

    txt.setText(""+char);
    

    从优化的角度来看,这不是很有效,但它确实有效:)

    【讨论】:

      猜你喜欢
      • 2013-08-10
      • 2022-11-02
      • 1970-01-01
      • 1970-01-01
      • 2011-11-22
      • 2021-05-14
      • 1970-01-01
      • 2016-11-09
      • 2018-12-11
      相关资源
      最近更新 更多