【问题标题】:Change from one layout view to another and going back?从一种布局视图更改为另一种布局视图并返回?
【发布时间】:2026-02-03 20:35:01
【问题描述】:

想要制作一个以 main 布局开头的 Android 应用,当您按下此布局中的按钮(称为 stateButton)时,布局会更改为 main2 布局包含另一个按钮(称为 boton2),当你按下这个按钮时,你会回到第一个主按钮。

我想在同一个活动中执行此操作,而不创建或启动另一个活动。

这里我给你看部分代码:

public class NuevoshActivity extends Activity
implements SensorEventListener, OnClickListener {
    private Button stateButton;
    private Button boton2;

    /** Called when the activity is first created. */ 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
        super.onCreate(savedInstanceState);       
        setContentView(R.layout.main); 
        this.stateButton = (Button) this.findViewById(R.id.boton);
        this.boton2 = (Button) this.findViewById(R.id.boton2);      
        stateButton.setOnClickListener(this);
        boton2.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        if(v==stateButton) {
            setContentView(R.layout.main2);             
        }
        else if(v==boton2) {
            setContentView(R.layout.main);
        }
    }
}

主要只有一些图像、文本视图和按钮。

但我有一些麻烦。难道就不能这么简单吗?或者我错过了什么或出了什么问题?

【问题讨论】:

    标签: android android-layout android-button


    【解决方案1】:

    当您使用 findViewById 时,您实际上是在尝试在 setContentView 指定的布局内查找视图。因此,当您尝试检查按钮时,一次又一次地使用 setContentView 可能会带来问题。

    我不会使用 setContentView,而是将屏幕的 2 个布局添加为一次只显示一个孩子的 view-flipper 的孩子布局。您可以指定要显示的子项的索引。使用视图翻转器的好处是,如果在视图之间切换时需要动画,您可以轻松地为视图指定“进”和“出”动画。这是一个更简洁的方法,然后一次又一次地调用 setContentView。

    【讨论】:

      【解决方案2】:

      FrameLayout 处理得非常好...与<include... 构造一起使用可以加载多个其他布局,然后您可以在各个布局上使用setvisibility(View.VISIBLE);setVisibility(View.INVISIBLE); 在它们之间来回切换。

      例如:

      主要的 XML 包括另外两个布局:

      <?xml version="1.0" encoding="utf-8"?>
      <FrameLayout android:id="@+id/frameLayout1" android:layout_width="fill_parent" android:layout_height="fill_parent" xmlns:android="http://schemas.android.com/apk/res/android">
          <include android:id="@+id/buildinvoice_step1_layout" layout="@layout/buildinvoice_step1" android:layout_width="fill_parent" android:layout_height="fill_parent"></include>
          <include android:id="@+id/buildinvoice_step2_layout" android:layout_width="fill_parent" layout="@layout/buildinvoice_step2" android:layout_height="fill_parent"></include>
      </FrameLayout>
      

      在布局之间切换的代码:

      findViewById(R.id.buildinvoice_step1_layout).setVisibility(View.VISIBLE);
      findViewById(R.id.buildinvoice_step2_layout).setVisibility(View.INVISIBLE);
      

      您还需要在活动开始时(或在 XML 中)设置各个布局的可见性,否则您会同时看到它们 - 一个在另一个之上。

      【讨论】:

        【解决方案3】:

        您的boton2 按钮将为NULL,因为该按钮的定义在main2.xml 中。 您将能够找到的唯一视图是在 main.xml 中定义的视图。

        【讨论】:

          【解决方案4】:

          谢谢!!!所有信息对于理解很多事情都很有用,正如 C0deAttack 评论的那样,我在 main2 上的按钮遇到了麻烦。我所做的是将 View.VISIBLE 和 View.GONE 设置为我在每个布局中想要的 TextViews 和 Buttons。非常感谢。

          【讨论】: