如何设置对比布局的可见性



我有约束布局xml,里面有两个约束布局。我在xml中保持了第一布局的可见性。并尝试在活动中以编程方式设置第一个布局的可见性。但视觉效果不起作用。我是约束布局的新手。请帮我设置约束布局的可见性

首先,确保在xml代码-中为该ConstraintLayout设置了一个id

<?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">
<androidx.constraintlayout.widget.ConstraintLayout
android:id="@+id/firstlayout"
android:visibility="gone"
android:layout_width="match_parent"
android:layout_height="match_parent">
</androidx.constraintlayout.widget.ConstraintLayout>
<androidx.constraintlayout.widget.ConstraintLayout
android:id="@+id/secondlayout"
android:layout_width="match_parent"
android:layout_height="match_parent">
</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.constraintlayout.widget.ConstraintLayout>

之后,转到"活动Java"文件(MainActivity.Java或您必须显示该布局的活动(并创建一个ConstraintLayout字段,然后将该特定视图分配到该字段中。

package com.legendsayantan.test;
import androidx.appcompat.app.AppCompatActivity;
import androidx.constraintlayout.widget.ConstraintLayout;
import android.os.Bundle;
import android.view.View;
public class MainActivity extends AppCompatActivity {
ConstraintLayout firstlayout;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
firstlayout=findViewById(R.id.firstlayout);
}
public static void showView(View view){
view.setVisibility(View.VISIBLE);
}
public static void hideView(View view){
view.setVisibility(View.GONE);
}
}

现在,要更改任何ConstraintLayout的可见性,只需调用以下showView()hideView()方法,并将相应的ConstraintLayout传递给该方法。

例如:

这将隐藏第一个布局:

hideView(firstlayout); 

这将显示第一个布局:

showView(firstlayout);

如果你的问题现在解决了,请告诉我。。。

最新更新