我们如何在Android中以编程方式隐藏包含布局?

Dha*_*apu 23 android android-layout

我必须在我的应用程序中包含一个布局.所以我用过

<include
    android:id="@+id/support_layout"
    android:width="match_parent"
    android:height="match_parent"
    layout="@layout/support"/>
Run Code Online (Sandbox Code Playgroud)

我使用View在我的java文件中引用了这个包含标记.

View v = (View) findViewById(R.id.support_layout);
Run Code Online (Sandbox Code Playgroud)

但在我的代码的某些方面,我必须隐藏这个布局.所以我用v.GONE

但它不是隐藏.我想以编程方式引用XML中的那些文本和按钮属性.我怎样才能做到这一点?

有我的support.xml:

<LinearLayout
    android:id="@+id/support_layout"
    android:width="match_parent"
    android:height="match_parent">

    <TextView
        android:id="@+id/txt"
        android:width="match_parent"
        android:height="wrap_content"/>

    <Button
        android:id="@+id/btn" 
        android:width="match_parent"
        android:height="wrap_content"
        android:text="Button"/>

</LinearLayout>
Run Code Online (Sandbox Code Playgroud)

MrH*_*rio 16

我们需要看到View你提到的隐藏的实际实现.

但是,直接阅读你的问题,我认为你可能会以错误的方式做到这一点.

要隐藏或使视图不可见,请使用以下命令:

yourView.setVisibility(View.INVISIBLE);
Run Code Online (Sandbox Code Playgroud)

请记住,这并不能完全取消观点; 它仍将保留在您的布局中,您可以获得它的引用,甚至尝试操纵它.

要完全删除它,请改用:

yourView.setVisibility(View.GONE);
Run Code Online (Sandbox Code Playgroud)

现在,如果你调用它,你的视图将被完全从布局中删除.您将无法再获得对它的引用.


小智 12

由于<include/>在 android 中不是 View 类型并且visibility是 的属性View,因此我们无法从包含的布局参考中访问可见性。

但是,如果您将 kotlin 与视图绑定一起使用,我们可以获得包含布局的根的引用,例如binding.supportLayout.root这可能是其中之一View (ConstraintLayout, RelativeLayout, LinearLayout etc.)

现在我们有了视图的引用意味着我们可以像下面的代码一样使用它们的可见性。

binding.supportLayout.root.visibility = View.GONE
Run Code Online (Sandbox Code Playgroud)

希望你有这个想法。

  • 工作,感谢您的良好解释,其他答案不起作用。 (2认同)

小智 10

将该视图放入线性布局并隐藏线性布局.它会工作.

<LinearLayout
android:id="@+id/support_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >

<include
    layout="@layout/support"
    android:height="match_parent"
    android:width="match_parent" /> </LinearLayout>
Run Code Online (Sandbox Code Playgroud)

不要忘记编写Linearlayout而不是View.

简而言之,而不是

View v = (View) findViewById(R.id.support_layout);
Run Code Online (Sandbox Code Playgroud)

做这个

LinearLayout v = (LinearLayout) findViewById(R.id.support_layout);
Run Code Online (Sandbox Code Playgroud)

  • 否定使用包​​含标签的想法.想法是使层次结构平坦. (4认同)