0

我是 Android 编程新手,如果这个问题听起来很愚蠢,请原谅我。我正在为 Android 开发一个计算器。所以我有大约 20 个按钮和一个文本字段。每当按下按钮时,我都会更新文本字段,以便用户知道他输入了什么。

但是,当我更新文本字段时,应用程序崩溃了。

updateExpression 是按下任何按钮时调用的方法。

  public void updateExpression (View v)
    {
      Log.d("string", "updateExpression Called");
      EditText text = (EditText) findViewById(R.id.name);
      text.setText("HELLO EVERYONE");
    }

按钮的 .xml 文件是:

<Button
    android:id="@+id/Button03"
    android:layout_width="70dp"
    android:layout_height="wrap_content"
    android:layout_alignLeft="@+id/name"
    android:layout_below="@+id/name"
    android:onClick="updateExpression"
    android:text="C" />
// goes on for 20 buttons with different ids and text

<TextView  
    android:id="@+id/name"
    android:layout_width="fill_parent" 
    android:text="@string/edit_message" 
    android:layout_height="33dp" 
    android:textColor="@color/opaque_red"/>
</RelativeLayout>

最后,logcat 有字符串数据“updateExpression Called”。但是,在那之后它立即崩溃。该错误具有标记 AndroidRuntime Fatal Exception main。这之后还有很多错误。一个相关的(据我说是)

引起:java.lang.classCatException: android.widget.TextView 不能转换成 android.widget.EditText

请帮忙。

谢谢你。

4

2 回答 2

2

您正在尝试将 TextView 转换为 EditText,就像错误所说的那样。这是两个单独的类。

EditText text = (EditText) findViewById(R.id.name); 

应该

TextView text = (TextView) findViewById(R.id.name); 
于 2012-12-16T02:10:17.697 回答
2

在您的 xml 中,它是 aTextView 在您的代码中
EditText text = (EditText) findViewById(R.id.name);
,它是 a EditText
所以选择一个。这取决于您的需求。如果用户能够输入此内容View,则使用EditText. 如果它是只读的并且您将处理这些文本,请选择TextView.

于 2012-12-16T02:09:39.523 回答