如何在mainactivity android中使用其他布局的对象

如何在mainactivity android中使用其他布局的对象,android,android-layout,textview,Android,Android Layout,Textview,我的android程序中有两种不同的布局,有时我想在它们之间切换。但一开始,我的程序正在终止,无法工作,因为没有定义layout 2对象。我怎样才能解决这个问题 // d and z are obejcts of another layout Button mainButton1 = (Button) findViewById(R.id.d); final TextView myTextView1 = (TextView) findViewById(R.id.z

我的android程序中有两种不同的布局,有时我想在它们之间切换。但一开始,我的程序正在终止,无法工作,因为没有定义layout 2对象。我怎样才能解决这个问题

        // d and z are obejcts of another layout

    Button mainButton1 = (Button) findViewById(R.id.d);
    final TextView myTextView1 = (TextView) findViewById(R.id.z);

    mainButton1.setOnClickListener(new OnClickListener()
    {
        @Override
        public void onClick(View arg0)
        {
            myTextView1.setText("Bye!");
        }
    });

在您的活动中使用所有视图之前,请为它们设置Id。

您不能这样做,因为在使用xml文件的元素之前,我们必须提供对该xml文件的引用,否则它将通过空指针异常。如果您必须将某些信息传递给其他活动,您可以将其附加到用于启动其他活动的意图中
希望它有帮助

您只能在使用
setContentView()
(在活动中)膨胀的版面上找到视图。您是否在单个活动中使用两个版面?我可以显示另一个版面,但如何控制它?我的意思是,我显示了另一个布局,但我如何为位于该布局中的对象编程?