android - findViewById() 在一个 Activity 中有效,但在另一个 Activity 中无效

标签 android android-edittext nullreferenceexception android-view findviewbyid

我正在尝试将 EditText 从 Activity1 传递到 Activity2。

Activity1代码:

public void openNextActivity() 
{
    Intent intent = new Intent("com.abc.xyz.ImageActivity"); 
    EditText myEditText = (EditText)findViewById(R.id.myEditText);

    int myEditTextId = myEditText.getId();
    //For Test purpose ----- starts
    // **Point1: next line of code works fine in this Activity1**
    EditText myEditTextTest = (EditText)findViewById(myEditTextId); 
    //For Test purpose ----- ends   

    intent.putExtra("myEditText", myEditTextId);

    startActivity(intent); 
}

Activity 2代码:

public void onCreate(Bundle savedInstanceState) 
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.comments_detail);

    Bundle extras = getIntent().getExtras();
    if(extras != null)
    {
        int myEditTextId = extras.getInt("myEditText");

        // Point2: next line of code displays the correct Id
        Log.d("tag","myEditTextId"+ myEditTextId);

        // Point 3: Next line of code not works in this Activity2
        EditText myEditText = (EditText)findViewById(myEditTextId);

        if(myEditText != null)
        {
            Log.d("tag","Not null");
        }
        else
        {
            Log.d("tag","null");// **Point4: this condition executes**
        }
    }
}

问题是行:EditText myEditText = (EditText)findViewById(myEditTextId);在 Activity1 中工作正常 但在 Activity2 中不工作。

编辑:

注意:两个 Activity 都使用不同的布局 感谢您的宝贵时间和帮助。

最佳答案

您唯一可以访问的 View 是您在 Activity 2 开始时加载的布局中的 View ,即 R.layout.comments_detail 中的 View 。我猜测 Activity 1 使用其 setContentView(..) 加载了不同的布局,并且它位于定义了“myEditText”且在范围内的布局中。

关于android - findViewById() 在一个 Activity 中有效,但在另一个 Activity 中无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7891762/

相关文章:

android - 重新连接互联网后向服务器发送 http post 请求

android - 从谷歌搜索或语音输入开始 Activity

android - 如何在使用 InputMethodManager 隐藏后恢复软键盘

nullreferenceexception - MVCSiteMapProvider 在转移到生产环境时给出空引用

c# - NullReferenceException 在 WPF 中为 vtk 加载 RenderWindowControl

android - `this@classname` 在 Kotlin 中是什么意思?

android - 如何获取水平 ScrollView 的宽度

android - 单击 EditText 时检查空格

Android EditText 值到整数

c# - 无法在 wp7 应用程序中获取 mp3 文件流