构建用户界面和使用控件_第1页
构建用户界面和使用控件_第2页
构建用户界面和使用控件_第3页
构建用户界面和使用控件_第4页
构建用户界面和使用控件_第5页
已阅读5页,还剩52页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

1、构建用户界面和使用控件Android中的常见控件:一、文本控件TextViewTextView类的定义如下,它属于View类的直接子类,主要功能是用于显示文本。java.lang.Objectandroid.view.Viewandroid.widget.TextView主要属性所有组件都会在R.java中自动生成 public static final class id public static final int textView01=0 x7f050000;在程序代码中,可以通过setAutoLinkMask方法进行autoLink行为的设置, 传递一个int类型的值,如Linkify

2、.EMAIL_ADDRESS或Linkify.WEB_ADDRESS或者使用Linkify类的静态方法addLinksLinkify.addLinks(tv,Linkify.ALL);设置背景颜色有三种方法:setBackgroundResource:通过颜色资源ID设置背景色。setBackgroundColor:通过颜色值设置背景色。setBackgroundDrawable:通过Drawable对象设置背景色。setBackgroundResource方法设置背景:以下为引用内容: textView.setBackgroundResource(R.color.background); s

3、etBackgroundColor方法设置背景:以下为引用内容: textView.setBackgroundColor(android.graphics.Color.RED);setBackgroundDrawable方法设置背景:以下为引用内容: Resources resources=getBaseContext().getResources();Drawable drawable=resources.getDrawable(R.color.background);textView.setBackgroundDrawable(drawable);等价于textView.setBackgr

4、ound(getResources().getDrawable(R.color.background)设置背景图片1、将背景图片放置在 drawable-mdpi 目录下,假设图片名为 jobs.jpg 。2、main.xml 文件以下为引用内容: 为TextView编写style在Android中为了方便美工对组件进行修饰,也可以使用一些样式文件对组件显示进行控制,用户只需要按照如下的xml文件格式即可定义组件的显示格式,方法:res的values目录,复制strings.xml文档进行修改即可30px#0000FFwrap_contentwrap_contentall如果要引用样式表文件,

5、EditText样式表20px#0000FFwrap_contentwrap_contentall20px#0000FFwrap_contentwrap_contentfill_parentwrap_content10ptdrawable/bg_borderandroid:hint可以提示文本,此文本将以较暗一些的颜色显示,并在用户开始键入内容时立即消失。提示的用途是让用户知道应在此字段中输入何种内容,无需用户选择或擦除文本。在代码中,可以通过调用setHint方法进行设置。二、按钮控件1. Button处理单击事件:方法一:略方法二:为Button设置androi:onClick属性,并在A

6、ctivity文件中编写相应的方法,该方法必须有一个View类型的参数main.xmlButtonClickActivity.java public void clickOne(View v) (TextView)v).setText(R.string.newtext); tv.setText(R.string.newtext);方法3:Activity本身作为事件监听器public class NowActivity extends Activity implements OnClickListener /* Called when the activity is first created

7、. */Button btn;TextView tv; Override public void onCreate(Bundle savedInstanceState) super.onCreate(savedInstanceState); setContentView(R.layout.main); btn=(Button)findViewById(R.id.time); tv=(TextView)findViewById(R.id.text); btn.setOnClickListener(this); public void onClick(View view) updateTime()

8、; public void updateTime() tv.setText(new Date().toString(); 如果有多个按钮,判断是哪个按钮被按下class MyButtonOnClick implements OnClickListenerOverridepublic void onClick(View v) / TODO Auto-generated method stubif(v=myButton)tv.setText(R.string.click1);else tv.setText(R.string.click2); 2. ImageButtonImageButton bt

9、n =(ImageButton)this.findViewById(R.id.imageBtn);btn.setImageResource(R.drawable.icon);按钮的图像文件必须位于res/drawable文件夹下选择器将该文件放在res/drawable文件夹下,将按钮的android:src属性设置为选择器xml文件android:src= drawable /imagebuttonselector3. ToggleButtonToggleButton是一种具有两种状态的按钮,此按钮可以处于On状态,也可以处于Off状态,默认行为时在On状态下显示一个绿条,并将文本设置为On

10、,在Off状态下显示一个灰条。并将文本设置为Off.也可以通过textOn和textOff属性修改ToggleButton的文本。4. CheckBoxHYPERLINK file:/C:/Android/android-sdk/docs/reference/java/lang/Object.htmljava.lang.ObjectHYPERLINK file:/C:/Android/android-sdk/docs/reference/android/view/View.htmlandroid.view.ViewHYPERLINK file:/C:/Android/android-sdk/d

11、ocs/reference/android/widget/TextView.htmlandroid.widget.TextViewHYPERLINK file:/C:/Android/android-sdk/docs/reference/android/widget/Button.htmlandroid.widget.ButtonHYPERLINK file:/C:/Android/android-sdk/docs/reference/android/widget/CompoundButton.htmlandroid.widget.CompoundButtonandroid.widget.Ch

12、eckBoxCheckBox类本身没有找到合适的方法,此时可以到它的父类中去找,如CompoundButton父类中去找常用方法: public boolean isChecked() public void setChecked(boolean checked)public void setOnCheckedChangeListener(HYPERLINK file:/C:/Android/android-sdk/docs/reference/android/widget/CompoundButton.OnCheckedChangeListener.htmlCompoundButton.On

13、CheckedChangeListener listener) public void toggle() /Change the checked state of the view to the inverse of its current statech1.setOnCheckedChangeListener(new OnCheckedChangeListener()Override public void onCheckedChanged(CompoundButton arg0, boolean arg1) / TODO Auto-generated method stubif(arg1)

14、System.out.println(swim);); RadioButtonRadioGroup与RadioButton单选钮HYPERLINK file:/C:/Android/android-sdk/docs/reference/java/lang/Object.htmljava.lang.ObjectHYPERLINK file:/C:/Android/android-sdk/docs/reference/android/view/View.htmlandroid.view.ViewHYPERLINK file:/C:/Android/android-sdk/docs/referenc

15、e/android/view/ViewGroup.htmlandroid.view.ViewGroupHYPERLINK file:/C:/Android/android-sdk/docs/reference/android/widget/LinearLayout.htmlandroid.widget.LinearLayoutandroid.widget.RadioGroup在许多语言中,单选钮直接定义即可,但在Android中,RadioGroup定义的只是一个单选钮的容器,在这个容器中要加入多个单选项,而这个单选项就是RadioButtonHYPERLINK file:/C:/Androi

16、d/android-sdk/docs/reference/java/lang/Object.htmljava.lang.ObjectHYPERLINK file:/C:/Android/android-sdk/docs/reference/android/view/View.htmlandroid.view.ViewHYPERLINK file:/C:/Android/android-sdk/docs/reference/android/widget/TextView.htmlandroid.widget.TextViewHYPERLINK file:/C:/Android/android-s

17、dk/docs/reference/android/widget/Button.htmlandroid.widget.ButtonHYPERLINK file:/C:/Android/android-sdk/docs/reference/android/widget/CompoundButton.htmlandroid.widget.CompoundButtonandroid.widget.RadioButton常用方法:public void check(int id) /设置要选中的按钮编号public void clearCheck() /清空选中状态public int getChec

18、kedRadioButtonId() /取得选中的RadioButton的IDpublic void setOnCheckedChangedListener (RadioGroup.OnCheckedChangedListener listener)sexGroup.setOnCheckedChangeListener( new RadioGroup .OnCheckedChangeListener() Overridepublic void onCheckedChanged(RadioGroup arg0, int arg1) / TODO Auto-generated method stu

19、b);判断是哪一个按钮被checkedpublic void onCheckedChanged(RadioGroup arg0, int arg1) / TODO Auto-generated method stubif(maleButton.getId()=arg1)System.out.println(male);else if(femaleButton.getId()=arg1)System.out.println(female);或者采用以下方式:if(sexGroup.getCheckedRadioButtonId()=R.id.male)System.out.println(mal

20、e);else if(sexGroup.getCheckedRadioButtonId()=R.id.female)System.out.println(female);或者if(R.id.male=arg1)System.out.println(male);else if(R.id.female=arg1)System.out.println(female);btn.setOnClickListener(new Button.OnClickListener()Overridepublic void onClick(View v) / TODO Auto-generated method st

21、ubupdateTime(); ); setContentView(btn); public class UpdateActivity extends Activity implements View.OnClickListener /* Called when the activity is first created. */Button btn; Override public void onCreate(Bundle savedInstanceState) super.onCreate(savedInstanceState); btn=new Button(this); btn.setO

22、nClickListener(this); updateTime(); setContentView(btn); Overridepublic void onClick(View v) / TODO Auto-generated method stubupdateTime();public void updateTime() btn.setText(new Date().toString(); public class UpdateActivity extends Activity /* Called when the activity is first created. */Button b

23、tn; Override public void onCreate(Bundle savedInstanceState) super.onCreate(savedInstanceState); setContentView(R.layout.main); public void someMethod(View theButton) (Button)theButton).setText(Clicke me); public class TestActivity extends Activity /* Called when the activity is first created. */Rad

24、ioButton answera=null,answerb=null,answerc=null,answerd=null;RadioGroup test=null; Override public void onCreate(Bundle savedInstanceState) super.onCreate(savedInstanceState); setContentView(R.layout.main); answera=(RadioButton)findViewById(R.id.a); answerb=(RadioButton)findViewById(R.id.b); answerc

25、=(RadioButton)findViewById(R.id.c); answerd=(RadioButton)findViewById(R.id.d); test=(RadioGroup)findViewById(R.id.testGroup); test.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() Overridepublic void onCheckedChanged(RadioGroup arg0, int arg1) / TODO Auto-generated method stubif(a

26、rg1=answerb.getId()displayToast(恭喜你,你答对了!);elsedisplayToast(不好意思,你打错了);); public void displayToast(String str) Toast toast=Toast.makeText(this, str, Toast.LENGTH_LONG); toast.setGravity(Gravity.TOP, 0,200); toast.show(); ToastA toast is a view containing a quick little message for the user. The toas

27、t class helps you create and show those.When the view is shown to the user, appears as a floating view over the application. It will never receive focus. The user will probably be in the middle of typing something else. The idea is to be as unobtrusive as possible, while still showing the user the i

28、nformation you want them to see. Two examples are the volume control, and the brief message saying that your settings have been saved.HYPERLINK file:/C:/Android/android-sdk/docs/reference/java/lang/Object.htmljava.lang.Objectandroid.widget.Toast6. ToggleButtonAndroid:text属性不起作用,起作用的是android:textOff和

29、android:textOn,Android:checked属性可以修改它的默认状态,是否被选中,也可以通过setChecked方法来改变。AutoCompleteTextViewString autoString=new Stringa,ab,abc,bb,bcd,手机,手机操作系统,手机软件;AutoCompleteTextView auto; auto=(AutoCompleteTextView)findViewById(R.id.autoCompleteTextView1); ArrayAdapter adapter=new ArrayAdapter(this,android.R.la

30、yout.simple_dropdown_item_1line,autoString); auto.setAdapter(adapter);创建ListView的2种不同方式:使用系统默认的布局文件,不修改main.xml,只要将Activity设置为ListActivity的子类,并且为其创建适配器,在该Activity类中也不需要书写setContentview方法 setListAdapter(new ArrayAdapter(this, android.R.layout.simple_list_item_1,items); 具体代码如下public class ListViewActi

31、vity extends ListActivity /* Called when the activity is first created. */String items=easy,middle,hard; Override public void onCreate(Bundle savedInstanceState) super.onCreate(savedInstanceState); setListAdapter(new ArrayAdapter(this, android.R.layout.simple_list_item_1,items); Overrideprotected vo

32、id onListItemClick(ListView l, View v, int position, long id) / TODO Auto-generated method stubsuper.onListItemClick(l, v, position, id); 使用自己设定的布局文件,此时要在布局文件中添加一个ListView组件,并为其设定id属性,相应的需要在对应的Activity类中书写setConview方法。ListView的布局图: Activity类:public class ListViewActivity extends ListActivity /* Call

33、ed when the activity is first created. */String items=easy,middle,hard; Override public void onCreate(Bundle savedInstanceState) super.onCreate(savedInstanceState); setContentView(R.layout.main); setListAdapter(new ArrayAdapter(this, android.R.layout.simple_list_item_1,items); Overrideprotected void

34、 onListItemClick(ListView l, View v, int position, long id) / TODO Auto-generated method stubsuper.onListItemClick(l, v, position, id); public class ListAndIntentActivity extends Activity /* Called when the activity is first created. */MediaPlayer song; Override public void onCreate(Bundle savedInst

35、anceState) super.onCreate(savedInstanceState); setContentView(R.layout.main); song=MediaPlayer.create(this, R.raw.moshou); song.start(); Thread timer=new Thread()Overridepublic void run() / TODO Auto-generated method stubtry sleep(2000); catch (InterruptedException e) / TODO Auto-generated catch blo

36、cke.printStackTrace();finally/启动另一个Acitity,该Activity的Action名字为.MenuIntent intent=new Intent(.Menu); startActivity(intent); ; timer.start(); Overrideprotected void onPause() / TODO Auto-generated method stubsuper.onPause();song.stop();finish();public class Menu extends ListActivity String items=MainA

37、ctivity,easy,middle,hard;Overrideprotected void onCreate(Bundle savedInstanceState) / TODO Auto-generated method stubsuper.onCreate(savedInstanceState);setListAdapter(new ArrayAdapter(this, android.R.layout.simple_list_item_1,items);Overrideprotected void onListItemClick(ListView l, View v, int posi

38、tion, long id) / TODO Auto-generated method stubsuper.onListItemClick(l, v, position, id);String cheese=itemsposition;Class ourClass;try ourClass = Class.forName(.+cheese);Intent ourIntent=new Intent(Menu.this,ourClass);startActivity(ourIntent); catch (ClassNotFoundException e) / TODO Auto-generated

39、 catch blocke.printStackTrace(); Android Manifest文件 List, ListActivity, ListView, 和Adatpter, ListAdapter, SimpleAdapter, SimpleCursorAdapter的关系ListActivity是一个Activity,它派生于Activity, 一个ListActivity中必须包含一个ListView一个ListView是用垂直方向显示列表项的View一个List是一个模板集合,它继承自java.util.ListAdapter是一个适配器,一个ListView要与数据项进行绑

40、定,必须通过Adapter。ListAdapter, ArrayAdapter, SimpleAdapter,SimpleCursorAdapter均属于Adapter的子类;常用的有三种, ArrayAdapter, SimpleAdapter,SimpleCursorAdapter,这三种适配器均属于ListAdapter的子类ArrayAdapter最为简单,只能展示一行字。SimpleAdapter有最好的扩充性,可以自定义出各种效果。SimpleCursorAdapter可以认为是SimpleAdapter对数据库的简单结合,可以方面的把数据库的内容以列表的形式展示出来。packag

41、e .fzh;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.ArrayAdapter;import android.widget.ListAdapter;import android.widget.ListView;import android.widget.SimpleAda

42、pter;public class ListView02Activity extends ListActivity /* Called when the activity is first created. */Overrideprotected void onCreate(Bundle savedInstanceState) / TODO Auto-generated method stubsuper.onCreate(savedInstanceState);setContentView(R.layout.main);ArrayListHashMap list =new ArrayListH

43、ashMap();HashMap map1=new HashMap();HashMap map2=new HashMap();HashMap map3=new HashMap();map1.put(user_name, zhangsan);map1.put(user_ip, );map2.put(user_name, lisi);map2.put(user_ip, );map3.put(user_name, wangwu);map3.put(user_ip, );list.add(map1);list.add(map2);list.add(map3);ListAdapter listAdapt

44、er=new SimpleAdapter(this, list, R.layout.user, new Stringuser_name,user_ip, new int R.id.user_name,R.id.user_ip);setListAdapter(listAdapter);Overrideprotected void onListItemClick(ListView l, View v, int position, long id) / TODO Auto-generated method stubsuper.onListItemClick(l, v, position, id);S

45、ystem.out.println(id-+id);System.out.println(position-+position); user.xml package .fzh;import java.util.ArrayList;import java.util.HashMap;import java.util.Map;import android.app.Activity;import android.app.ListActivity;import android.os.Bundle;import android.widget.Adapter;import android.widget.Im

46、ageView;import android.widget.ListAdapter;import android.widget.ListView;import android.widget.SimpleAdapter;import android.widget.TextView;public class ImageListActivity extends ListActivity /* Called when the activity is first created. */private String names=new String李白,弄玉,李清照,虎头;private int imag

47、eIds=new intR.drawable.libai,R.drawable.nongyu,R.drawable.qingzhao, R.drawable.tiger; Override public void onCreate(Bundle savedInstanceState) super.onCreate(savedInstanceState); ArrayListMap listItems=new ArrayListMap(); for(int i=0;inames.length;i+) Map listItem=new HashMap(); listItem.put(header,

48、 imageIdsi); listItem.put(names, namesi); listItems.add(listItem); ListAdapter listAdapter=new SimpleAdapter(this, listItems, R.layout.user, new Stringheader,names, new intR.id.header,R.); setListAdapter(listAdapter); Android中的基本控件(上) 下拉列表:Spinner下拉列表框也是一种常见的图形组件,它可以为用户提供列表的选则方式,与复选框或单选钮相比还可以节省手机的屏幕

49、空间,在Android中可以使用android.widget.Spinner类实现,此类定义如下: java.lang.Object android.view.View android.view.ViewGroup android.widget.AdapterView android.widget.AbsSpinner android.widget.Spinner Spinner类的常用方法 No.方法类型描述1public CharSequence getPrompt ()普通取得提示文字2public void setPrompt (CharSequence prompt)普通设置组件的提

50、示文字3public void setAdapter (SpinnerAdapter adapter)普通设置下拉列表项4public CharSequence getPrompt()普通得到提示信息5public void setOnItemClickListener(AdapterView.OnItemClickListener l)普通设置选项单击事件配置列表项在Android中,可以直接在main.xml文件中定义“”节点,但是在定义此元素的时候却不能直接设置其显示的列表项,关于下拉列表框中的列表项有以下两种方式进行配置: 方式一:直接通过资源文件配置;方式二:通过android.wi

51、dget.ArrayAdapter类读取资源文件或者是指定具体设置的数据;方式一:直接通过资源文件配置 定义一个values/city_data.xml文件,在定义数据内容的时候需要使用“”元素指定,定义内容如下: 北京上海南京这个时候定义的是一个“string-array”的根节点,表示里面配置的是一个数组的集合,而里面的每一个“”节点表示的就是每一个列表项的内容,随后在layout/main.xml文件定义“”节点的时候直接使用“android:entries=array/city_labels”属性就可以读取信息了方式二:通过android.widget.ArrayAdapter类 Ar

52、rayAdapter类的功能:有两个主要功能:读取资源文件中定义的列表项或者是通过List集合设置列表项,此类定义了如下几个常用方法。ArrayAdapter类的常用方法 No.方法类型描述1public ArrayAdapter (Context context, int textViewResourceId, List objects)构造定义ArrayAdapter对象,同时向里面传入一个Activity实例(this)、列表项的显示风格(每次之显示一行数据)、List集合数据2public ArrayAdapter (Context context, int textViewResou

53、rceId, T objects)构造定义ArrayAdapter对象,同时向里面传入一个Activity实例(this)、列表项的显示风格(每次之显示一行数据)、数组数据3public static ArrayAdapter createFromResource (Context context, int textArrayResId, int textViewResId)普通通过静态方法取得ArrayAdapter对象,传入Activity实例、资源文件的id、列表项的显示风格4public void setDropDownViewResource (int resource)普通设置下拉

54、列表项的显示风格注意:对于下拉列表项的显示风格一般都会将其设置为:“android.R.layout.simple_spinner_item”,下面分别在values文件夹之中定义两个资源文件,用于保存所需要的下拉列表信息。 定义两个资源文件定义表示城市的资源信息文件 values/city_data.xml 北京上海南京定义表示颜色信息的资源文件 values/color_data.xml 北京上海南京定义表示颜色信息的资源文件 values/color_data.xml 红色绿色蓝色定义下拉列表框 layout/main.xml布局管理器高度为屏幕高度组件的高度为文字高度定义使用的文本资源

55、定义下拉列表框 layout/main.xml布局管理器高度为屏幕高度 组件的高度为文字高度组件的高度为文字高度程序说明:本程序分别使用“”节点分别定义了三个下拉列表框:列表框一,+id/mycity:直接通过“android:entries=”array/city_labels”读取了资源city_data文件中“”元素中配置name属性为“city_labels”的信息,并将此资源文件中定义的列表项设置到了下拉列表框之中,而列表框的提示信息直接在strings.xml文件中定义(定义的名称为“city_prompt”); 列表框二,+id/mycolor:只是定义了一个下拉列表框组件,此组

56、件的内容要通过程序读取资源文件设置; 列表框三,+id/myedu:定义一个下拉列表框组件,以后直接通过程序进行内容的设置。 范例:定义提示信息 values/strings.xmlHello World, MySpinnerDemo!MySpinnerDemo请选择您喜欢的城市:public class MySpinnerDemo extends Activity private Spinner spiColor = null; / 定义表示颜色的列表框private Spinner spiEdu = null; / 定义表示学历的列表框private ArrayAdapter adapte

57、rColor = null; / 下拉列表内容适配器private ArrayAdapter adapterEdu = null; / 下拉列表内容适配器private List dataEdu = null; / 集合保存下拉列表选项Overridepublic void onCreate(Bundle savedInstanceState) super.onCreate(savedInstanceState);/ 父类onCreate()方法super.setContentView(R.layout.main);/ 调用布局管理器this.spiColor = (Spinner) supe

58、r.findViewById(R.id.mycolor);/ 取出组件this.spiColor.setPrompt(请选择您喜欢的颜色:); / 定义提示信息this.adapterColor = ArrayAdapter.createFromResource(this,R.array.color_labels, android.R.layout.simple_spinner_item); / 从资源文件读取选项this.adapterColor.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);/

59、设置列表显示风格this.spiColor.setAdapter(this.adapterColor); / 设置下拉列表选项this.dataEdu = new ArrayList(); / 实例化List集合this.dataEdu.add(大学); / 设置选项内容this.dataEdu.add(研究生); / 设置选项内容this.dataEdu.add(高中); / 设置选项内容this.spiEdu = (Spinner) super.findViewById(R.id.myedu); / 取得下拉列表框this.spiEdu.setPrompt(请选择您喜欢的学历:); / 设

60、置提示信息this.adapterEdu = new ArrayAdapter(this,android.R.layout.simple_spinner_item, this.dataEdu); / 定义下拉列表项this.adapterEdu.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);/ 设置下拉列表显示风格this.spiEdu.setAdapter(this.adapterEdu); / 设置下拉列表选项显示提示对话框首先只是显示一个确认按钮的简单对话框,代码如下: Button dial

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论