U4 Android应用界面        

4.2 Android界面控件基础

4.2.1 文本框 TextView

(1)在程序中 完成控件的使用

TextView tv=new TextView(this);
tv.setText("Hello World");
setContentView(tv);

(2)使用XML描述控件  并在程序中引用和使用      (更优:方便代码的维护、编码灵活、利于分工协作)

①在res/layout 文件下的XML文件中描述控件

②在程序中引用XML描述的TextView

TextView text_view = (TextView) findViewById(R.id.text_view);

TextView控件常用的方法:getText()、setText()

表 4-8

android 物联网开发板 安卓物联网开发入门_android 物联网开发板

4.2.2 编辑框 EditText

不仅可以实现输入信息,还可以根据需要对输入的信息进行限制约束

1)用XML描述一个EditView

2)在程序中引用XML描述的TextView

EditText editText = (EditText) findViewById(R.id.editText);

 表4-9

android 物联网开发板 安卓物联网开发入门_XML_02

android 物联网开发板 安卓物联网开发入门_android_03

  

4.2.3 按钮控件Button

它的常用子类有CheckBox、RadioButton、ToggleButton等

(1)用XML描述一个Button

(2)在程序代码中用XML描述的Button

Button button = (button)findViewById(R.id.button);

(3)给Button设置响应事件

button.setOnClickListener(button_listener);

(4)生成一个按钮事件监听器

private Button.OnClickListener button_listener=new
Button.OnClickListener(){
public void onClick(View v){
switch(v.getId()){
        case R.id.Button:
            textView.setText("Button按钮1");
            return;
        case R.id.Button2:
            textView.setText("Button按钮2");
            return;}
}};

当用户单击Button时,安卓系统会自动调用Activity中的selfDestruct(View)方法,但此方法必须声明public。

4.2.4 图片按钮ImageButton

 ImageButton继承自ImageView类,既可以显示图片,又可以作为Button使用。ImageButton中没有text属性。

(1)在res/layout文件下的XML文件中描述ImageButton控件

(2)在程序中引用XML描述的ImageButton:

ImageButton imageButton = (ImageButton)findViewById(R.id.ImageButton01);

(3)利用setImageResource()函数将新加入的png文件 R.drawable.download传给ImageButton

imageButton.setImageResource(R.drawable.download);

4.2.5 单选按钮 RadioButton

RadioButton是仅可以选择一个选项的控件,单选按钮要声明在RadioGroup中,RadioGroup是RadioButton的承载体,程序运行时不可见,应用程序中可能包含一个或多个RadioGroup,RadioGroup是LinearLayout的子类。

RadioButton状态更改的监听是要给它的RadioGroup添加setOnCheckedChangeListener(RadioGroup.OnCheckedChangeListener)监听器。

监听器类型和复选按钮(CheckBox)是不相同的。

单选按钮的通常用法:

1.用XML描述的RadioGroup和RadioButton应用的界面设计
2.引用处理程序

4.2.6 复选框 CheckBox

一个同时可以选择多个选项的控件

方法名称

描述

isChecked()

检查是否被选中

setChecked(boolean)

如为true,则设置成选中状态

setOnCheckedChangeListener()

处理复选框被选择事件监听按钮状态是否更改,把CompoundButton.OnChecked

-ChangeListener实例作为参数传入

getText()

获取复选框的值

CheckBox的通常用法:

1.用XML描述的CheckBox应用界面设计

2.引用XML描述的代码处理

4.2.7 列表控件 ListView

一种用于垂直显示的列表控件,列表的显示需要3个元素:

(1)ListView用来展示列表的View

(2)适配器用来把数据映射到ListView上的中介

(3)数据,指被映射的字符串、图片或基本组件