Error “Cannot resolve Symbol editText” in Android Studio MyFirstApp tutorial

[亡魂溺海] 提交于 2021-01-27 10:21:15

问题


I'm new to Android Studio and Android development. So I was following the tutorial given by developer.android.com and I'm having an error in this line : EditText editText = (EditText) findViewById(R.id.editText); The error is saying that : cannot find symbol variable editText .

This is part of my code :

import android.os.Bundle;
import android.widget.EditText;


public class MainActivity extends AppCompatActivity {
   
    public void sendMessage(View view){
        EditText editText = (EditText) findViewById(R.id.editText);
        String message = editText.getText().toString();

    }
}

回答1:


Make sure that you have assigned the id for your EditText in the activity_main.xml as below:

<EditText
    android:id="@+id/editText"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" />



回答2:


You are probably missing the edit text in your XML. If not, perhaps the id you gave it differs from editText.

<EditText
    android:layout_width="368dp"
    android:layout_height="wrap_content"
    android:id="@+id/editText" />



回答3:


Without posting your XML code it leaves it a bit difficult, however I would guess if you go back to your XML code where you have the edit text xml code. Add this android:id="@+id/editText".




回答4:


I had the same issue as you OP. I went back to the activity_main.xml and noticed the ID was different somehow in the top right corner under attributes for the Text box. Changed the ID back and reran the app and no issues/




回答5:


The reason is that you need to write editTextTextPersonName2 instead of editText to match the definition in activity_main.xml:

android:id="@+id/editTextTextPersonName2"

The code shall thus be as follows:

public void sendMessage(View view) 
{
    Intent intent = new Intent(this, DisplayMessageActivity.class);
    EditText editText = (EditText) findViewById(R.id.editTextTextPersonName2);
    String message = editText.getText().toString();
    intent.putExtra(EXTRA_MESSAGE, message);
    startActivity(intent);
}



回答6:


R.id.editTextTextPersonName2 cause problem. You can try R.id.editText and follow the recommendation mentioned by others by adding android:id="@+id/editText" in activity_main.xml



来源:https://stackoverflow.com/questions/45377621/error-cannot-resolve-symbol-edittext-in-android-studio-myfirstapp-tutorial

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!