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>