每一个GUI开发工具都会提供一些基本的控件,例如Label和Button 等,下面我们来看下Android的一些基本控件。
- Label:就是只用来显示些文本信息,而且不需要编辑的控件,在Android中是使用TextView控件的。我们来看一下在xml文件下面怎么定义该控件,我们来看以下的xml代码:
<TextView android:layout_width=”fill_parent”
android:layout_height=”wrap_content”
android:text=”hello world”
/>我们在代码里定义了TextView的宽度,高度和显示文本等,当然我们还可以定义它显示的样式和颜色等。我们看运行效果
- Button:点击按钮,我们在Android 学习之四中曾经创建了一个带Button控件的示例程序,我们当时是在代码中设置它的监听事件的,现在我们可以直接在xml文件中设置其点击事件要触发的方法,看下面的xml代码:
<Button android:layout_width=”fill_parent”
android:layout_height=”wrap_content”
android:text=”click me”
android:onClick=”dosomething”
/>接下来我们只需要在java代码中定义名称我dosomething的方法就可以了,代码如下:
public class NowActivity extends Activity {
/** Called when the activity is first created. */
Button btn;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void dosomething(View btn){
TextView t=(TextView)this.findViewById(R.id.tv);
t.setText(“click”);
}
} - ImageView:显示 Image,要注意到是android:src写图片地址的时候不需要填写图片的扩展名,例如本例 calendar.png,只需要写calendar就可以了。也可以通过setImageURI()来设置图片内容。
<ImageView
android:layout_width=”fill_parent”
android:layout_height=”wrap_content”
android:id=”@+id/icon1″
android:src=”@drawable/calendar”
android:background=”#ffffffff”
/> - ImageButton:图片按钮控件。
- EditText:文本编辑框。经常用到属性有:
<EditText
android:layout_width=”fill_parent”
android:layout_height=”wrap_content”
android:capitalize=”sentences”
android:text=”Hello”
android:digits=”1234″
/>
6.CheckBox:常用的你可以使用 isChecked()来判断选中状态,setChecked()来使之为选中状态,toggle()使之选中状态变为当前相反。xml代码如下
<CheckBox android:layout_width=”fill_parent”
android:layout_height=”wrap_content”
android:id=”@+id/chktest”
android:text=”text”
/>
java代码调用如下:
CheckBox chk=(CheckBox)this.findViewById(R.id.chktest);
chk.setOnCheckedChangeListener(new OnCheckedChangeListener(){
@Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
// TODO Auto-generated method stub
if(isChecked){
chk.setText(“checked”);
}
else{
chk.setText(“unchecked”);
}
}
});
7.RadioButton:一般和RadioGroup一块使用,看下面的xml代码:
<RadioGroup android:layout_width=”fill_parent”
android:layout_height=”wrap_content”
android:id=”@+id/group1″>
<RadioButton android:layout_width=”fill_parent”
android:layout_height=”wrap_content”
android:text=”one”
android:id=”@+id/rb1″/>
<RadioButton android:layout_width=”fill_parent”
android:layout_height=”wrap_content”
android:text=”two”
android:id=”@+id/rb2″/>
</RadioGroup>
可以使用RadioGroup的check(id),和 clearCheck()来对RadioButton来操作。
一些比较有用的属性:
- android:nextFocusDown
- android:nextFocusLeft
- android:nextFocusRight
- android:nextFocusUp