组件的显示与隐藏
1.Activity.java
package com.text;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class HhActivity extends Activity {
/** Called when the activity is first created. */
Button but1 = null;
Button but2 = null;
TextView text1 = null;
EditText edit1 = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
but1 = (Button) findViewById(R.id.but1);
but2 = (Button) findViewById(R.id.but2);
text1 = (TextView) findViewById(R.id.text1);
edit1 = (EditText) findViewById(R.id.edit1);
but1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
but1.setVisibility(View.GONE);
but2.setVisibility(View.VISIBLE);
text1.setVisibility(View.VISIBLE);
edit1.setVisibility(View.VISIBLE);
}
});
but2.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
but1.setVisibility(View.VISIBLE);
but2.setVisibility(View.GONE);
text1.setVisibility(View.GONE);
edit1.setVisibility(View.GONE);
}
});
}
}
2.main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
<Button android:id="@+id/but1" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:text="but1"/>
<TextView android:id="@+id/text1" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:visibility="gone" android:text="text1"/>
<EditText android:id="@+id/edit1" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:visibility="gone"/>
<Button android:id="@+id/but2" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:visibility="gone" android:text="but2"/>
</LinearLayout>
//代码解析
SetVisibility(int visibility)为View设置可行的状态,visibility参数为三者其中一个VISIBLE,INVISIBLE,GONE
VISIBLE:可见的,值0
INVISIBLE:不可见,但占据一定空间布局,值4
GONE:不可见,不占据任何空间布局,值8
相关的XML属性:android:visibility