从其他活动引用活动布局

时间:2012-02-01 18:20:27

标签: android android-layout android-intent android-activity

我几年来一直在开发网络应用程序,并且决定使用本书开始使用android开发:开始使用wrox的Android应用程序开发。

在某些时候,本书解释了如何从意图中获得结果(标题为“从意图中返回结果”)。

以下是步骤:

  1. 本书介绍了如何通过添加一些新控件来更改main.xml布局文件。
  2. 这本书描述了如何更改第二个活动(Activity2),它说这个活动应该通过调用来引用不同活动的布局 ​Button btn = (Button) findViewById(R.id.btn_OK); 由于btn_OK是在主要活动的布局中定义的(而不是Activity2中的一个,它在main.xml中),因此该方法返回null。
  3. 官方文件描述:

    public View findViewById (int id)
    Since: API Level 1
    

    查找由onCreate(Bundle)中处理的XML中的id属性标识的视图。

    所以我在这里遗漏了一些东西,或者这本书是不正确的?

2 个答案:

答案 0 :(得分:0)

在Activity中使用findViewById()搜索onCreate()中setContentView()中使用的布局xml文件。

如果这两个活动使用不同的layout.xml文件,那些文件中的按钮可能具有相同的ID,并且不会混淆(通过findViewById())。

答案 1 :(得分:0)

在Activity1中

public static Button btn;
void onCreate(...) {
   btn = (Button) findViewById(R.id.btn_OK);
}

在Activity2中:

​Button btn = Activity1.btn;

注意:当你使用Intent导航到Activity2时,不要调用activity1.finish(),因为这会破坏btn;