Android开发中,大部分控件都有visibility这个属性,其属性有3个分别为“visible ”、“invisible”、“gone”。主要用来设置控制控件的显示和隐藏。
1) 可见(visible)
XML文件:android:visibility="visible"
Java代码:view.setVisibility(View.VISIBLE);
2) 不可见(invisible)
XML文件:android:visibility="invisible"
Java代码:view.setVisibility(View.INVISIBLE);
3) 隐藏(GONE)
XML文件:android:visibility="gone"
Java代码:view.setVisibility(View.GONE);
为了区别其作用,测试demo如下:
Java代码:
public class MainActivity extends Activity {
private TextView txt222 = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
txt222 = (TextView)findViewById(R.id.txt2222);
findViewById(R.id.btn1).setOnClickListener(listener);
findViewById(R.id.btn2).setOnClickListener(listener);
findViewById(R.id.btn3).setOnClickListener(listener);
}
View.OnClickListener listener = new View.OnClickListener() {
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn1:
txt222.setVisibility(View.VISIBLE);
break;
case R.id.btn2:
txt222.setVisibility(View.INVISIBLE);
break;
case R.id.btn3:
txt222.setVisibility(View.GONE);
break;
}
}
};
}
xml代码:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="20dip"
android:orientation="horizontal" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:background="#F00"
android:text="1111"
android:visibility="visible" />
<TextView
android:id="@+id/txt2222"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:background="#0F0"
android:text="2222"
android:visibility="visible" />
</LinearLayout>
<Button
android:id="@+id/btn1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="2222 VISIBLE" />
<Button
android:id="@+id/btn2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="2222 INVISIBLE" />
<Button
android:id="@+id/btn3"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="2222 GONE" />
</LinearLayout>