在布局文件xml中通过属性 android:visibility进行控制。
该属性有三个参数,分别为:visible(可见)invisible(不可见)以及gone
gone与invisible都是不可见的。但不同的是,gone在隐藏的情况下不会占用任何的布局空间。
<?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" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello" />
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="click it !"
android:id="@+id/btn_mybuttom"
/>
<ImageView
android:id="@+id/img"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:visibility="gone"
android:src="@drawable/youtube"
/>
<TextView
android:text="it is an example!"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
</LinearLayout>
public class SumaryActivity extends Activity {
private Button btn_Mybutton;
private ImageView imgView_img;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
findView();
btn_Mybutton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// i=0,it is visible;i=4,it is invisible;i=0,it is gone;
int i = 0;
i = imgView_img.getVisibility();
if (i == 8) {
imgView_img.setVisibility(View.VISIBLE);
} else {
imgView_img.setVisibility(View.GONE);
}
}
});
}
/**
* find views by id for each one
*/
public void findView() {
btn_Mybutton = (Button) findViewById(R.id.btn_mybuttom);
imgView_img = (ImageView) findViewById(R.id.img);
}
}
下面对i进行简单的说明。getVisibility()方法是获取当前空间是否可见,如果可见,返回值为8,不可见但占空间,返回值为4;不可见并不占用空间,返回值为0.