android - 错误 : incompatible types: View cannot be converted to TextView and Error:Execution failed for task ':app:compileDebugJavaWithJavac'

标签 android android-layout android-activity

我是 Android 编程的新手,正在尝试使用以下 Java Activity 代码创建应用,

所以在 com.ezbatech.healthtips 中我有,

主要 Activity .java:

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;

public class MainActivity extends AppCompatActivity {
static final String EXTRA_MESSAGE = "com.ezbatech.healthtips.MESSAGE";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}

/** Called when the user taps the Send button */
public void sendMessage(View view) {
    Intent intent = new Intent(this, DisplayMessageActivity.class);
    EditText editText = (EditText) findViewById(R.id.editText);
    String message = editText.getText().toString();
    intent.putExtra(EXTRA_MESSAGE, message);
    startActivity(intent);
}
    // Do something in response to button
}`

Main2Activity.java:

package com.ezbatech.healthtips;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;

public class Main2Activity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main2);
    // Get the Intent that started this activity and extract the string
    Intent intent = getIntent();
    String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);

    // Capture the layout's TextView and set the string as its text
    TextView textView = findViewById(R.id.textView);
    textView.setText(message);
}

但是,代码在标题中返回以下错误,如下所示,

Error:(19, 41) 错误:类型不兼容:无法将 View 转换为 TextView

错误:任务 ':app:compileDebugJavaWithJavac' 执行失败。

编译失败;有关详细信息,请参阅编译器错误输出。

我引用的文档是https://developer.android.com/training/basics/firstapp/starting-activity.html

我相信这是基本的。任何帮助将不胜感激。

谢谢!

最佳答案

如果您没有使用新的 app-compat 库,那么您应该手动进行转换:

改变这个:

TextView textView = findViewById(R.id.textView);

对此:

TextView textView = (TextView)findViewById(R.id.textView); 

关于android - 错误 : incompatible types: View cannot be converted to TextView and Error:Execution failed for task ':app:compileDebugJavaWithJavac' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47445318/

相关文章:

android - 我有 edittext 填充问题

java - Android 登录按钮停止工作

安卓; MapView,如何设置默认位置?

Android应用内计费问题

Android App关闭并重新打开重新开始

android - 软键盘上推布局或隐藏操作栏

android - 操作栏中的三点操作溢出菜单?

安卓:layout_toRightOf 和 android:layout_below

android - Flutter Plugin 使用 Kotlin,Activity 总是返回 null

java - 无法恢复 Activity - NullPointerException