关于android中的隐藏布局

来源:互联网 发布:百度人工智能发布会 编辑:程序博客网 时间:2024/05/17 22:50

问题描述:一张图片,在需要显示的时候显示,否则处于隐藏状态。图片隐藏时不占用任何的布局控件;图片显示时,图片一下的所有布局依次向下移动。如图所示:

 

点击按钮,图片显示,再次点击,图片消失。

 

问题解决:

通过上网查资料,可以通过view的可见性实现以上功能。

在布局文件xml中通过属性 android:visibility进行控制。

该属性有三个参数,分别为:visible(可见)invisible(不可见)以及gone

gone与invisible都是不可见的。但不同的是,gone在隐藏的情况下不会占用任何的布局空间

 

明白以上属性以及属性参数之后,可以在java文件中,为button设计监听器,点击button则可以控制view的可见性了。

 

下面给出完整代码。

另外,我已将项目工程上传至csdn,需要的朋友可以下载。地址:http://download.csdn.net/download/jenn_lian/4520407

 

 

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" >

    <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>

 

java文件:

package com.csdn.blog;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;

/**
 * the activity is to show the invisible layout when it is necessary
 *
 * @author jenn
 *
 */
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.

原创粉丝点击