Android4开发入门经典 之 第四部分:用户界面
基本概念
常用Widgets和布局
常用的Widgets
常用的Layout
Android常用的Widgets的属性大同小异,这里以TextView为例来看一看
- TextView tv = new TextView(this);
- SpannableStringBuilder style=new SpannableStringBuilder("这是测试111");
- style.setSpan(new ForegroundColorSpan(Color.RED), 0, 2, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
- style.setSpan(new ForegroundColorSpan(Color.YELLOW), 2, 4, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
- style.setSpan(new ForegroundColorSpan(Color.BLUE), 4, 6, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
- tv.setText(style);
Button
Small的Button
- <ToggleButton
- android:textOn="设置选定状态的显示文本"
- android:textOff="设置未选状态的显示文本"
- ......
- />
- ImageButton
- <ImageButton
- android:src="@drawable/myimg" ......
- />
EditText
Checkbox、RadioGroup和RadioButton
配置的示例如下
- <RadioGroup
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:orientation="vertical"
- android:checkedButton="@+id/mycolor"
- android:id="@+id/menu">
- <RadioButton
- android:text="red"
- android:id="@+id/red"
- />
- <RadioButton
- android:text="green"
- android:id="@+id/green" />
- <RadioButton
- android:text="blue"
- android:id="@+id/blue" />
- <TextView
- android:text="请选择颜色"
- android:id="@+id/choice" />
- </RadioGroup>
Spinner
配置的示例如下
- <Spinner android:id="@+id/spinner"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:drawSelectorOnTop="true"
- android:prompt="@string/select_color"
- />
准备数据,如果是固定的数据,可以在string下面新建一个arrays.xml,内容配置的示例如下:
- <resources>
- <string-array name="colors">
- <item>red</item>
- <item>green</item>
- <item>blue</item>
- </string-array>
- </resources>
在程序里面把数据设置到Spinner,示例代码如下:
- final Spinner sp = (Spinner)this.findViewById(R.id.spinner);
- //准备数据
- ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
- this, R.array.colors, android.R.layout.simple_spinner_item);
- adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
- //把数据设置到spinner
- sp.setAdapter(adapter);
如果是动态的数据,可以不用定义arrys.xml,而完全用程序设置,示例代码:
- ArrayAdapter<CharSequence> adapter = new ArrayAdapter<CharSequence>(this,android.R.layout.simple_spinner_item);
- adapter.add("red");
- adapter.add("blue");
- sp.getSelectedItem().toString()
ProgressBar
基本的进度条,直接在布局文件里面配置,示例如下:
- <ProgressBar
- android:id="@+id/progress_horizontal"
- style="?android:attr/progressBarStyleHorizontal"
- android:layout_width="200dip"
- android:layout_height="wrap_content"
- android:max="100"
- android:progress="10"
- android:secondaryProgress="20" />
ImageView
主要是在布局文件里面配置,常见属性如下:
DatePicker
在创建Dialog的回调方法中,去真正创建DatePickerDialog,示例代码如下:
- protected Dialog onCreateDialog(int id) {
- switch (id) {
- case 1:
- return new DatePickerDialog(this,
- mDateSetListener,
- mYear, mMonth, mDay);
- }
- return null;
- }
TimePicker
在创建Dialog的回调方法中,去真正创建TimePickerDialog,示例代码如下:
- protected Dialog onCreateDialog(int id) {
- switch (id) {
- case TIME_DIALOG_ID:
- return new TimePickerDialog(this,
- mTimeSetListener, mHour, mMinute, false);
- }
- return null;
- }
RatingBar
常用属性如下:
Gallery
Gallery的使用相对要麻烦一点,首先在布局文件里面要定义
- class ImageAdapter extends BaseAdapter {
- private Context mContext;
- private Integer[] mImageIds = {R.drawable.icon,R.drawable.icon,
- R.drawable.icon,R.drawable.icon,R.drawable.icon,R.drawable.icon,
- R.drawable.icon,R.drawable.icon,R.drawable.icon,R.drawable.icon};
- public ImageAdapter(Context c) { mContext = c; }
- public int getCount() { return mImageIds.length; }
- public Object getItem(int position) { return position; }
- public long getItemId(int position) { return position; }
- public View getView(int position, View convertView, ViewGroup parent) {
- ImageView imageView = new ImageView(mContext);
- imageView.setImageResource(mImageIds[position]);
- imageView.setLayoutParams(new Gallery.LayoutParams(150, 100));
- imageView.setScaleType(ImageView.ScaleType.FIT_XY);
- return imageView;
- }
- }
如果要给Gallery设置风格的话,需要在res/values文件夹下面创建一个attrs.xml,示例代码如下:
- <?xml version="1.0" encoding="utf-8"?>
- <resources>
- <declare-styleable name="MyGallery">
- <attr name="android:galleryItemBackground" />
- </declare-styleable>
- </resources>
然后在自定义的适配器里面,在构造方法里面,添加如下的代码:
- TypedArray attr = mContext.obtainStyledAttributes(R.styleable.MyGallery);
- mGalleryItemBackground = attr.getResourceId(
- R.styleable.MyGallery_android_galleryItemBackground, 0);
有了风格过后,在创建ImageView的时候,就可以使用这个风格了,在getView方法里面添加如下代码:
- imageView.setBackgroundResource(mGalleryItemBackground);
AutoComplete
然后在程序里面,为它设置值,示例代码如下:
- AutoCompleteTextView textView = (AutoCompleteTextView) findViewById(R.id.autocomplete);
- ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.autoc_item, new String[]{"abc","abd","abcd","bcd","bef"});
- textView.setAdapter(adapter);
- <TextView xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- android:padding="10dp"
- android:textSize="16sp"
- android:textColor="#ff0000">
- </TextView>
首先在布局文件设置使用MultiAutoCompleteTextView,示例代码如下:
- <MultiAutoCompleteTextView android:id="@+id/autocomplete"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- />
然后在程序中,为他设置值,示例代码如下:
- MultiAutoCompleteTextView textView = (MultiAutoCompleteTextView) findViewById(R.id.autocomplete);
- ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.autoc_item, new String[]{"abc","abd","abcd","bcd","bef"});
- textView.setAdapter(adapter);
- textView.setTokenizer(new MultiAutoCompleteTextView.CommaTokenizer());
LinearLayout
- <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:orientation="horizontal"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- android:layout_weight="1">
- <TextView
- android:text="red"
- android:gravity="center_horizontal"
- android:background="#ff0000"
- android:layout_width="wrap_content"
- android:layout_height="fill_parent"
- android:layout_weight="1"/>
- <TextView
- android:text="green"
- android:gravity="center_horizontal"
- android:background="#00ff00"
- android:layout_width="wrap_content"
- android:layout_height="fill_parent"
- android:layout_weight="1"/>
- <TextView
- android:text="blue"
- android:gravity="center_horizontal"
- android:background="#0000ff"
- android:layout_width="wrap_content"
- android:layout_height="fill_parent"
- android:layout_weight="1"/>
- <TextView
- android:text="yellow"
- android:gravity="center_horizontal"
- android:background="#aaaa00"
- android:layout_width="wrap_content"
- android:layout_height="fill_parent"
- android:layout_weight="1"/>
- </LinearLayout>
- <LinearLayout
- android:orientation="vertical"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- android:layout_weight="1">
- <TextView
- android:text="第一行"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:layout_weight="1"/>
- <TextView
- android:text="第二行"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:layout_weight="1"/>
- <TextView
- android:text="第三行"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:layout_weight="1"/>
- </LinearLayout>
- </LinearLayout>
RelativeLayout
- <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent">
- <TextView
- android:id="@+id/label"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:text="请输入:"/>
- <EditText
- android:id="@+id/entry"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:background="@android:drawable/editbox_background"
- android:layout_below="@id/label"/>
- <Button
- android:id="@+id/ok"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_below="@id/entry"
- android:layout_alignParentRight="true"
- android:layout_marginLeft="10dip"
- android:text="确定" />
- <Button
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_toLeftOf="@id/ok"
- android:layout_alignTop="@id/ok"
- android:text="取消" />
- </RelativeLayout>
TableLayout
- <TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- android:stretchColumns="1">
- <TableRow>
- <TextView android:layout_column="1" android:text="张三" android:padding="3dip" />
- <TextView
- android:text="25岁" android:gravity="right" android:padding="3dip" />
- </TableRow>
- <TableRow>
- <TextView android:layout_column="1" android:text="李四" android:padding="3dip" />
- <TextView
- android:text="22岁"
- android:gravity="right"
- android:padding="3dip" />
- </TableRow>
- <View android:layout_height="2dip" android:background="#FF909090" />
- <TableRow>
- <TextView
- android:text="王五"
- android:padding="3dip" />
- <TextView
- android:text="本科毕业"
- android:padding="3dip" />
- <TextView
- android:text="23岁"
- android:gravity="right"
- android:padding="3dip" />
- </TableRow>
- </TableLayout>
TableLayout的常用属性如下:
GridView
首先在布局文件里面配置使用GridView,示例代码如下:
- <GridView xmlns:android="http://schemas.android.com/apk/res/android"
- android:id="@+id/gridview"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- android:columnWidth="50dp"
- android:numColumns="5"
- android:verticalSpacing="10dp"
- android:horizontalSpacing="2dp"
- android:stretchMode="columnWidth"
- android:gravity="center"
- />
然后在程序里面,为它设置值,示例代码如下:
- GridView gridview = (GridView) findViewById(R.id.gridview);
- gridview.setAdapter(new ImageAdapter(this));
然后在程序里面,为它设置值,需要使用一个自定义的Adapter,示例代码如下:
- class ImageAdapter extends BaseAdapter {
- private Context mContext;
- public ImageAdapter(Context c) { mContext = c; }
- public int getCount() {return mThumbIds.length; }
- public Object getItem(int position) { return null;}
- public long getItemId(int position) { return 0; }
- public View getView(int position, View convertView, ViewGroup parent) {
- ImageView imageView;
- if (convertView == null) {
- imageView = new ImageView(mContext);
- imageView.setLayoutParams(new GridView.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
- imageView.setScaleType(ImageView.ScaleType.FIT_XY);
- imageView.setPadding(0, 0,0,0);
- imageView.setBackgroundColor(Color.RED);
- } else {
- imageView = (ImageView) convertView;
- }
- imageView.setImageResource(mThumbIds[position]);
- return imageView;
- }
- private Integer[] mThumbIds = {
- R.drawable.icon, R.drawable.icon,
- R.drawable.icon, R.drawable.icon,
- R.drawable.icon, R.drawable.icon,
- R.drawable.icon, R.drawable.icon
- };
- }
事件处理是实现OnItemClickListener,示例代码如下:
- gridview.setOnItemClickListener(new OnItemClickListener() {
- public void onItemClick(AdapterView<?> parent, View v,
- int position, long id) {
- Toast.makeText(TestWidgets.this, "" + position,
- Toast.LENGTH_SHORT).show();
- }
- });
TabLayout
要实现基本的TabLayout,首先需要在布局文件里面定义,示例代码如下:
- <TabHost xmlns:android="http://schemas.android.com/apk/res/android"
- android:id="@android:id/tabhost"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent">
- <LinearLayout
- android:orientation="vertical"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- android:padding="5dp">
- <TabWidget
- android:id="@android:id/tabs"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content" />
- <FrameLayout
- android:id="@android:id/tabcontent"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- android:padding="5dp" />
- </LinearLayout>
- </TabHost>nTabHost就是用来存放多个Tab的容器
TabWidget就是实现Tab的Widget
有了布局过后,就可以直接在程序里面设置Tab了,示例如下:
2:得到TabHost,示例代码如下:
- TabHost tabHost = getTabHost();
3:创建一个Intent对象,做为点击tab后的事件响应,示例代码如下:
- Intent intent = new Intent().setClass(this, MyActivity.class);
- intent.putExtra("showStr", "第一个tab");
- Intent设置的Class就是点击tab,内容页显示出来的Activity。
5:然后把这个TabSpec添加到TabHost中即可,示例代码如下:
- tabHost.addTab(spec);
如果想要给Tab设置图片,方法步骤如下:
- <?xml version="1.0" encoding="utf-8"?>
- <selector xmlns:android="http://schemas.android.com/apk/res/android">
- <item android:drawable="@drawable/icon2"
- android:state_selected="true" />
- <item android:drawable="@drawable/icon" />
- </selector>
- Resources res = getResources();
- spec = tabHost.newTabSpec("FirstTag").setIndicator(
- "第一个Tab",res.getDrawable(R.drawable.my_tab1_selector))
- .setContent(intent);
ListView
对于最基本的ListView,直接在代码里面写,示例如下:
- public class TestList extends ListActivity {
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- // this.setContentView(R.layout.TestList);
- setListAdapter(new ArrayAdapter<String>(this,
- android.R.layout.simple_list_item_1, new String[]{"111","222","333"}));
- }
- protected void onListItemClick(ListView l,View v,int position,long id){
- super.onListItemClick(l, v, position, id);
- String s = ""+l.getItemAtPosition(position);
- System.out.println("now click="+s);
- }
- }
List的单选模式,示例代码如下:
- setListAdapter(new ArrayAdapter<String>(this,
- android.R.layout. simple_list_item_single_choice, new String[]{"111","222","333}));
- this.getListView().setItemsCanFocus(false);
- this.getListView().setChoiceMode(ListView. CHOICE_MODE_SINGLE);
List的多选模式,示例代码如下:
- setListAdapter(new ArrayAdapter<String>(this,
- android.R.layout.simple_list_item_multiple_choice, new String[]{"111","222","333}));
- this.getListView().setItemsCanFocus(false);
- this.getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
在ListView里面设置多个值的方法
在ListView的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 xmlns:android="http://schemas.android.com/apk/res/android"
- android:orientation="vertical"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- >
- <ListView
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- android:padding="10dp"
- android:textSize="16sp"
- android:id="@id/android:list"
- >
- </ListView>
- </LinearLayout>
- </LinearLayout>
在ListView的Item的布局文件中
- <?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"
- >
- <RelativeLayout
- android:layout_width="fill_parent"
- android:layout_height="fill_parent">
- <TextView
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:id="@+id/userId"
- >
- </TextView>
- <TextView
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:id="@+id/userName"
- android:layout_marginLeft="20dip"
- android:layout_toRightOf="@id/userId"
- >
- </TextView>
- <TextView
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:id="@+id/userAge"
- android:layout_marginLeft="20dip"
- android:layout_toRightOf="@id/userName"
- >
- </TextView>
- </RelativeLayout>
- </LinearLayout>
在java程序中
- List list = new ArrayList();
- Map map1 = new HashMap();
- map1.put("userId","11");
- map1.put("userName","11N");
- map1.put("age","11");
- list.add(map1);
- Map map2 = new HashMap();
- map2.put("userId","22");
- map2.put("userName","22N");
- map2.put("age","22");
- list.add(map2);
- setListAdapter(new SimpleAdapter(this, list,R.layout.list,new String[]{"userId","userName","age"}, new int[]{R.id.userId,R.id.userName,R.id.userAge}));
- protected void onListItemClick(ListView l, View v, int position, long id) {
- super.onListItemClick(l, v, position, id);
- System.out.println("sssssssss===="+l.getItemAtPosition(position));
菜单
在Android系统中,菜单分成三种
创建菜单资源
- <menu xmlns:android="http://schemas.android.com/apk/res/android">
- <item android:id="@+id/to_add"
- android:icon="@drawable/icon"
- android:title="转向新增" />
- <item android:id="@+id/to_update"
- android:icon="@drawable/icon"
- android:title="转向修改" />
- </menu>
- public boolean onCreateOptionsMenu(Menu menu) {
- MenuInflater inflater = getMenuInflater();
- inflater.inflate(R.menu.test_menu, menu);
- return true;
- }
响应菜单,在程序里面,需要写代码来实现菜单被点击后要实现的功能
- public boolean onOptionsItemSelected(MenuItem item) {
- switch (item.getItemId()) {
- case R.id.to_add:
- Log.i("javass","now to add"); break;
- case R.id.to_update:
- Log.i("javass","now to update"); break;
- default: return super.onOptionsItemSelected(item);
- }
- return true;
- }
- public void myToAdd(MenuItem item) {
- Log.i("javass","now in myToAdd");
- }
上下文菜单
上下文菜单就相当于PC上的右击,创建上下文菜单:
- this.registerForContextMenu(btnRun);
- public void onCreateContextMenu(ContextMenu menu,View v,ContextMenuInfo info) {
- super.onCreateContextMenu(menu, v, info);
- MenuInflater inflater = getMenuInflater();
- inflater.inflate(R.menu.test_menu, menu);
- }
- public boolean onContextItemSelected(MenuItem item) {
- AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
- switch (item.getItemId()) {
- case R.id. new_file:
- Log.i("onContextItemSelected", "now ruuuuuuuuuuu");
- return true;
- default: return super.onContextItemSelected(item);
- }
- }
子菜单
创建子菜单非常简单,只需要在菜单资源文件中配置即可,示例如下:
- <item android:id="@+id/new_file"
- android:icon="@drawable/ic_launcher"
- android:title="@string/new_file"
- >
- <menu>
- <item android:id="@+id/create_new"
- android:title="now new" />
- <item android:id="@+id/open"
- android:title="now open" />
- </menu>
- </item>
给菜单分组
给菜单分组非常简单,只需要在菜单资源文件中配置即可,示例如下:
- <group android:id="@+id/group1">
- <item android:id="@+id/create_new"
- android:icon="@drawable/ic_launcher"
- android:title="now new" />
- <item android:id="@+id/open"
- android:icon="@drawable/ic_launcher"
- android:title="now open" />
- </group>
分组后能干什么
可选菜单
可选菜单非常简单,只需要在菜单资源文件中配置即可,示例如下:
可选菜单一般针对上下文菜单和子菜单
1:对于Options的子菜单,可以在onPrepareOptionsMenu方法里面设置状态,示例代码如下:
- public boolean onPrepareOptionsMenu(Menu menu) {
- super.onPrepareOptionsMenu(menu);
- MenuItem mi = menu.findItem(R.id.create_new);
- mi.setChecked(flag);
- return true;
- }
动态修改菜单项
有些时候,需要动态的修改菜单项,该怎么实现呢?
对于Options的菜单及其子菜单
onPrepareOptionsMenu方法和onCreateOptionsMenu方法
编程式实现菜单
前面是声明式实现菜单,也可以采用编程式的方式来实现菜单,常用API为:
关于Menu的图标
Action Bar基本概念
是什么
特点
使用Action Bar
删除Action Bar
- <activity android:theme="@android:style/Theme.Holo.NoActionBar">
- ActionBar actionBar = getActionBar();
- actionBar.hide();
添加Action View
- <menu xmlns:android="http://schemas.android.com/apk/res/android">
- <item android:id="@+id/menu_search"
- android:title="Search"
- android:icon="@drawable/ic_menu_search"
- android:showAsAction="ifRoom"
- android:actionLayout="@layout/searchview" />
- </menu>
- 或者把android:actionLayout=“@layout/searchview” 换成:
- android:actionViewClass="android.widget.SearchView"
1:简单的修改,可以通过:
- ActionBar actionBar = getActionBar();
- actionBar.setDisplayUseLogoEnabled(true);
- actionBar.setLogo(R.drawable.app_sample_code);
- actionBar.setBackgroundDrawable(this.getResources().getDrawable(R.drawable.app_sample_code));
- <activity android:name=".ExampleActivity"
- android:theme="@android:style/Theme.Holo.Light" />
Dialogs
什么是Dialog
常见的Dialog
创建和显示Dialog
关闭Dialog
Dismiss listener
实现Dialog风格的Activity
Alert Dialog
创建带Button的Alert Dialog
- AlertDialog.Builder builder = new AlertDialog.Builder(this);
- builder.setMessage("确定要删除吗?")
- .setCancelable(false)
- .setPositiveButton("取消",
- new DialogInterface.OnClickListener() {
- public void onClick(DialogInterface dialog,int id) {
- Toast.makeText(HelloWorldActivity.this, “dialog取消", Toast.LENGTH_LONG).show();
- }
- })
- .setNegativeButton("确定",
- new DialogInterface.OnClickListener() {
- public void onClick(DialogInterface dialog,int id) { Toast.makeText(HelloWorldActivity.this,“dialog确定", Toast.LENGTH_LONG).show();
- }
- });
- AlertDialog alert = builder.create();
- final CharSequence[] items = { "红色", "绿色", "蓝色" };
- AlertDialog.Builder builder = new AlertDialog.Builder(this);
- builder.setTitle("请选择颜色");
- builder.setItems(items, new DialogInterface.OnClickListener() {
- public void onClick(DialogInterface dialog, int item) {
- Toast.makeText(getApplicationContext(), items[item],
- Toast.LENGTH_SHORT).show();
- }
- });
- AlertDialog alert = builder.create();
- final CharSequence[] items = { "红色", "绿色", "蓝色" };
- AlertDialog.Builder builder = new AlertDialog.Builder(this);
- builder.setTitle("请选择颜色");
- builder.setSingleChoiceItems(items, -1,new DialogInterface.OnClickListener() {
- public void onClick(DialogInterface dialog, int item) {
- Toast.makeText(getApplicationContext(), items[item],
- Toast.LENGTH_SHORT).show();
- dialog.dismiss();
- }
- });
- AlertDialog alert = builder.create();
- inal CharSequence[] items = { "红色", "绿色", "蓝色" };
- AlertDialog.Builder builder = new AlertDialog.Builder(this);
- builder.setTitle("请选择颜色");
- builder.setMultiChoiceItems(items, new boolean[]{false,false,false},new DialogInterface.OnMultiChoiceClickListener() {
- public void onClick(DialogInterface dialog, int which, boolean isChecked) {
- Toast.makeText(getApplicationContext(), items[which], Toast.LENGTH_SHORT).show();
- }
- });
- builder.setNegativeButton("确定",
- new DialogInterface.OnClickListener() {
- public void onClick(DialogInterface dialog, int id) {
- Toast.makeText(HelloWorldActivity.this, "dialog确定", Toast.LENGTH_LONG).show();
- dialog.dismiss();
- }
- }
- );
- AlertDialog alert = builder.create();
Progress Dialog
Progress Dialog扩展自Alert Dialog
- HandlerThread ht = new HandlerThread("MyThread");
- Handler h = null;
- if(!ht.isAlive()){
- ht.start();
- h = new Handler(ht.getLooper()){
- public void handleMessage(Message msg) {
- try {
- Thread.sleep(5000L);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- HelloWorldActivity.this.dismissDialog(1);
- super.handleMessage(msg);
- }
- };
- }
- Message msg = h.obtainMessage();
- msg.sendToTarget();
使用Progress Bar,同样需要配合Handler来执行,示例如下:
1:创建Progress Bar,在onCreateDialog方法里面,示例如下:
- dialog = new ProgressDialog(HelloWorldActivity.this);
- dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
- dialog.setMessage("装载中...");
- dialog.setCancelable(false);
- dialog.setMax(10);
2:定义Handler和Runnable
- Handler h = new Handler() {
- public void handleMessage(Message msg) {
- super.handleMessage(msg);
- if(msg.arg1 < dialog.getMax()){dialog.setProgress(msg.arg1);}
- else{dialog.dismiss();}}};
- int num = 0;
- Runnable r = new Runnable() {
- public void run() {
- Message msg = h.obtainMessage();
- msg.arg1 = num++;
- h.sendMessage(msg);
- h.postDelayed(r, 1000L);
- }};
也可以通过配置文件来使用Progress Bar,同样需要配合Handler来执行,示例如下:
1:在layout的配置文件里面创建Progress Bar,示例如下:
- <ProgressBar
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:id="@+id/progress_bar"
- style="?android:attr/progressBarStyleHorizontal"
- android:visibility="gone"
- />
2:在程序中启动Progress Bar,示例如下:
- pb = (ProgressBar)HelloWorldActivity.this.findViewById(R.id.progress_bar);
- pb.setMax(10);
- pb.setVisibility(View.VISIBLE);
- h.post(r);
Customer Dialog
如果想要使用自己订制的Dialog,那么首先需要定义自己的布局,示例如下:
- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:id="@+id/layout_root"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- android:orientation="horizontal"
- android:padding="10dp" >
- <ImageView
- android:id="@+id/image"
- android:layout_width="wrap_content"
- android:layout_height="fill_parent"
- android:layout_marginRight="10dp" />
- <TextView
- android:id="@+id/text"
- android:layout_width="wrap_content"
- android:layout_height="fill_parent"
- />
- </LinearLayout>
在程序中获取这些对象,然后设置相应的属性,再显示出来,示例如下:
- Context mContext = HelloWorldActivity.this;
- Dialog dialog = new Dialog(mContext);
- dialog.setContentView(R.layout.my_dialog);
- dialog.setTitle("自己订制的Dialog");
- TextView text = (TextView) dialog.findViewById(R.id.text);
- text.setText("欢迎使用本系统");
- ImageView image = (ImageView) dialog.findViewById(R.id.image);
- image.setImageResource(R.drawable.ic_launcher);
- //最后显示出来
- dialog.show();
Handler
Handler概述
Handler使用
Handler
- Handler h = new Handler() {
- public void handleMessage(Message msg) {
- super.handleMessage(msg);
- //使用what来区分是什么样的消息
- switch (msg.what){
- case 1 :
- //这里进行消息的处理
- break;
- default :
- //这里进行消息的处理
- }
- }};
- int what = 0;
- Runnable r = new Runnable() {
- public void run() {
- Message msg = h.obtainMessage();
- msg.obj = "1234567";//传递的参数
- msg.what = what;
- what++;
- h.sendMessage(msg);
- h.postDelayed(r, 1000L);
- }};
如果想要启动新的线程来处理,使用HandlerThread的示例如下:
- HandlerThread ht = new HandlerThread("MyThread");
- Handler h = null;
- ht.start();
- h = new Handler(ht.getLooper()){
- public void handleMessage(Message msg) {
- super.handleMessage(msg);
- //这里真正处理消息
- Toast.makeText(getApplicationContext(),"msg="+msg.obj,Toast.LENGTH_LONG).show();
- }
- };
- Message msg = h.obtainMessage();
- msg.obj="test message";
- msg.sendToTarget();
Notifications
Android系统中,有如下通知类型:
指定Toast的位置,使用Gravity属性,示例如下:
- Toast t = Toast.makeText(HelloWorldActivity.this,"okok", Toast.LENGTH_SHORT);
- t.setGravity(Gravity.TOP|Gravity.LEFT, 5,10);
- t.show();
订制Toast,需订制布局文件,这里使用上一个示例的布局文件来示例,程序写法如下:
- LayoutInflater inflater = getLayoutInflater();
- View layout = inflater.inflate(R.layout.my_dialog,
- (ViewGroup) findViewById(R.id.layout_root));
- ImageView image = (ImageView) layout.findViewById(R.id.image);
- image.setImageResource(R.drawable.ic_launcher);
- TextView text = (TextView) layout.findViewById(R.id.text);
- text.setText("欢迎您的到来!");
- Toast t = new Toast(HelloWorldActivity.this);
- t.setView(layout);
- t.setGravity(Gravity.CENTER|Gravity.LEFT, 5,10);
- t.show();
Status Bar Notification :可以由Activity或Service发出。示例如下:
- //获取NotificationManager
- String ns = Context.NOTIFICATION_SERVICE;
- NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);
- //设置在status bar上显示的信息条
- int icon = R.drawable.app_sample_code;
- CharSequence tickerText = "请注意";
- long when = System.currentTimeMillis();
- Notification notification = new Notification(icon, tickerText, when);
- //设置在status 列表里面显示的信息,以及点击的事件
- CharSequence contentTitle = "重要通知";
- CharSequence contentText = "测试";
- Intent notificationIntent = new Intent(HelloWorldActivity.this, T2.class);
- PendingIntent contentIntent = PendingIntent.getActivity(HelloWorldActivity.this, 0, notificationIntent, 0);
- notification.setLatestEventInfo(HelloWorldActivity.this, contentTitle, contentText, contentIntent);
- //发出通知
- mNotificationManager.notify(1, notification);
为Notification添加其他特性
客户化的Notification,只是客户化在通知信息列表里面的展示,其他的跟前面仍然是一样的,示例如下:
基本概念
常用Widgets和布局
常用的Widgets
常用的Layout
Android常用的Widgets的属性大同小异,这里以TextView为例来看一看
- TextView tv = new TextView(this);
- SpannableStringBuilder style=new SpannableStringBuilder("这是测试111");
- style.setSpan(new ForegroundColorSpan(Color.RED), 0, 2, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
- style.setSpan(new ForegroundColorSpan(Color.YELLOW), 2, 4, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
- style.setSpan(new ForegroundColorSpan(Color.BLUE), 4, 6, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
- tv.setText(style);
Button
Small的Button
- <ToggleButton
- android:textOn="设置选定状态的显示文本"
- android:textOff="设置未选状态的显示文本"
- ......
- />
- ImageButton
- <ImageButton
- android:src="@drawable/myimg" ......
- />
EditText
Checkbox、RadioGroup和RadioButton
配置的示例如下
- <RadioGroup
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:orientation="vertical"
- android:checkedButton="@+id/mycolor"
- android:id="@+id/menu">
- <RadioButton
- android:text="red"
- android:id="@+id/red"
- />
- <RadioButton
- android:text="green"
- android:id="@+id/green" />
- <RadioButton
- android:text="blue"
- android:id="@+id/blue" />
- <TextView
- android:text="请选择颜色"
- android:id="@+id/choice" />
- </RadioGroup>
Spinner
配置的示例如下
- <Spinner android:id="@+id/spinner"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:drawSelectorOnTop="true"
- android:prompt="@string/select_color"
- />
准备数据,如果是固定的数据,可以在string下面新建一个arrays.xml,内容配置的示例如下:
- <resources>
- <string-array name="colors">
- <item>red</item>
- <item>green</item>
- <item>blue</item>
- </string-array>
- </resources>
在程序里面把数据设置到Spinner,示例代码如下:
- final Spinner sp = (Spinner)this.findViewById(R.id.spinner);
- //准备数据
- ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
- this, R.array.colors, android.R.layout.simple_spinner_item);
- adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
- //把数据设置到spinner
- sp.setAdapter(adapter);
如果是动态的数据,可以不用定义arrys.xml,而完全用程序设置,示例代码:
- ArrayAdapter<CharSequence> adapter = new ArrayAdapter<CharSequence>(this,android.R.layout.simple_spinner_item);
- adapter.add("red");
- adapter.add("blue");
- sp.getSelectedItem().toString()
ProgressBar
基本的进度条,直接在布局文件里面配置,示例如下:
- <ProgressBar
- android:id="@+id/progress_horizontal"
- style="?android:attr/progressBarStyleHorizontal"
- android:layout_width="200dip"
- android:layout_height="wrap_content"
- android:max="100"
- android:progress="10"
- android:secondaryProgress="20" />
ImageView
主要是在布局文件里面配置,常见属性如下:
DatePicker
在创建Dialog的回调方法中,去真正创建DatePickerDialog,示例代码如下:
- protected Dialog onCreateDialog(int id) {
- switch (id) {
- case 1:
- return new DatePickerDialog(this,
- mDateSetListener,
- mYear, mMonth, mDay);
- }
- return null;
- }
TimePicker
在创建Dialog的回调方法中,去真正创建TimePickerDialog,示例代码如下:
- protected Dialog onCreateDialog(int id) {
- switch (id) {
- case TIME_DIALOG_ID:
- return new TimePickerDialog(this,
- mTimeSetListener, mHour, mMinute, false);
- }
- return null;
- }
RatingBar
常用属性如下:
Gallery
Gallery的使用相对要麻烦一点,首先在布局文件里面要定义
- class ImageAdapter extends BaseAdapter {
- private Context mContext;
- private Integer[] mImageIds = {R.drawable.icon,R.drawable.icon,
- R.drawable.icon,R.drawable.icon,R.drawable.icon,R.drawable.icon,
- R.drawable.icon,R.drawable.icon,R.drawable.icon,R.drawable.icon};
- public ImageAdapter(Context c) { mContext = c; }
- public int getCount() { return mImageIds.length; }
- public Object getItem(int position) { return position; }
- public long getItemId(int position) { return position; }
- public View getView(int position, View convertView, ViewGroup parent) {
- ImageView imageView = new ImageView(mContext);
- imageView.setImageResource(mImageIds[position]);
- imageView.setLayoutParams(new Gallery.LayoutParams(150, 100));
- imageView.setScaleType(ImageView.ScaleType.FIT_XY);
- return imageView;
- }
- }
如果要给Gallery设置风格的话,需要在res/values文件夹下面创建一个attrs.xml,示例代码如下:
- <?xml version="1.0" encoding="utf-8"?>
- <resources>
- <declare-styleable name="MyGallery">
- <attr name="android:galleryItemBackground" />
- </declare-styleable>
- </resources>
然后在自定义的适配器里面,在构造方法里面,添加如下的代码:
- TypedArray attr = mContext.obtainStyledAttributes(R.styleable.MyGallery);
- mGalleryItemBackground = attr.getResourceId(
- R.styleable.MyGallery_android_galleryItemBackground, 0);
有了风格过后,在创建ImageView的时候,就可以使用这个风格了,在getView方法里面添加如下代码:
- imageView.setBackgroundResource(mGalleryItemBackground);
AutoComplete
然后在程序里面,为它设置值,示例代码如下:
- AutoCompleteTextView textView = (AutoCompleteTextView) findViewById(R.id.autocomplete);
- ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.autoc_item, new String[]{"abc","abd","abcd","bcd","bef"});
- textView.setAdapter(adapter);
- <TextView xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- android:padding="10dp"
- android:textSize="16sp"
- android:textColor="#ff0000">
- </TextView>
首先在布局文件设置使用MultiAutoCompleteTextView,示例代码如下:
- <MultiAutoCompleteTextView android:id="@+id/autocomplete"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- />
然后在程序中,为他设置值,示例代码如下:
- MultiAutoCompleteTextView textView = (MultiAutoCompleteTextView) findViewById(R.id.autocomplete);
- ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.autoc_item, new String[]{"abc","abd","abcd","bcd","bef"});
- textView.setAdapter(adapter);
- textView.setTokenizer(new MultiAutoCompleteTextView.CommaTokenizer());
LinearLayout
- <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:orientation="horizontal"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- android:layout_weight="1">
- <TextView
- android:text="red"
- android:gravity="center_horizontal"
- android:background="#ff0000"
- android:layout_width="wrap_content"
- android:layout_height="fill_parent"
- android:layout_weight="1"/>
- <TextView
- android:text="green"
- android:gravity="center_horizontal"
- android:background="#00ff00"
- android:layout_width="wrap_content"
- android:layout_height="fill_parent"
- android:layout_weight="1"/>
- <TextView
- android:text="blue"
- android:gravity="center_horizontal"
- android:background="#0000ff"
- android:layout_width="wrap_content"
- android:layout_height="fill_parent"
- android:layout_weight="1"/>
- <TextView
- android:text="yellow"
- android:gravity="center_horizontal"
- android:background="#aaaa00"
- android:layout_width="wrap_content"
- android:layout_height="fill_parent"
- android:layout_weight="1"/>
- </LinearLayout>
- <LinearLayout
- android:orientation="vertical"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- android:layout_weight="1">
- <TextView
- android:text="第一行"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:layout_weight="1"/>
- <TextView
- android:text="第二行"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:layout_weight="1"/>
- <TextView
- android:text="第三行"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:layout_weight="1"/>
- </LinearLayout>
- </LinearLayout>
RelativeLayout
- <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent">
- <TextView
- android:id="@+id/label"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:text="请输入:"/>
- <EditText
- android:id="@+id/entry"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:background="@android:drawable/editbox_background"
- android:layout_below="@id/label"/>
- <Button
- android:id="@+id/ok"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_below="@id/entry"
- android:layout_alignParentRight="true"
- android:layout_marginLeft="10dip"
- android:text="确定" />
- <Button
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_toLeftOf="@id/ok"
- android:layout_alignTop="@id/ok"
- android:text="取消" />
- </RelativeLayout>
TableLayout
- <TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- android:stretchColumns="1">
- <TableRow>
- <TextView android:layout_column="1" android:text="张三" android:padding="3dip" />
- <TextView
- android:text="25岁" android:gravity="right" android:padding="3dip" />
- </TableRow>
- <TableRow>
- <TextView android:layout_column="1" android:text="李四" android:padding="3dip" />
- <TextView
- android:text="22岁"
- android:gravity="right"
- android:padding="3dip" />
- </TableRow>
- <View android:layout_height="2dip" android:background="#FF909090" />
- <TableRow>
- <TextView
- android:text="王五"
- android:padding="3dip" />
- <TextView
- android:text="本科毕业"
- android:padding="3dip" />
- <TextView
- android:text="23岁"
- android:gravity="right"
- android:padding="3dip" />
- </TableRow>
- </TableLayout>
TableLayout的常用属性如下:
GridView
首先在布局文件里面配置使用GridView,示例代码如下:
- <GridView xmlns:android="http://schemas.android.com/apk/res/android"
- android:id="@+id/gridview"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- android:columnWidth="50dp"
- android:numColumns="5"
- android:verticalSpacing="10dp"
- android:horizontalSpacing="2dp"
- android:stretchMode="columnWidth"
- android:gravity="center"
- />
然后在程序里面,为它设置值,示例代码如下:
- GridView gridview = (GridView) findViewById(R.id.gridview);
- gridview.setAdapter(new ImageAdapter(this));
然后在程序里面,为它设置值,需要使用一个自定义的Adapter,示例代码如下:
- class ImageAdapter extends BaseAdapter {
- private Context mContext;
- public ImageAdapter(Context c) { mContext = c; }
- public int getCount() {return mThumbIds.length; }
- public Object getItem(int position) { return null;}
- public long getItemId(int position) { return 0; }
- public View getView(int position, View convertView, ViewGroup parent) {
- ImageView imageView;
- if (convertView == null) {
- imageView = new ImageView(mContext);
- imageView.setLayoutParams(new GridView.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
- imageView.setScaleType(ImageView.ScaleType.FIT_XY);
- imageView.setPadding(0, 0,0,0);
- imageView.setBackgroundColor(Color.RED);
- } else {
- imageView = (ImageView) convertView;
- }
- imageView.setImageResource(mThumbIds[position]);
- return imageView;
- }
- private Integer[] mThumbIds = {
- R.drawable.icon, R.drawable.icon,
- R.drawable.icon, R.drawable.icon,
- R.drawable.icon, R.drawable.icon,
- R.drawable.icon, R.drawable.icon
- };
- }
事件处理是实现OnItemClickListener,示例代码如下:
- gridview.setOnItemClickListener(new OnItemClickListener() {
- public void onItemClick(AdapterView<?> parent, View v,
- int position, long id) {
- Toast.makeText(TestWidgets.this, "" + position,
- Toast.LENGTH_SHORT).show();
- }
- });
TabLayout
要实现基本的TabLayout,首先需要在布局文件里面定义,示例代码如下:
- <TabHost xmlns:android="http://schemas.android.com/apk/res/android"
- android:id="@android:id/tabhost"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent">
- <LinearLayout
- android:orientation="vertical"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- android:padding="5dp">
- <TabWidget
- android:id="@android:id/tabs"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content" />
- <FrameLayout
- android:id="@android:id/tabcontent"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- android:padding="5dp" />
- </LinearLayout>
- </TabHost>nTabHost就是用来存放多个Tab的容器
TabWidget就是实现Tab的Widget
有了布局过后,就可以直接在程序里面设置Tab了,示例如下:
2:得到TabHost,示例代码如下:
- TabHost tabHost = getTabHost();
3:创建一个Intent对象,做为点击tab后的事件响应,示例代码如下:
- Intent intent = new Intent().setClass(this, MyActivity.class);
- intent.putExtra("showStr", "第一个tab");
- Intent设置的Class就是点击tab,内容页显示出来的Activity。
5:然后把这个TabSpec添加到TabHost中即可,示例代码如下:
- tabHost.addTab(spec);
如果想要给Tab设置图片,方法步骤如下:
- <?xml version="1.0" encoding="utf-8"?>
- <selector xmlns:android="http://schemas.android.com/apk/res/android">
- <item android:drawable="@drawable/icon2"
- android:state_selected="true" />
- <item android:drawable="@drawable/icon" />
- </selector>
- Resources res = getResources();
- spec = tabHost.newTabSpec("FirstTag").setIndicator(
- "第一个Tab",res.getDrawable(R.drawable.my_tab1_selector))
- .setContent(intent);
ListView
对于最基本的ListView,直接在代码里面写,示例如下:
- public class TestList extends ListActivity {
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- // this.setContentView(R.layout.TestList);
- setListAdapter(new ArrayAdapter<String>(this,
- android.R.layout.simple_list_item_1, new String[]{"111","222","333"}));
- }
- protected void onListItemClick(ListView l,View v,int position,long id){
- super.onListItemClick(l, v, position, id);
- String s = ""+l.getItemAtPosition(position);
- System.out.println("now click="+s);
- }
- }
List的单选模式,示例代码如下:
- setListAdapter(new ArrayAdapter<String>(this,
- android.R.layout. simple_list_item_single_choice, new String[]{"111","222","333}));
- this.getListView().setItemsCanFocus(false);
- this.getListView().setChoiceMode(ListView. CHOICE_MODE_SINGLE);
List的多选模式,示例代码如下:
- setListAdapter(new ArrayAdapter<String>(this,
- android.R.layout.simple_list_item_multiple_choice, new String[]{"111","222","333}));
- this.getListView().setItemsCanFocus(false);
- this.getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
在ListView里面设置多个值的方法
在ListView的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 xmlns:android="http://schemas.android.com/apk/res/android"
- android:orientation="vertical"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- >
- <ListView
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- android:padding="10dp"
- android:textSize="16sp"
- android:id="@id/android:list"
- >
- </ListView>
- </LinearLayout>
- </LinearLayout>
在ListView的Item的布局文件中
- <?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"
- >
- <RelativeLayout
- android:layout_width="fill_parent"
- android:layout_height="fill_parent">
- <TextView
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:id="@+id/userId"
- >
- </TextView>
- <TextView
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:id="@+id/userName"
- android:layout_marginLeft="20dip"
- android:layout_toRightOf="@id/userId"
- >
- </TextView>
- <TextView
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:id="@+id/userAge"
- android:layout_marginLeft="20dip"
- android:layout_toRightOf="@id/userName"
- >
- </TextView>
- </RelativeLayout>
- </LinearLayout>
在java程序中
- List list = new ArrayList();
- Map map1 = new HashMap();
- map1.put("userId","11");
- map1.put("userName","11N");
- map1.put("age","11");
- list.add(map1);
- Map map2 = new HashMap();
- map2.put("userId","22");
- map2.put("userName","22N");
- map2.put("age","22");
- list.add(map2);
- setListAdapter(new SimpleAdapter(this, list,R.layout.list,new String[]{"userId","userName","age"}, new int[]{R.id.userId,R.id.userName,R.id.userAge}));
- protected void onListItemClick(ListView l, View v, int position, long id) {
- super.onListItemClick(l, v, position, id);
- System.out.println("sssssssss===="+l.getItemAtPosition(position));
菜单
在Android系统中,菜单分成三种
创建菜单资源
- <menu xmlns:android="http://schemas.android.com/apk/res/android">
- <item android:id="@+id/to_add"
- android:icon="@drawable/icon"
- android:title="转向新增" />
- <item android:id="@+id/to_update"
- android:icon="@drawable/icon"
- android:title="转向修改" />
- </menu>
- public boolean onCreateOptionsMenu(Menu menu) {
- MenuInflater inflater = getMenuInflater();
- inflater.inflate(R.menu.test_menu, menu);
- return true;
- }
响应菜单,在程序里面,需要写代码来实现菜单被点击后要实现的功能
- public boolean onOptionsItemSelected(MenuItem item) {
- switch (item.getItemId()) {
- case R.id.to_add:
- Log.i("javass","now to add"); break;
- case R.id.to_update:
- Log.i("javass","now to update"); break;
- default: return super.onOptionsItemSelected(item);
- }
- return true;
- }
- public void myToAdd(MenuItem item) {
- Log.i("javass","now in myToAdd");
- }
上下文菜单
上下文菜单就相当于PC上的右击,创建上下文菜单:
- this.registerForContextMenu(btnRun);
- public void onCreateContextMenu(ContextMenu menu,View v,ContextMenuInfo info) {
- super.onCreateContextMenu(menu, v, info);
- MenuInflater inflater = getMenuInflater();
- inflater.inflate(R.menu.test_menu, menu);
- }
- public boolean onContextItemSelected(MenuItem item) {
- AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
- switch (item.getItemId()) {
- case R.id. new_file:
- Log.i("onContextItemSelected", "now ruuuuuuuuuuu");
- return true;
- default: return super.onContextItemSelected(item);
- }
- }
子菜单
创建子菜单非常简单,只需要在菜单资源文件中配置即可,示例如下:
- <item android:id="@+id/new_file"
- android:icon="@drawable/ic_launcher"
- android:title="@string/new_file"
- >
- <menu>
- <item android:id="@+id/create_new"
- android:title="now new" />
- <item android:id="@+id/open"
- android:title="now open" />
- </menu>
- </item>
给菜单分组
给菜单分组非常简单,只需要在菜单资源文件中配置即可,示例如下:
- <group android:id="@+id/group1">
- <item android:id="@+id/create_new"
- android:icon="@drawable/ic_launcher"
- android:title="now new" />
- <item android:id="@+id/open"
- android:icon="@drawable/ic_launcher"
- android:title="now open" />
- </group>
分组后能干什么
可选菜单
可选菜单非常简单,只需要在菜单资源文件中配置即可,示例如下:
可选菜单一般针对上下文菜单和子菜单
1:对于Options的子菜单,可以在onPrepareOptionsMenu方法里面设置状态,示例代码如下:
- public boolean onPrepareOptionsMenu(Menu menu) {
- super.onPrepareOptionsMenu(menu);
- MenuItem mi = menu.findItem(R.id.create_new);
- mi.setChecked(flag);
- return true;
- }
动态修改菜单项
有些时候,需要动态的修改菜单项,该怎么实现呢?
对于Options的菜单及其子菜单
onPrepareOptionsMenu方法和onCreateOptionsMenu方法
编程式实现菜单
前面是声明式实现菜单,也可以采用编程式的方式来实现菜单,常用API为:
关于Menu的图标
Action Bar基本概念
是什么
特点
使用Action Bar
删除Action Bar
- <activity android:theme="@android:style/Theme.Holo.NoActionBar">
- ActionBar actionBar = getActionBar();
- actionBar.hide();
添加Action View
- <menu xmlns:android="http://schemas.android.com/apk/res/android">
- <item android:id="@+id/menu_search"
- android:title="Search"
- android:icon="@drawable/ic_menu_search"
- android:showAsAction="ifRoom"
- android:actionLayout="@layout/searchview" />
- </menu>
- 或者把android:actionLayout=“@layout/searchview” 换成:
- android:actionViewClass="android.widget.SearchView"
1:简单的修改,可以通过:
- ActionBar actionBar = getActionBar();
- actionBar.setDisplayUseLogoEnabled(true);
- actionBar.setLogo(R.drawable.app_sample_code);
- actionBar.setBackgroundDrawable(this.getResources().getDrawable(R.drawable.app_sample_code));
- <activity android:name=".ExampleActivity"
- android:theme="@android:style/Theme.Holo.Light" />
Dialogs
什么是Dialog
常见的Dialog
创建和显示Dialog
关闭Dialog
Dismiss listener
实现Dialog风格的Activity
Alert Dialog
创建带Button的Alert Dialog
- AlertDialog.Builder builder = new AlertDialog.Builder(this);
- builder.setMessage("确定要删除吗?")
- .setCancelable(false)
- .setPositiveButton("取消",
- new DialogInterface.OnClickListener() {
- public void onClick(DialogInterface dialog,int id) {
- Toast.makeText(HelloWorldActivity.this, “dialog取消", Toast.LENGTH_LONG).show();
- }
- })
- .setNegativeButton("确定",
- new DialogInterface.OnClickListener() {
- public void onClick(DialogInterface dialog,int id) { Toast.makeText(HelloWorldActivity.this,“dialog确定", Toast.LENGTH_LONG).show();
- }
- });
- AlertDialog alert = builder.create();
- final CharSequence[] items = { "红色", "绿色", "蓝色" };
- AlertDialog.Builder builder = new AlertDialog.Builder(this);
- builder.setTitle("请选择颜色");
- builder.setItems(items, new DialogInterface.OnClickListener() {
- public void onClick(DialogInterface dialog, int item) {
- Toast.makeText(getApplicationContext(), items[item],
- Toast.LENGTH_SHORT).show();
- }
- });
- AlertDialog alert = builder.create();
- final CharSequence[] items = { "红色", "绿色", "蓝色" };
- AlertDialog.Builder builder = new AlertDialog.Builder(this);
- builder.setTitle("请选择颜色");
- builder.setSingleChoiceItems(items, -1,new DialogInterface.OnClickListener() {
- public void onClick(DialogInterface dialog, int item) {
- Toast.makeText(getApplicationContext(), items[item],
- Toast.LENGTH_SHORT).show();
- dialog.dismiss();
- }
- });
- AlertDialog alert = builder.create();
- inal CharSequence[] items = { "红色", "绿色", "蓝色" };
- AlertDialog.Builder builder = new AlertDialog.Builder(this);
- builder.setTitle("请选择颜色");
- builder.setMultiChoiceItems(items, new boolean[]{false,false,false},new DialogInterface.OnMultiChoiceClickListener() {
- public void onClick(DialogInterface dialog, int which, boolean isChecked) {
- Toast.makeText(getApplicationContext(), items[which], Toast.LENGTH_SHORT).show();
- }
- });
- builder.setNegativeButton("确定",
- new DialogInterface.OnClickListener() {
- public void onClick(DialogInterface dialog, int id) {
- Toast.makeText(HelloWorldActivity.this, "dialog确定", Toast.LENGTH_LONG).show();
- dialog.dismiss();
- }
- }
- );
- AlertDialog alert = builder.create();
Progress Dialog
Progress Dialog扩展自Alert Dialog
- HandlerThread ht = new HandlerThread("MyThread");
- Handler h = null;
- if(!ht.isAlive()){
- ht.start();
- h = new Handler(ht.getLooper()){
- public void handleMessage(Message msg) {
- try {
- Thread.sleep(5000L);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- HelloWorldActivity.this.dismissDialog(1);
- super.handleMessage(msg);
- }
- };
- }
- Message msg = h.obtainMessage();
- msg.sendToTarget();
使用Progress Bar,同样需要配合Handler来执行,示例如下:
1:创建Progress Bar,在onCreateDialog方法里面,示例如下:
- dialog = new ProgressDialog(HelloWorldActivity.this);
- dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
- dialog.setMessage("装载中...");
- dialog.setCancelable(false);
- dialog.setMax(10);
2:定义Handler和Runnable
- Handler h = new Handler() {
- public void handleMessage(Message msg) {
- super.handleMessage(msg);
- if(msg.arg1 < dialog.getMax()){dialog.setProgress(msg.arg1);}
- else{dialog.dismiss();}}};
- int num = 0;
- Runnable r = new Runnable() {
- public void run() {
- Message msg = h.obtainMessage();
- msg.arg1 = num++;
- h.sendMessage(msg);
- h.postDelayed(r, 1000L);
- }};
也可以通过配置文件来使用Progress Bar,同样需要配合Handler来执行,示例如下:
1:在layout的配置文件里面创建Progress Bar,示例如下:
- <ProgressBar
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:id="@+id/progress_bar"
- style="?android:attr/progressBarStyleHorizontal"
- android:visibility="gone"
- />
2:在程序中启动Progress Bar,示例如下:
- pb = (ProgressBar)HelloWorldActivity.this.findViewById(R.id.progress_bar);
- pb.setMax(10);
- pb.setVisibility(View.VISIBLE);
- h.post(r);
Customer Dialog
如果想要使用自己订制的Dialog,那么首先需要定义自己的布局,示例如下:
- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:id="@+id/layout_root"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- android:orientation="horizontal"
- android:padding="10dp" >
- <ImageView
- android:id="@+id/image"
- android:layout_width="wrap_content"
- android:layout_height="fill_parent"
- android:layout_marginRight="10dp" />
- <TextView
- android:id="@+id/text"
- android:layout_width="wrap_content"
- android:layout_height="fill_parent"
- />
- </LinearLayout>
在程序中获取这些对象,然后设置相应的属性,再显示出来,示例如下:
- Context mContext = HelloWorldActivity.this;
- Dialog dialog = new Dialog(mContext);
- dialog.setContentView(R.layout.my_dialog);
- dialog.setTitle("自己订制的Dialog");
- TextView text = (TextView) dialog.findViewById(R.id.text);
- text.setText("欢迎使用本系统");
- ImageView image = (ImageView) dialog.findViewById(R.id.image);
- image.setImageResource(R.drawable.ic_launcher);
- //最后显示出来
- dialog.show();
Handler
Handler概述
Handler使用
Handler
- Handler h = new Handler() {
- public void handleMessage(Message msg) {
- super.handleMessage(msg);
- //使用what来区分是什么样的消息
- switch (msg.what){
- case 1 :
- //这里进行消息的处理
- break;
- default :
- //这里进行消息的处理
- }
- }};
- int what = 0;
- Runnable r = new Runnable() {
- public void run() {
- Message msg = h.obtainMessage();
- msg.obj = "1234567";//传递的参数
- msg.what = what;
- what++;
- h.sendMessage(msg);
- h.postDelayed(r, 1000L);
- }};
如果想要启动新的线程来处理,使用HandlerThread的示例如下:
- HandlerThread ht = new HandlerThread("MyThread");
- Handler h = null;
- ht.start();
- h = new Handler(ht.getLooper()){
- public void handleMessage(Message msg) {
- super.handleMessage(msg);
- //这里真正处理消息
- Toast.makeText(getApplicationContext(),"msg="+msg.obj,Toast.LENGTH_LONG).show();
- }
- };
- Message msg = h.obtainMessage();
- msg.obj="test message";
- msg.sendToTarget();
Notifications
Android系统中,有如下通知类型:
指定Toast的位置,使用Gravity属性,示例如下:
- Toast t = Toast.makeText(HelloWorldActivity.this,"okok", Toast.LENGTH_SHORT);
- t.setGravity(Gravity.TOP|Gravity.LEFT, 5,10);
- t.show();
订制Toast,需订制布局文件,这里使用上一个示例的布局文件来示例,程序写法如下:
- LayoutInflater inflater = getLayoutInflater();
- View layout = inflater.inflate(R.layout.my_dialog,
- (ViewGroup) findViewById(R.id.layout_root));
- ImageView image = (ImageView) layout.findViewById(R.id.image);
- image.setImageResource(R.drawable.ic_launcher);
- TextView text = (TextView) layout.findViewById(R.id.text);
- text.setText("欢迎您的到来!");
- Toast t = new Toast(HelloWorldActivity.this);
- t.setView(layout);
- t.setGravity(Gravity.CENTER|Gravity.LEFT, 5,10);
- t.show();
Status Bar Notification :可以由Activity或Service发出。示例如下:
- //获取NotificationManager
- String ns = Context.NOTIFICATION_SERVICE;
- NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);
- //设置在status bar上显示的信息条
- int icon = R.drawable.app_sample_code;
- CharSequence tickerText = "请注意";
- long when = System.currentTimeMillis();
- Notification notification = new Notification(icon, tickerText, when);
- //设置在status 列表里面显示的信息,以及点击的事件
- CharSequence contentTitle = "重要通知";
- CharSequence contentText = "测试";
- Intent notificationIntent = new Intent(HelloWorldActivity.this, T2.class);
- PendingIntent contentIntent = PendingIntent.getActivity(HelloWorldActivity.this, 0, notificationIntent, 0);
- notification.setLatestEventInfo(HelloWorldActivity.this, contentTitle, contentText, contentIntent);
- //发出通知
- mNotificationManager.notify(1, notification);
为Notification添加其他特性
客户化的Notification,只是客户化在通知信息列表里面的展示,其他的跟前面仍然是一样的,示例如下:
转载于:https://www.cnblogs.com/helloandroid1/archive/2012/08/03/2622020.html
Android4开发入门经典 之 第四部分:用户界面相关推荐
- Android4开发入门经典 之 第十二部分:最佳实践
性能提升 有两个编写有效代码的基本规则: 1:不要做你不需要做的. 2:不分配没必要分配的内存. 应该尽量避免创建多余的对象,比如: 1:在一组输入数据中抽取字符串时,尝试返回源数据的子串,而非创建一 ...
- Android4开发入门经典 之 第十二部分:最佳实践【私塾在线原创】
性能提升 有两个编写有效代码的基本规则: 1:不要做你不需要做的. 2:不分配没必要分配的内存. 应该尽量避免创建多余的对象,比如: 1:在一组输入数据中抽取字符串时,尝试返回源数据的子串,而非创建一 ...
- Android4开发入门经典 之 第七部分:数据存储
数据存储基本知识 Android系统提供了多种数据存储的方式,如下: 1:Shared Preferences:用来存储私有的.原始类型的.简单的数据,通常是Key-value对 2:Internal ...
- 《iOS 8应用开发入门经典(第6版)》——第1章,第1.6节小结
本节书摘来自异步社区<iOS 8应用开发入门经典(第6版)>一书中的第1章,第1.6节小结,作者 [美]John Ray(约翰 雷),更多章节内容可以访问云栖社区"异步社区&qu ...
- 《Android应用开发入门经典(第3版)》——第6.1节创建演示应用
本节书摘来自异步社区<Android应用开发入门经典(第3版)>一书中的第6章,第6.1节创建演示应用,作者 [美]Carmen Delessio , Lauren Darcey , Sh ...
- 《iOS 9应用开发入门经典(第7版)》——第2章,第2.4节小结
本节书摘来自异步社区<iOS 9应用开发入门经典(第7版)>一书中的第2章,第2.4节小结,作者 [美]约翰 雷(John Ray),更多章节内容可以访问云栖社区"异步社区&qu ...
- 谷歌眼镜开发入门经典
2019独角兽企业重金招聘Python工程师标准>>> 谷歌眼镜开发入门经典 Google Glass将是目前以及未来几年风靡全球的革命性的移动计算平台,<谷歌眼镜开发入门经典 ...
- 《Android应用开发入门经典(第3版)》——导读
本节书摘来自异步社区<Android应用开发入门经典(第3版)>一书中的目录,作者 [美]Carmen Delessio , Lauren Darcey , Shane Conder,更多 ...
- HTML5移动应用开发入门经典 中文pdf扫描版
HTML5是关注度ZUI高的前沿Web技术,而移动互联网则是近两年ZUI炙手可热的Web领域.<HTML5移动应用开发入门经典>将这两者巧妙结合起来,详细讲解了如何利用HTML5进行移动应 ...
最新文章
- haproxy配置文件详解--转
- 如何判断Javascript对象是否存在
- 数据中心发电机组的选择及控制
- [机器学习]超参数优化算法-SuccessiveHalving与Hyperband
- bcp+Sql语句抽取数据导出
- php有哪些_php工作原理是什么?php常用功能有哪些?
- [Swift]LeetCode599. 两个列表的最小索引总和 | Minimum Index Sum of Two Lists
- BerkeleyDB-JE数据库操作封装
- hive表名命名规范_数据仓库开发规范
- python是什么 自学-Python怎样自学?
- Tech.Ed 2011微软技术大会(二)之专题讲座
- 基于Flash CS6和AS3.0编写的打企鹅游戏(类打地鼠)
- Java基础知识之笔记总结分享(超详细)入门必备
- 浅谈博客、微博与轻博客的区别与联系
- HTML jquery笔试题,2019Web前端面试题及答案汇总-Jquery篇
- TI am335x系列(am3352)LCD驱动修改移植
- An Underwater Image Enhancement Benchmark Dataset and Beyong
- 3966: 购物(sum)
- mongodb类型转换
- zynq嵌入式linux显示logo,如何定制嵌入式linux 启动logo(小企鹅)
热门文章
- mysql 运算符转义_我的MYSQL学习心得(五) 运算符
- 图像局部特征(十六)--SimpleBlobDetector
- 如何读出烧录程序.bin的数据_如何改变程序搜索数据的方式?使用Redis进行搜索...
- “21天好习惯”第一期-16
- C语言:从键盘中输入字符串,追加填写到指定文件中
- scala Iterator类型入门初探
- supervisor入门应用
- 俄罗斯方块的那些事:1.概要
- Web Components 小榄
- 大数据时代的回收生意经(淼一专访)