Android Studio 使用按钮切换布局

时间:2021-05-18 13:43:14

标签: android android-studio android-layout

我的问题很简单,如何使用每个布局中的按钮在布局之间切换? 布局 1:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

<Button
    android:id="@+id/button"
    android:layout_width="54dp"
    android:layout_height="54dp"
    android:layout_marginTop="7dp"
    android:layout_marginEnd="7dp"
    android:layout_marginRight="7dp"
    app:backgroundTint="#FFFFFF"
    app:icon="@drawable/ic_polygon"
    app:iconTint="#000000"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintTop_toTopOf="parent" />


</androidx.constraintlayout.widget.ConstraintLayout>

布局 2:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/linearLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

<Button
    android:id="@+id/button1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginStart="7dp"
    android:layout_marginLeft="7dp"
    android:layout_marginTop="7dp"
    android:text="Back"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

按钮:

btn_1= findViewById(R.id.button);
btn_2= findViewById(R.id.button1); 

btn_1.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                setContentView(R.layout.layout2);
            }
});
btn_2.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                setContentView(R.layout.layout1);
            }
        });

第一个按钮工作正常,但秒不工作。 我也试过放大视图:

view_2 = getLayoutInflater().inflate(R.layout.layout2, null);
btn_2 = view_2.findById(R.id.button2);

我需要添加更多细节,所以,我来了。 我想使用按钮切换布局,确实第一个按钮更改布局,但是当我已经更改布局时,我无法使用另一个按钮“返回”到第一个布局。它应该看起来像一个菜单。

1 个答案:

答案 0 :(得分:0)

经过多次测试,最好使用另一个应用程序或片段,您可以在其中创建另一个布局并毫无问题地更改它。