view.setVisibility()方法在Java中对控件布局动态设置是否可见时使用,共有三个参数,在使用时可以直接用int代替参数,具体参数如下:
参数 | int | 说明 |
---|---|---|
View.VISIBLE | 0 | 可见,View会占有所分配的布局空间 |
View.INVISIBLE | 4 | 不可见,View会占有所分配的布局空间 |
View.GONE | 8 | 不可见,View不会占有所分配的布局空间 |
使用预览效果:
代码:
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.widget.LinearLayout;
import android.widget.Button;
import android.widget.TableLayout.LayoutParams;
import android.view.Gravity;
public class MainActivity extends Activity implements View.OnClickListener {
TextView tv;
LinearLayout ll;
Button bt[]=new Button[3];
String str[]={"VISIBLE","INVISIBLE","GONE"};
@Override
protected void onCreate(Bundle s) {
super.onCreate(s);
tv = new TextView(this);
TextView tv1=new TextView(this);
ll = new LinearLayout(this);
ll.setLayoutParams(new LayoutParams(-1, -1));
LayoutParams lp=new LayoutParams();
lp.height = -2;
lp.width = -2;
LinearLayout tvl=new LinearLayout(this);
ll.setGravity(Gravity.CENTER);
tvl.setGravity(Gravity.CENTER);
ll.setOrientation(1);
tvl.setOrientation(1);
tvl.setLayoutParams(lp);
tvl.setBackgroundColor(Color.YELLOW);
tvl.setPadding(50, 50, 50, 50);
tv.setLayoutParams(lp);
tv.setText("这是未设置的状态,即 View.VISIBLE");
tv1.setLayoutParams(lp);
tv1.setText("快点下面的按钮试试吧");
tv.setBackgroundColor(Color.BLUE);
tvl.addView(tv);
tvl.addView(tv1);
ll.addView(tvl);
for (int i=0;i < 3;i++) {
bt[i] = new Button(this);
bt[i].setText(str[i]);
bt[i].setId(-21000 - i);
bt[i].setLayoutParams(lp);
bt[i].setOnClickListener(this);
ll.addView(bt[i]);
}
ll.setBackgroundColor(-1);
setContentView(ll);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case -21000:
tv.setVisibility(View.VISIBLE);
tv.setText(str[0]);
break;
case -21001:
tv.setVisibility(View.INVISIBLE);
tv.setText(str[1]);
break;
case -21002:
tv.setVisibility(View.GONE);
tv.setText(str[2]);
break;
}
}
}