如何在Android中以编程方式隐藏布局/视图

Shr*_*don 3 android android-layout android-view

我刚刚开始学习Android.我对XML中的布局几乎没有什么困惑

  1. 我在布局中定义的所有视图是否基本上都是膨胀的还是可选的?假设我在视图组中有两个不同的视图,但我想只使用第一个或仅第二个有条件.可能吗?

  2. 动态创建的视图如何处理layout.XML文件?

  3. 如果我希望收到的消息以红色显示并以黑色发送消息,我该怎么办?

小智 6

您可以在XML布局文件中包含不可见的视图,直到以编程方式显示它们.只需在XML文件中使用"android:visible ="gone"或"android:visible ="invisible"即可.

例如,我最初在我的布局文件中包含以下内容,但它不可见:

    <LinearLayout
        android:id="@+id/pnlLatLong"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:visibility="gone"
        >
        <TextView
            android:id="@+id/lblLatLng"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/lat_long"
            />
        <EditText
            android:id="@+id/txtLatitude"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:inputType="numberDecimal|numberSigned"
            />
        <EditText
            android:id="@+id/txtLongitude"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:inputType="numberDecimal|numberSigned"
            />
    </LinearLayout>
Run Code Online (Sandbox Code Playgroud)

在Java代码中,当代码逻辑指示它应该是可见的时,我以编程方式将可见性更改为:

    View v = findViewById(R.id.pnlLatLng);
    v.setVisibility(View.VISIBLE);
Run Code Online (Sandbox Code Playgroud)

  • 值得注意的是,INVISIBLE和GONE不是同义词.GONE几乎会从布局中删除视图,根据需要调整其他视图,而INVISIBLE只会隐藏视图,但不会更改其边界/渲染大小. (2认同)

Moh*_*sif 1

您可以在 xml 中设置 android:visibility="gone" 或通过代码 setVisibility(View.gone); 要更改文本颜色,您可以设置 android:text color="#000000" 或通过代码 setTextColor();