五、基本界面控件
大多数的界面控件都在android.view和android.widget包中,android.view.View为他们的父类,还有Dialog系列,android.app.Dialog为父类,等等。
Android的原生控件,一般是在res/layout下的xml文件中声明。然后在Activity通过使用super.setContentView(R.layout.某布局layout文件名)来加载layout。在Activity中获取控件的引用需要使用super.findViewById(R.id.控件的ID),接着就可以使用这个引用对控件进行操作,例如添加监听,设置内容等。当然也可以通过代码动态的使用控件。
View子类结构图:
TextView子类结构:
ViewGroup子类结构图:
FrameLayout子类结构:
android.app.Dialog子类结构:
5.1文本编辑控件
5.1.1 TextView
图5.1.1 TextView
android.widget.TextView一般用来文本展示,继承自android.view.View,在android.widget包中。
他的常用子类有Button, CheckedTextView, Chronometer, DigitalClock, EditText。
常用属性设置:
android:text="" |
文字显示 |
android:autoLink=”” |
链接类型。Web网址,email邮件,phone电话,map地图。Linkify。 |
|
|
链接状态时,Web情况可直接调用浏览器进行浏览。Email直接调用手机的Email软件,phone转到拨打电话页面。
5.1.2 EditText
图5.1.2EditText(四种用法:普通用法、密码框、输入电话、输入数字)
android.widget.EditText为输入框,继承自android.widget.TextView,在android.widget包中。他的常用子类。AutoCompleteTextView和MultiAutoCompleteTextView。ExtractEditText与输入法有关。
常用属性设置:
android:hint="请输入用户名" |
输入框的提示文字 |
android:password="" |
True为密码框 |
android:phoneNumber="" |
True为电话框 |
android:numeric="" |
数字框。Integer正整数, signed整数(可带负号), decimal浮点数。 |
android:digits |
设置允许输入哪些字符。如“1234567890.+-*/%\n()” |
5.1.3 AutoCompleteTextView
图5.1.3AutoCompleteTextView和MultiAutoCompleteTextView
android.widget.AutoCompleteTextView带提示的输入框,继承自android.widget.EditText,在android.widget包中。
AutoCompleteTextViewhe和MultiAutoCompleteTextView都是自动提示,一个是单选,一个多选。
常用属性设置:
android:completionThreshold |
输入几个字符时提示 |
AutoCompleteTextView就是一个带自动提示的EditText,当输入字符时,会出现提示窗口,点击选择即可。
首先在layout中定义一个AutoCompleteTextView,然后需要在Activity设置数据源就可以了。
ArrayAdapter的构造方法三个参数为:上下文的Context,每行的textView布局,数据源。
- this.autoCompleteTextView = (AutoCompleteTextView) super.findViewById(R.id.autoCompleteTextView);
- ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, R.layout.arrayadapte_textview, CITY_NAMES);
- this.autoCompleteTextView.setAdapter(arrayAdapter);
MultiAutoCompleteTextView和AutoCompleteTextView的类似,也是带有提示的输入框。区别在于MultiAutoCompleteTextView可以连续提示,选择一个提示项后会自动添加一个分隔符,在输入时继续提示。AutoCompleteTextView则属于单选模式的。
MultiAutoCompleteTextView使用时需要设置分隔符类CommaTokenizer。其他与AutoCompleteTextView一样。
属性 | 描述 |
android:background | 设 置背景色/背景图片。可以通过以下两种方法设置背景为透明:”@android:color/transparent”和”@null”。注意 TextView默认是透明的,不用写此属性,但是Buttom/ImageButton/ImageView想透明的话就得写这个属性了。 |
android:clickable | 是否响应点击事件。 |
android:contentDescription | 设置View的备注说明,作为一种辅助功能提供,为一些没有文字描述的View提供说明,如ImageButton。这里在界面上不会有效果,自己在程序中控制,可临时放一点字符串数据。 |
android:drawingCacheQuality | 设置绘图时半透明质量。有以下值可设置:auto(默认,由框架决定)/high(高质量,使用较高的颜色深度,消耗更多的内存)/low(低质量,使用较低的颜色深度,但是用更少的内存)。 |
android:duplicateParentState | 如果设置此属性,将直接从父容器中获取绘图状态(光标,按下等)。 见下面代码部分,注意根据目前测试情况仅仅是获取绘图状态,而没有获取事件,也就是你点一下LinearLayout时Button有被点击的效果,但是不执行点击事件。 |
android:fadingEdge | 设置拉滚动条时 ,边框渐变的放向。none(边框颜色不变),horizontal(水平方向颜色变淡),vertical(垂直方向颜色变淡)。参照fadingEdgeLength的效果图 |
android:fadingEdgeLength | 设置 边框渐变的长度。 |
android:fitsSystemWindows | 设置布局调整时是否考虑系统窗口(如状态栏) |
android:focusable | 设 置是否获得焦点。若有requestFocus()被调用时,后者优先处理。注意在表单中想设置某一个如EditText获取焦点,光设置这个是不行的, 需要将这个EditText前面的focusable都设置为false才行。在Touch模式下获取焦点需要设置 focusableInTouchMode为true。 |
android:focusableInTouchMode | 设置在Touch模式下View是否能取得焦点。 |
android:hapticFeedbackEnabled | 设置长按时是否接受其他触摸反馈事件。这里模拟器没有试出效果,难道是多点触摸?找不到资料可以找找performHapticFeedback或HapticFeedback这个关键字的资料看看。 |
android:id | 给 当前View设置一个在当前layout.xml中的唯一编号,可以通过调用View.findViewById() 或Activity.findViewById()根据这个编号查找到对应的View。不同的layout.xml之间定义相同的id不会冲突。格式 如”@+id/btnName” |
android:isScrollContainer | 设置当前View为滚动容器。这里没有测试出效果来,ListView/ GridView/ ScrollView根本就不用设置这个属性,而EdidText设置android:scrollbars也能出滚动条。 |
android:keepScreenOn | View在可见的情况下是否保持唤醒状态。
常在LinearLayout使用该属性,但是模拟器这里没有效果。 |
android:longClickable | 设置是否响应长按事件. |
android:minHeight | 设置视图最小高度 |
android:minWidth | 设置视图最小宽度度 |
android:nextFocusDown | 设置下方 指定视图获得下一个焦点。焦点移动是基于一个在给定方向 查找最近邻居的算法。如果指定视图不存在,移动焦点时将报运行时错误。可以设置imeOptions= actionDone,这样输入完即跳到下一个焦点。 |
android:nextFocusLeft | 设置左边 指定视图获得下一个焦点。 |
android:nextFocusRight | 设置右边 指定视图获得下一个焦点。 |
android:nextFocusUp | 设置上方 指定视图获得下一个焦点。 |
android:onClick | 点击时从上下文中调用指定的方法。这里指定一个方法名称,一般在Activity定义符合如下参数和返回值的函数并将方法名字符串指定为该值即可:
public void onClickButton(View view) android:onClick=” onClickButton” |
android:padding | 设置上下左右的边距,以像素为单位填充空白。 |
android:paddingBottom | 设置底部的边距,以像素为单位填充空白。 |
android:paddingLeft | 设置左边的边距,以像素为单位填充空白。 |
android:paddingRight | 设置右边的边距,以像素为单位填充空白。. |
android:paddingTop | 设置上方的边距,以像素为单位填充空白。 |
android:saveEnabled | 设置是否在窗口冻结时(如旋转屏幕)保存View的数据,默认为true,但是前提是你需要设置id才能自动保存,参见这里 。 |
android:scrollX | 以像素为单位设置水平方向滚动的的偏移值,在GridView中可看的这个效果。 |
android:scrollY | 以像素为单位设置垂直方向滚动的的偏移值 |
android:scrollbarAlwaysDrawHorizontalTrack | 设置是否始终显示垂直滚动条。这里用ScrollView、ListView测试均没有效果。 |
android:scrollbarAlwaysDrawVerticalTrack | 设置是否始终显示垂直滚动条。这里用ScrollView、ListView测试均没有效果。 |
android:scrollbarDefaultDelayBeforeFade | 设置N毫秒后开始淡化,以毫秒为单位。 |
android:scrollbarFadeDuration | 设置滚动条淡出效果(从有到慢慢的变淡直至消失)时间,以毫秒为单位。Android2.2中滚动条滚动完之后会消失,再滚动又会出来,在1.5、1.6版本里面会一直显示着。 |
android:scrollbarSize | 设置滚动条的宽度。 |
android:scrollbarStyle | 设置滚动条的风格和位置。设置值:insideOverlay、insideInset、outsideOverlay、outsideInset。这里没有试出太多效果,以下依次是outsideOverlay与outsideInset效果截图比较: |
android:scrollbarThumbHorizontal | 设置水平滚动条的drawable(如颜色)。 |
android:scrollbarThumbVertical | 设置垂直滚动条的drawable(如颜色). |
android:scrollbarTrackHorizontal | 设置水平滚动条背景(轨迹)的色drawable(如颜色) |
android:scrollbarTrackVertical |
设置垂直滚动条背景(轨迹)的drawable注意直接设置颜色值如”android:color/white”将得出很难看的效果,甚至都不理解这个属性了,这里可以参见ApiDemos里res/drawable/ scrollbar_vertical_thumb.xml和scrollbar_vertical_track.xml,设置代码为:android:scrollbarTrackVertical ="@drawable/scrollbar_vertical_track" |
android:scrollbars | 设置滚动条显示。none(隐藏),horizontal(水平),vertical(垂直)。见下列代码演示使用该属性让EditText内有滚动条。 但是其他容器如LinearLayout设置了但是没有效果。 |
android:soundEffectsEnabled | 设置点击或触摸时是否有声音效果 |
android:tag | 设置一个文本标签。可以通过View.getTag()或 for with View.findViewWithTag()检索含有该标签字符串的View。但一般最好通过ID来查询View,因为它的速度更快,并且允许编译时类型检查。 |
android:visibility | 设置是否显示View。设置值:visible(默认值 |
系统自带的SeekBar组件的样式较为老土,已经不能满足广大开发者的需求了,这里给大家介绍一个简单快捷的定制自己的SeekBar样式的方法,不必重写哦!
1.准备几张个性化的图片,一张是拖动条背景图,一张是进度条图,一张是拖动条图。
这里给几张示范图:
:拖动条背景图
:进度条图
:拖动条图
2.在res/drawable 目录下新建一个xml文件 ,配置信息如下:
seekbar_progress.xml
- <?xml version="1.0" encoding="utf-8"?>
- <layer-list
- xmlns:android="http://schemas.android.com/apk/res/android">
- <item android:id="@android:id/background"> // 背景项
- <nine-patch android:src="@drawable/progress_background" /> // 背景图 // 这里使用9文件,因此这么配置如果使用的是普通图片可直接使用<drawable />标签,或者使用<shape />标签,自定义图形
- </item>
- <item android:id="@android:id/progress"> // 进度项
- <clip>
- <nine-patch android:src="@drawable/progress_progress" /> // 进度图
- </clip>
- </item>
- </layer-list>
3.接下来<SeekBar ... />标签中添加如下参数:
- android:progressDrawable="@drawable/seekbar_progress"
- android:thumb="@drawable/thumb_drawable"
好了,经过上面的三个步骤,就可以轻松的实现自定义的SeekBar视图了。看下效果吧!
附:这里再贴一个使用<shape />标签为SeekBar设置背景和进度的xml配置文件,注意和上面的使用9文件的比对:
- <?xml version="1.0" encoding="utf-8"?>
- <!-- ChenJianLi Code: View: Seekbar
- 滑动时的背景效果 -->
- <layer-list xmlns:android="http://schemas.android.com/apk/res/android">
- <!-- 背景 -->
- <item android:id="@android:id/background">
- <shape>
- <corners android:radius="5dip" />
- <gradient
- android:startColor="#ffffffff"
- android:centerColor="#fffffff0"
- android:centerY="0.75"
- android:endColor="#fffffafa"
- android:angle="270"
- />
- </shape>
- </item>
- <!-- 第二进度条 -->
- <item android:id="@android:id/secondaryProgress">
- <clip>
- <shape>
- <corners android:radius="5dip" />
- <gradient
- android:startColor="#8000cdcd"
- android:centerColor="#8000bfff"
- android:centerY="0.75"
- android:endColor="#a000b2ee"
- android:angle="270"
- />
- </shape>
- </clip>
- </item>
- <!-- 第一进度条 -->
- <item android:id="@android:id/progress">
- <clip>
- <shape>
- <corners android:radius="5dip" />
- <gradient
- android:startColor="#ff00ffff"
- android:centerColor="#ff00ced1"
- android:centerY="0.75"
- android:endColor="#ff00f5ff"
- android:angle="270"
- />
- </shape>
- </clip>
- </item>
- </layer-list>
- 下面的代码是mars老师视频教程里的代码,我把它注释了一下。
- 创建两个XML布局文件main.xml和user.xml。main.xml文件为系统自动创建
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" >
- <LinearLayout android:id="@+id/listLinearLayout" <!-- 设置LinearLayout的ID -->
- android:layout_width="fill_parent" <!-- 设置LinearLayout宽度为填满整个屏幕 -->
- android:layout_height="wrap_content" <!-- 设置LinearLayout高度适应内部控件的高度 -->
- android:orientation="vertical"> <!-- 设置LinearLayout的排列方式为纵向排列 -->
- <!-- 在LinearLayout里嵌套一个ListView控件 -->
- <ListView android:id="@id/android:list" <!-- 设置ListView控件的ID,这个ID为android系统内置ID -->
- android:layout_width="fill_parent" <!-- 设置ListView控件的宽度为填满整个屏幕 -->
- android:layout_height="wrap_content" <!-- 设置ListView控件的高度为自适应 -->
- android:drawSelectorOnTop="false" <!-- 设置ListView控件条目被按下时背景颜色在文字背后,设置成True时背景色会覆盖文字 -->
- android:scrollbars="vertical"/> <!-- 设置ListView控件滚动条的方向为纵向 -->
- </LinearLayout>
- </LinearLayout>
ListViw控件中的ID (android:id="@id/android:list") 是Android系统内置的ID,不能改为其他。
android:drawSelectorOnTop="false" <!-- 当设置为false时条目被按下时背景颜色在文字背后,设置成True时背景色会覆盖文字
user.xml布局文件代码:- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:orientation="horizontal"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent">
- <TextView android:id="@+id/user_name"
- android:layout_width="180dip"
- android:layout_height="wrap_content"
- android:singleLine="true"
- android:textSize="10pt"
- android:paddingTop="2dip"
- android:paddingLeft="2dip"
- />
- <TextView android:id="@+id/user_ip"
- android:layout_width="180dip"
- android:layout_height="wrap_content"
- android:textSize="10pt"
- android:singleLine="true"
- android:paddingTop="2dip"
- android:paddingRight="2dip"
- />
- </LinearLayout>
- 在Java源代码文件中写入如下代码:
- package paj.ListView;
- import java.util.ArrayList;
- import java.util.HashMap;
- import android.app.Activity;
- import android.app.ListActivity;
- import android.os.Bundle;
- import android.view.View;
- import android.widget.ListView;
- import android.widget.SimpleAdapter;
- public class ListViewMain extends ListActivity{
- /** Called when the activity is first created. */
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- //生成一个ArrayList类型的变量list
- ArrayList<HashMap<String, String>> list = new ArrayList<HashMap<String,String>>();
- //生成两个HashMap类型的变量map1 , map2
- //HashMpa为键值对类型。第一个参数为建,第二个参数为值
- HashMap<String, String> map1 = new HashMap<String, String>();
- HashMap<String, String> map2 = new HashMap<String, String>();
- //把数据填充到map1和map2中。
- map1.put("user_name", "张三");
- map1.put("user_ip", "192.168.1.52");
- map2.put("user_name", "李四");
- map2.put("user_ip", "192.168.0.1");
- //把map1和map2添加到list中
- list.add(map1);
- list.add(map2);
- //生成一个SimpleAdapter类型的变量来填充数据
- SimpleAdapter listAdapter = new SimpleAdapter(this, list, R.layout.user, new String[]{"user_name" , "user_ip"}, new int[]{R.id.user_name , R.id.user_ip});
- //设置显示ListView
- setListAdapter(listAdapter);
- }
- //重写onListItemClick但是ListView条目事件
- @Override
- protected void onListItemClick(ListView l, View v, int position, long id) {
- // TODO Auto-generated method stub
- super.onListItemClick(l, v, position, id);
- //显示单击条目ID号
- System.out.println("id = " + id);
- //显示所单击条目的位置数
- System.out.println("position = " + position);
- }
- }
//生成SimpleAdapter对象参数的解释
- SimpleAdapter listAdapter = new SimpleAdapter(
- this //this是当前Activity的对象
- , list //list为填充数据后的ArrayList类型的list对象
- , R.layout.user //这个就是之前创建的第二个布局文件user.xml的id。
- , new String[]{"user_name" , "user_ip"} //这个String数组中的元素就是list对象中的列,list中有几这个数组中就要写几列。
- //其中的元素必须是list中列的名。
- , new int[]{R.id.user_name , R.id.user_ip} //这个int型数组中的元素对应着上上一个参数String类型数组中的列名。
- //它的值是对应user.xml布局文件中的TextView的id
- );
5.1.4 TextSwitcher
android.widget.TextSwitcher文字切换。继承自android.widget.ViewSwitcher(ViewGroup),在android.widget包中。
使用方法setInAnimation(Animation),setOutAnimation(Animation)设置动画。
例子,设置ViewSwitcher的动画,并使用数字时钟更改ViewSwitcher的字符串
- public class SwitcherActivity extends Activity implements ViewSwitcher.ViewFactory, View.OnClickListener {
- private Button buttonChangeText;
- private TextSwitcher myTextSwitcher;
- private DigitalClock myDigitalClock;
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- super.setContentView(R.layout.switcher);
- this.buttonChangeText = (Button) super.findViewById(R.id.buttonChangeText);
- this.myTextSwitcher = (TextSwitcher) super.findViewById(R.id.myTextSwitcher);
- this.myDigitalClock = (DigitalClock) super.findViewById(R.id.myDigitalClock);
- this.buttonChangeText.setOnClickListener(this);
- this.myTextSwitcher.setFactory(this);
- this.myTextSwitcher.setInAnimation(AnimationUtils.loadAnimation(this, android.R.anim.fade_in));
- this.myTextSwitcher.setOutAnimation(AnimationUtils.loadAnimation(this, android.R.anim.fade_out));
- }
- @Override
- public View makeView() {
- TextView textView = new TextView(this);
- textView.setGravity(Gravity.TOP | Gravity.CENTER_HORIZONTAL);
- textView.setTextSize(36);
- return textView;
- }
- @Override
- public void onClick(View v) {
- this.myDigitalClock.addTextChangedListener(textWatcher);
- }
- private android.text.TextWatcher textWatcher = new android.text.TextWatcher() {
- @Override
- public void onTextChanged(CharSequence s, int start, int before, int count) {
- SwitcherActivity.this.myTextSwitcher.setText(SwitcherActivity.this.myDigitalClock.getText());
- }
- @Override
- public void beforeTextChanged(CharSequence s, int start, int count, int after) {
- }
- @Override
- public void afterTextChanged(Editable s) {
- }
- };
- }
- <?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"
- android:gravity="center_horizontal">
- <Button android:id="@+id/buttonChangeText"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="开始" />
- <DigitalClock android:id="@+id/myDigitalClock"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:textSize="36dip"/>
- <TextSwitcher android:id="@+id/myTextSwitcher"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content" />
- </LinearLayout>
5.2 按钮控件
Button的子类
5.2.1 Button
图5.2.1Button
android.widget.Button最常用的按钮,继承自android.widget.TextView,在android.widget包中。
他的常用子类CheckBox, RadioButton, ToggleButton。
通常用法:
super.findViewById(id)得到在layout中声明的Button的引用,setOnClickListener(View.OnClickListener)添加监听。然后再View.OnClickListener监听器中使用v.equals(View)方法判断哪个按钮被按下,进行分别处理。
5.2.2 CheckBox
图5.2.2CheckBox
android.widget.CheckBox复选按钮,继承自android.widget.CompoundButton,在android.widget包中。
常用方法:
isChecked()检查是否被选中。
监听按钮状态更改,需要添加setOnCheckedChangeListener(CompoundButton.OnCheckedChangeListener);
5.2.3 RadioButton
图5.2.3RadioButton
android.widget. RadioButton单选按钮,继承自android.widget.CompoundButton,在android.widget包中。
通常用法:
单选按钮要声明在RadioGroup,RadioGroup是流式布局android.widget.LinearLayout的子类。
单选按钮状态更改的监听,是要给他的RadioGroup添加setOnCheckedChangeListener(RadioGroup.OnCheckedChangeListener)监听器。注意监听器类型和CheckBox是不一样的。
5.2.4 ToggleButton
图5.2.4ToggleButton
android.widget. ToggleButton开关形式的按钮,继承自android.widget.CompoundButton,在android.widget包中。
常用属性设置:
android:textOn="" |
选择状态文字 |
android:textOff="" |
未选状态文字 |
|
|
5.3 图片控件
5.3.1 ImageView
图5.3.1ImageView
android.widget.ImageView图片控件,继承自android.view.View,在android.widget包中。
最简单的使用方法。src设置图片路径,可引用drawable的图片。
- <ImageView android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:src="@drawable/tool"/>
动态声明ImageView,设置src。
- try {
- ImageView imageView = new ImageView(this);
- InputStream inputStream = super.getAssets().open("home.png");
- imageView.setImageDrawable(Drawable.createFromStream(inputStream, "tackpic"));
- this.imageLayout.addView(imageView, new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
- LinearLayout.LayoutParams.WRAP_CONTENT));
- } catch (IOException e) {
- e.printStackTrace();
- }
5.3.2 ImageButton
图5.3.2ImageButton
android.widget.ImageButton图片控件,继承自android.widget.ImageView,在android.widget包中。
最简单的使用方法。src设置图片路径,可引用drawable的图片。
- <ImageButton android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:src="@drawable/but_01"/>
动态声明ImageView,设置src。
- try {
- ImageButton imageButton = new ImageButton(this);
- InputStream inputStream = super.getAssets().open("but_02.png");
- imageButton.setImageDrawable(Drawable.createFromStream(inputStream, "tackpic"));
- this.imageLayout.addView(imageButton, new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
- LinearLayout.LayoutParams.WRAP_CONTENT));
- } catch (IOException e) {
- e.printStackTrace();
- }
5.3.3 ImageSwitcher和Gallery
图5.3.3 ImageSwitcher
android.widget. ImageSwitcher图片控件,继承自android.widget.ViewSwitcher(ViewGroup)。在android.widget包中。
ImageSwithcer是用来图片显示那块区域的控件,使用方法setInAnimation(Animation),setOutAnimation(Animation)设置动画。
Gallery是来控制底下那个图标索引列表索引用的。ImageAdapter继承自BaseAdapter,设置Gallery的适配器。
在layout添加ImageSwitcher和Gallery。定义Activity,implements接口OnItemSelectedListener, ViewFactory。onCreate的时候定义要显示图片路径列表,设置Gallery的Adapter。onItemSelected事件触发时,设置对应的图片。
Layout文件。
- <?xml version="1.0" encoding="utf-8"?>
- <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent">
- <ImageSwitcher android:id="@+id/switcher"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- android:layout_alignParentTop="true"
- android:layout_alignParentLeft="true" />
- <Gallery android:id="@+id/gallery"
- android:background="#55000000"
- android:layout_width="fill_parent"
- android:layout_height="60dp"
- android:layout_alignParentBottom="true"
- android:layout_alignParentLeft="true"
- android:gravity="center_vertical"
- android:spacing="16dp" />
- </RelativeLayout>
SwitcherActivity类。
- public class SwitcherActivity extends Activity implements OnItemSelectedListener, ViewFactory {
- private ImageSwitcher imageSwitcher;
- private Gallery gallery;
- private ArrayList<String> imageAssetPathList = new ArrayList<String>();
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- super.setContentView(R.layout.switcher);
- this.imageSwitcher = (ImageSwitcher) findViewById(R.id.switcher);
- this.gallery = (Gallery) findViewById(R.id.gallery);
- for (int i = 1; i <= 20; i++) {
- this.imageAssetPathList.add("images/" + i + ".jpg");
- }
- this.imageSwitcher.setFactory(this);
- this.gallery.setAdapter(new ImageAdapter(this, this.imageAssetPathList));
- this.gallery.setOnItemSelectedListener(this);
- }
- @Override
- public View makeView() {
- ImageView imageView = new ImageView(this);
- imageView.setBackgroundColor(0xFF000000);
- imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
- imageView.setLayoutParams(new ImageSwitcher.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
- return imageView;
- }
- @Override
- public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
- try {
- InputStream inputStream = super.getAssets().open(this.imageAssetPathList.get(position));
- imageSwitcher.setImageDrawable(Drawable.createFromStream(inputStream, "" + position));
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- @Override
- public void onNothingSelected(AdapterView<?> parent) {
- }
- }
ImageAdapter类
- public class ImageAdapter extends BaseAdapter {
- private Context content;
- private ArrayList<String> imageAssetPathList;
- public ImageAdapter(Context content, ArrayList<String> imageAssetPathList) {
- this.content = content;
- this.imageAssetPathList = imageAssetPathList;
- }
- @Override
- public int getCount() {
- if (this.imageAssetPathList != null) {
- return this.imageAssetPathList.size();
- } else {
- return 0;
- }
- }
- @Override
- public Object getItem(int position) {
- return null;
- }
- @Override
- public long getItemId(int position) {
- return 0;
- }
- @Override
- public View getView(int position, View convertView, ViewGroup parent) {
- try {
- ImageView imageView;
- imageView = new ImageView(this.content);
- imageView.setAdjustViewBounds(true);
- imageView.setScaleType(ImageView.ScaleType.FIT_XY);
- imageView.setPadding(0, 0, 0, 0);
- InputStream inputStream = this.content.getAssets().open(this.imageAssetPathList.get(position));
- imageView.setImageDrawable(Drawable.createFromStream(inputStream, "" + position));
- return imageView;
- } catch (IOException e) {
- e.printStackTrace();
- return null;
- }
- }
- }
5.4 时间控件
5.4.1 DigitalClock
图5.4.1 DigitalClock
android.widget. DigitalClock数字时钟,继承自android.widget.TextView。在android.widget包中。
电子时钟。在界面上显示一个动态的电子表。
一般用法:
调用方法getText(),可得到时间字符串。使用方法addTextChangedListener(android.text.TextWatcher)添加文字更改监听,则会每秒钟会激发一次事件。
5.4.2 AnalogClock
图5.4.2 AnalogClock
android.widget. AnalogClock模拟时钟,继承自android.view.View。在android.widget包中。
模拟时钟。在界面显示一个带时针和分针的模拟时钟。
5.4.3 TimePicker
图5.4.3 TimePicker
android.widget.TimePicker时间设置,继承自android.widget.FrameLayout(ViewGroup) 。在android.widget包中。
进行微调小时、分钟和 AM/PM(如果适用)。也可以键盘输入。AM/PM 下点击按钮选择。也可以使用此视图的对话框TimePickerDialog。
方法getCurrentHour()得到当前小时(根据AM/PM),getCurrentMinute()得到当前分钟。
方法setOnTimeChangedListener(TimePicker.OnTimeChangedListener),可对调节进行监听。
5.4.4 DatePicker
图5.4.4 DatePicker
android.widget. DatePicker时间设置,继承自android.widget.FrameLayout(ViewGroup) 。在android.widget包中。
进行微调年、月、日。也可以键盘输入。也可以使用此视图的对话框DatePickerDialog
方法getYear()得到年, getMonth()月, getDayOfMonth()当月日。
方法init(int year, int monthOfYear, int dayOfMonth, DatePicker.OnDateChangedListener onDateChangedListener),初始化年月日和调节监听。
5.5 进度条
5.5.1 ProgressBar
图5.5.1 ProgressBar
android.widget. ProgressBar,继承自android.view.View 。在android.widget包中。对应对话框ProgressDialog。
ProgressBar有两种展示方式,表盘形式(普通、小、大)和条形填充形式。在layout定义时,需要通过设施style属性类设置展示方式。
常用属性设置:
style |
显示方式,取值: ?android:attr/progressBarStyleLarge / progressBarStyle / progressBarStyleSmall / progressBarStyleHorizontal |
android:max |
progressBarStyleHorizontal方式时,进度条满时的值。 |
android:progress |
progressBarStyleHorizontal方式时,进度条主进度当前值。 |
android:secondaryProgress |
progressBarStyleHorizontal方式时,进度条次进度当前值。 |
- <ProgressBar android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- style="?android:attr/progressBarStyleLarge" />
- <ProgressBar android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- style="?android:attr/progressBarStyle"/>
- <ProgressBar android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- style="?android:attr/progressBarStyleSmall" />
- <ProgressBar android:id="@+id/myProgressBar"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- style="?android:attr/progressBarStyleHorizontal"
- android:max="100"
- android:progress="50"
- android:secondaryProgress="75"/>
progressBarStyleHorizontal方式时,就需要指定进度条最大值,当前值,次要的当前值。还可以在代码中手动设置。
通过按钮改变progress和secondaryProgress的代码:
- if (v.equals(this.buttonSubBar)) {
- this.myProgressBar.setProgress(this.myProgressBar.getProgress() - 10);
- } else if (v.equals(this.buttonAddBar)) {
- this.myProgressBar.setProgress(this.myProgressBar.getProgress() + 10);
- } else if (v.equals(this.buttonSubSecondaryBar)) {
- this.myProgressBar.setSecondaryProgress(this.myProgressBar.getSecondaryProgress() - 5);
- } else if (v.equals(this.buttonAddSecondaryBar)) {
- this.myProgressBar.setSecondaryProgress(this.myProgressBar.getSecondaryProgress() + 5);
- }
5.5.2 SeekBar
图5.5.2 SeekBar
android.widget. SeekBar拖动进度条,继承自android.widget.AbsSeekBar(android.widget. ProgressBar) 。在android.widget包中。
常用属性设置:
android:max |
进度条满时的值。 |
android:progress |
进度条主进度当前值。 |
android:thumb |
拇指跟随图标。 |
android:thumbOffset |
设置允许的轨道的范围扩展到拇指的拇指偏移量。 |
方法setOnSeekBarChangeListener(SeekBar.OnSeekBarChangeListener) 可进行监听,开始拖拽,停止拖拽,以及拖拽中进度条的值是否是用户改变等参数。
- <SeekBar android:id="@+id/mySeekBar"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:thumb="@drawable/thumb"
- android:thumbOffset="10px"
- android:max="100"
- android:progress="20"/>
- this.mySeekBar = (SeekBar) super.findViewById(R.id.mySeekBar);
- this.mySeekBar.setOnSeekBarChangeListener(onSeekBarChangeListener);
- *
- *
- /**
- * seekBar 监听器
- */
- private SeekBar.OnSeekBarChangeListener onSeekBarChangeListener = new SeekBar.OnSeekBarChangeListener() {
- @Override
- public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
- myTextSeekBar.setText(progress + "");
- Log.v(CommonConfig.LOG_TAG, "SeekBar onProgressChanged, progress: " + progress + ", fromUser: " + fromUser);
- }
- @Override
- public void onStartTrackingTouch(SeekBar seekBar) {
- Log.v(CommonConfig.LOG_TAG, "SeekBar onStartTrackingTouch");
- }
- @Override
- public void onStopTrackingTouch(SeekBar seekBar) {
- Log.v(CommonConfig.LOG_TAG, "SeekBar onStopTrackingTouch");
- }
- };
5.5.3 RatingBar
图5.5.3 RatingBar
android.widget. RatingBar星式进度条,继承自android.widget.AbsSeekBar(android.widget. ProgressBar)。在android.widget包中。
常用属性设置:
android:isIndicator |
是否是评级栏,指示器作用。True为指示器,用户不可操作。 |
android:numStars |
总星数。 |
android:rating |
当前星数。 |
android:stepSize |
每次可以等加的最小单位。浮点数。 |
setOnRatingBarChangeListener(RatingBar.OnRatingBarChangeListener),添加一个监听器,可以监听每次改变。
- <RatingBar android:id="@+id/myRatingBar"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:isIndicator="false"
- android:numStars="5"
- android:rating="1.5"
- android:stepSize="0.5"/>
- this.myRatingBar = (RatingBar) super.findViewById(R.id.myRatingBar);
- this.myRatingBar.setOnRatingBarChangeListener(onRatingBarChangeListener);
- *
- *
- /**
- * ratingBar 监听器
- */
- private RatingBar.OnRatingBarChangeListener onRatingBarChangeListener = new RatingBar.OnRatingBarChangeListener() {
- @Override
- public void onRatingChanged(RatingBar ratingBar, float rating, boolean fromUser) {
- myTextRatingBar.setText(rating + " / " + ratingBar.getNumStars());
- Log.v(CommonConfig.LOG_TAG, "RatingBar onRatingChanged, rating: " + rating + ", fromUser: " + fromUser);
- }
- };