我正在尝试将 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/