Android开发-菜单与对话框

 
Android开发06—菜单与对话框(下)

1. 进度对话框
ProgressDialog可以显示进度轮和进度条,由于ProgressDialog继承自AlertDialog,所以在进度对话框中也可以添加按钮。
实例说明进度对话框的用法:
Java代码 复制代码
  1. package qijia.si;   
  2.   
  3. import android.app.Activity;   
  4. import android.app.Dialog;   
  5. import android.app.ProgressDialog;   
  6. import android.os.Bundle;   
  7. import android.os.Handler;   
  8. import android.os.Message;   
  9. import android.view.View;   
  10. import android.view.View.OnClickListener;   
  11. import android.widget.Button;   
  12.   
  13. public class ContextMenuDemo extends Activity {   
  14.     //声明进度对话框id   
  15.     final int PROGRESS_DIALOG = 0;   
  16.     //Handler消息类型   
  17.     final int INCREASE = 0;   
  18.     //进度对话框对象引用   
  19.     ProgressDialog pd;   
  20.     //Handler对象引用   
  21.     Handler myHandler;   
  22.        
  23.     /** Called when the activity is first created. */  
  24.     @Override  
  25.     public void onCreate(Bundle savedInstanceState) {   
  26.         super.onCreate(savedInstanceState);   
  27.         setContentView(R.layout.main);   
  28.         //获得Button对象   
  29.         Button bt = (Button)this.findViewById(R.id.button1);   
  30.         //设置onClickListener监听器   
  31.         bt.setOnClickListener(new OnClickListener(){   
  32.   
  33.             public void onClick(View v) {   
  34.                 // TODO Auto-generated method stub   
  35.                 showDialog(PROGRESS_DIALOG);   
  36.             }   
  37.                
  38.         });   
  39.         //创建handler对象   
  40.         myHandler = new Handler(){   
  41.   
  42.             @Override  
  43.             public void handleMessage(Message msg) {   
  44.                 // TODO Auto-generated method stub   
  45.                 switch(msg.what){   
  46.                 case INCREASE:   
  47.                     pd.incrementProgressBy(1);   
  48.                     //如果进度走完就关闭   
  49.                     if(pd.getProgress()>=100){   
  50.                         pd.dismiss();   
  51.                     }   
  52.                     break;   
  53.                 }   
  54.                 super.handleMessage(msg);   
  55.             }   
  56.                
  57.         };   
  58.     }     
  59.     //重写onCreateDialog方法   
  60.     public Dialog onCreateDialog(int id){   
  61.         switch(id){   
  62.         //创建进度对话框   
  63.         case PROGRESS_DIALOG:   
  64.             pd = new ProgressDialog(this);   
  65.             //设置进度对话框   
  66.             pd.setMax(100);   
  67.             pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);   
  68.             pd.setTitle(R.string.title);   
  69.             pd.setCancelable(false);   
  70.             new Thread(){   
  71.             public void run(){   
  72.                 while(true){   
  73.                     //发送Handler消息   
  74.                     myHandler.sendEmptyMessage(INCREASE);   
  75.                     if(pd.getProgress()>=100){   
  76.                         break;   
  77.                     }   
  78.                     try{   
  79.                         Thread.sleep(100);   
  80.                     }catch(Exception e){   
  81.                         e.printStackTrace();   
  82.                     }   
  83.                 }   
  84.             }   
  85.         }.start();   
  86.             break;   
  87.         }   
  88.         return pd;   
  89.            
  90.     }   
  91.     //每次弹出对话框时被动态回调以动态更新对话框   
  92.     public void onPrePareDialog(int id,Dialog dialog){   
  93.         super.onPrepareDialog(id, dialog);   
  94.         switch(id){   
  95.         case PROGRESS_DIALOG:   
  96.             //对话框进度清零   
  97.             pd.incrementProgressBy(-pd.getProgress());   
  98.             //匿名对象   
  99.             new Thread()   
  100.             {   
  101.                 public void run(){   
  102.                     while(true){   
  103.                         //发送Handler消息   
  104.                         myHandler.sendEmptyMessage(INCREASE);   
  105.                         if(pd.getProgress()>=100){   
  106.                             break;   
  107.                         }   
  108.                         try{   
  109.                             Thread.sleep(100);   
  110.                         }catch(Exception e){   
  111.                             e.printStackTrace();   
  112.                         }   
  113.                     }   
  114.                 }   
  115.             }.start();   
  116.             break;   
  117.             }   
  118.     }   
  119.        
  120. }  
package qijia.si;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class ContextMenuDemo extends Activity {
	//声明进度对话框id
	final int PROGRESS_DIALOG = 0;
	//Handler消息类型
	final int INCREASE = 0;
	//进度对话框对象引用
	ProgressDialog pd;
	//Handler对象引用
	Handler myHandler;
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        //获得Button对象
        Button bt = (Button)this.findViewById(R.id.button1);
        //设置onClickListener监听器
        bt.setOnClickListener(new OnClickListener(){

			public void onClick(View v) {
				// TODO Auto-generated method stub
				showDialog(PROGRESS_DIALOG);
			}
        	
        });
        //创建handler对象
        myHandler = new Handler(){

			@Override
			public void handleMessage(Message msg) {
				// TODO Auto-generated method stub
				switch(msg.what){
				case INCREASE:
					pd.incrementProgressBy(1);
					//如果进度走完就关闭
					if(pd.getProgress()>=100){
						pd.dismiss();
					}
					break;
				}
				super.handleMessage(msg);
			}
        	
        };
    }  
    //重写onCreateDialog方法
    public Dialog onCreateDialog(int id){
    	switch(id){
    	//创建进度对话框
    	case PROGRESS_DIALOG:
    		pd = new ProgressDialog(this);
    		//设置进度对话框
    		pd.setMax(100);
    		pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
    		pd.setTitle(R.string.title);
    		pd.setCancelable(false);
    		new Thread(){
    		public void run(){
				while(true){
					//发送Handler消息
					myHandler.sendEmptyMessage(INCREASE);
					if(pd.getProgress()>=100){
						break;
					}
					try{
						Thread.sleep(100);
					}catch(Exception e){
						e.printStackTrace();
					}
				}
			}
		}.start();
    		break;
    	}
		return pd;
    	
    }
    //每次弹出对话框时被动态回调以动态更新对话框
    public void onPrePareDialog(int id,Dialog dialog){
    	super.onPrepareDialog(id, dialog);
    	switch(id){
    	case PROGRESS_DIALOG:
    		//对话框进度清零
    		pd.incrementProgressBy(-pd.getProgress());
    		//匿名对象
    		new Thread()
    		{
    			public void run(){
    				while(true){
    					//发送Handler消息
    					myHandler.sendEmptyMessage(INCREASE);
    					if(pd.getProgress()>=100){
    						break;
    					}
    					try{
    						Thread.sleep(100);
    					}catch(Exception e){
    						e.printStackTrace();
    					}
    				}
    			}
    		}.start();
    		break;
    		}
    }
    
}

2. 消息提示
1) Toast的使用
Toast向用户提供比较快速的即时消息,当Toast被显示时,虽然其悬浮于应用程序的最上方,但是Toast从不获得焦点。因为涉及Toast时就是为了让其在提示有用信息时尽量不显眼。Toast用于用户某项设置成功等。
Toast对象的创建通过Toast类的静态方法makeText来实现,该方法有两个重载实现,主要的不同时一个接受字符串,而另一个接收字符串的资源标识符作为参数。Toast对象创建好之后通过show方法即可将消息提示显示到屏幕上。

实例:
Java代码 复制代码
  1. package qijia.si;   
  2.   
  3. import android.app.Activity;   
  4. import android.os.Bundle;   
  5. import android.view.Gravity;   
  6. import android.view.View;   
  7. import android.view.View.OnClickListener;   
  8. import android.widget.Button;   
  9. import android.widget.ImageView;   
  10. import android.widget.LinearLayout;   
  11. import android.widget.Toast;   
  12.   
  13. public class ContextMenuDemo extends Activity {   
  14.   
  15.        
  16.     /** Called when the activity is first created. */  
  17.     @Override  
  18.     public void onCreate(Bundle savedInstanceState) {   
  19.         super.onCreate(savedInstanceState);   
  20.         setContentView(R.layout.main);   
  21.         Button btn = (Button) this.findViewById(R.id.button1);   
  22.         btn.setOnClickListener(new OnClickListener(){   
  23.   
  24.             public void onClick(View v) {   
  25.                 // TODO Auto-generated method stub   
  26.                 //创建ImageView   
  27.                 ImageView iv = new ImageView(ContextMenuDemo.this);   
  28.                 iv.setImageResource(R.drawable.header);   
  29.                 //创建一个线性布局   
  30.                 LinearLayout ll = new LinearLayout(ContextMenuDemo.this);   
  31.                    
  32.                 Toast toast = Toast.makeText(ContextMenuDemo.this"Hello World", Toast.LENGTH_LONG);   
  33.                 toast.setGravity(Gravity.CENTER, 00);   
  34.                 View toastView = toast.getView();   
  35.                 ll.setOrientation(LinearLayout.HORIZONTAL);   
  36.                 //将ImageView添加到线性布局   
  37.                 ll.addView(iv);   
  38.                 //将Toast的View添加到线性布局   
  39.                 ll.addView(toastView);   
  40.                 toast.setView(ll);   
  41.                 //显示toast   
  42.                 toast.show();   
  43.             }   
  44.                
  45.         });   
  46.     }   
  47.        
  48. }  
package qijia.si;

import android.app.Activity;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

public class ContextMenuDemo extends Activity {

	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Button btn = (Button) this.findViewById(R.id.button1);
        btn.setOnClickListener(new OnClickListener(){

			public void onClick(View v) {
				// TODO Auto-generated method stub
				//创建ImageView
				ImageView iv = new ImageView(ContextMenuDemo.this);
				iv.setImageResource(R.drawable.header);
				//创建一个线性布局
				LinearLayout ll = new LinearLayout(ContextMenuDemo.this);
				
				Toast toast = Toast.makeText(ContextMenuDemo.this, "Hello World", Toast.LENGTH_LONG);
				toast.setGravity(Gravity.CENTER, 0, 0);
				View toastView = toast.getView();
				ll.setOrientation(LinearLayout.HORIZONTAL);
				//将ImageView添加到线性布局
				ll.addView(iv);
				//将Toast的View添加到线性布局
				ll.addView(toastView);
				toast.setView(ll);
				//显示toast
				toast.show();
			}
        	
        });
    }
    
}
2) Notification
Notification是另一种消息提示的方式。Notification位于手机的状态栏,在Android手机中用手指按下状态栏并往下拉可以打开状态栏查看系统的提示信息。

实例:

main.xml:
Xml代码 复制代码
  1. <?xml version="1.0" encoding="utf-8"?>  
  2.     <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_height="fill_parent" android:id="@+id/linearLayout1" android:layout_width="fill_parent" android:orientation="vertical">  
  3.         <Button android:layout_height="wrap_content" android:id="@+id/button1" android:text="@string/btn" android:layout_width="fill_parent"></Button>  
  4.     </LinearLayout>  
   
  
  

notified.xml

Xml代码 复制代码
  1. <?xml version="1.0" encoding="utf-8"?>  
  2.     <LinearLayout android:id="@+id/linearLayout1" android:layout_width="fill_parent" android:layout_height="fill_parent" xmlns:android="http://schemas.android.com/apk/res/android">  
  3.         <EditText android:layout_height="wrap_content" android:id="@+id/editText1" android:text="@string/tv" android:layout_width="fill_parent" android:editable="false" android:layout_gravity="center_horizontal"></EditText>  
  4.     </LinearLayout>  



1. Activity
Java代码 复制代码
  1. package qijia.si;   
  2.   
  3. import android.app.Activity;   
  4. import android.app.Notification;   
  5. import android.app.NotificationManager;   
  6. import android.app.PendingIntent;   
  7. import android.content.Intent;   
  8. import android.os.Bundle;   
  9. import android.view.View;   
  10. import android.view.View.OnClickListener;   
  11. import android.widget.Button;   
  12.   
  13. public class ContextMenuDemo extends Activity {   
  14.   
  15.        
  16.     /** Called when the activity is first created. */  
  17.     @Override  
  18.     public void onCreate(Bundle savedInstanceState) {   
  19.         super.onCreate(savedInstanceState);   
  20.         setContentView(R.layout.main);   
  21.         Button btn = (Button)findViewById(R.id.button1);   
  22.         //添加监听   
  23.         btn.setOnClickListener(new OnClickListener(){   
  24.   
  25.             public void onClick(View v) {   
  26.                 // TODO Auto-generated method stub   
  27.                 Intent i = new Intent(ContextMenuDemo.this,NotifiedActivity.class);   
  28.                 //建立一个新的Activity   
  29.                 PendingIntent pi = PendingIntent.getActivity(ContextMenuDemo.this0, i, 0);   
  30.                 //创建一个Notification对象   
  31.                 Notification myNotification = new Notification();   
  32.                 myNotification.icon = R.drawable.header;   
  33.                 //设置文字和声音   
  34.                 myNotification.tickerText = getResources().getString(R.string.Notification);   
  35.                 myNotification.defaults = Notification.DEFAULT_SOUND;   
  36.                 myNotification.setLatestEventInfo(ContextMenuDemo.this"Example""Hello World", pi);   
  37.                 //建立NotificationManger并发送消息   
  38.                 NotificationManager notificationManager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);   
  39.                 notificationManager.notify(0,myNotification);   
  40.             }   
  41.                
  42.         });   
  43.     }   
  44.        
  45. }  
package qijia.si;

import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class ContextMenuDemo extends Activity {

	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Button btn = (Button)findViewById(R.id.button1);
        //添加监听
        btn.setOnClickListener(new OnClickListener(){

			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent i = new Intent(ContextMenuDemo.this,NotifiedActivity.class);
				//建立一个新的Activity
				PendingIntent pi = PendingIntent.getActivity(ContextMenuDemo.this, 0, i, 0);
				//创建一个Notification对象
				Notification myNotification = new Notification();
				myNotification.icon = R.drawable.header;
				//设置文字和声音
				myNotification.tickerText = getResources().getString(R.string.Notification);
				myNotification.defaults = Notification.DEFAULT_SOUND;
				myNotification.setLatestEventInfo(ContextMenuDemo.this, "Example", "Hello World", pi);
				//建立NotificationManger并发送消息
				NotificationManager notificationManager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
				notificationManager.notify(0,myNotification);
			}
        	
        });
    }
    
}
2. Activity
Java代码 复制代码
  1. package qijia.si;   
  2.   
  3. import android.app.Activity;   
  4. import android.os.Bundle;   
  5.   
  6. //当用户在状态栏点击Notification时会启动该Activity   
  7. public class NotifiedActivity extends Activity{   
  8.   
  9.     @Override  
  10.     protected void onCreate(Bundle savedInstanceState) {   
  11.         // TODO Auto-generated method stub   
  12.         super.onCreate(savedInstanceState);   
  13.         setContentView(R.layout.notified);   
  14.     }   
  15.        
  16.   
  17. }  
package qijia.si;

import android.app.Activity;
import android.os.Bundle;

//当用户在状态栏点击Notification时会启动该Activity
public class NotifiedActivity extends Activity{

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.notified);
	}
	

}

注意最后在AndroidManifest.xml中添加新的Acitivity,否则无法显示。
Android开发06—菜单与对话框(上)

1. 菜单
1) 选项菜单和子菜单
当Activity在前台工作的时候,按下menu将会弹出相应的选项菜单。这个功能是需要开发人员编成实现的,如果在程序中没有此功能,那么程序运行时按下手机的menu键将不会有反映。
对于有图标的选项菜单,每次最多能显示6个,当多于6个时,将只显示前5个和一个拓展菜单选项。
在Android中通过回调方法来创建菜单并处理菜单按下的事件。
开发选项菜单主要用到Menu,MenuItem及SubMenu
实例:接受用户在菜单中的选项并输出到文本框控件中
main.xml:
Xml代码 复制代码
  1. <?xml version="1.0" encoding="utf-8"?>  
  2.     <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_height="fill_parent" android:layout_width="fill_parent" android:id="@+id/linearLayout1">  
  3.         <ScrollView android:layout_width="fill_parent" android:layout_height="fill_parent" android:id="@+id/scrollView1">  
  4.             <EditText android:layout_width="fill_parent" android:layout_height="fill_parent" android:id="@+id/editText1" android:editable="false" android:cursorVisible="false" android:text="@string/label"></EditText>  
  5.         </ScrollView>  
  6.     </LinearLayout>  
Activity:
Java代码 复制代码
  1. package qijia.si;   
  2.   
  3. import android.app.Activity;   
  4. import android.app.TabActivity;   
  5. import android.os.Bundle;   
  6. import android.view.LayoutInflater;   
  7. import android.view.Menu;   
  8. import android.view.MenuItem;   
  9. import android.view.MenuItem.OnMenuItemClickListener;   
  10. import android.view.SubMenu;   
  11. import android.view.View;   
  12. import android.view.ViewGroup;   
  13. import android.widget.AdapterView;   
  14. import android.widget.AdapterView.OnItemClickListener;   
  15. import android.widget.BaseAdapter;   
  16. import android.widget.EditText;   
  17. import android.widget.Gallery;   
  18. import android.widget.ImageView;   
  19. import android.widget.ProgressBar;   
  20. import android.widget.RatingBar;   
  21. import android.widget.TabHost;   
  22.   
  23. public class JavaTest extends Activity {   
  24.     /** Called when the activity is first created. */  
  25.     final int MENU_GENDER_MALE = 0;   
  26.     final int MENU_GENDER_FEMALE = 1;   
  27.     final int MENU_HOBBY1=2;   
  28.     final int MENU_HOBBY2=3;   
  29.     final int MENU_HOBBY3=4;   
  30.     final int MENU_OK=5;   
  31.     final int MENU_GENDER=6;   
  32.     final int MENU_HOBBY=7;   
  33.     final int GENDER_GROUP=0;   
  34.     final int HOBBY_GROUP=1;   
  35.     final int MAIN_GROUP=2;   
  36.     MenuItem[] miaHobby = new MenuItem[3];   
  37.     MenuItem male = null;   
  38.     @Override  
  39.     public void onCreate(Bundle savedInstanceState) {   
  40.         super.onCreate(savedInstanceState);   
  41.         setContentView(R.layout.main);   
  42.            
  43.     }    
  44.     public boolean onCreateOptionsMenu(Menu menu){   
  45.         //初始化菜单通过此函数实现   
  46.         SubMenu subMenuGender = menu.addSubMenu(MAIN_GROUP,MENU_GENDER,0,R.string.gender);   
  47.         subMenuGender.setIcon(R.drawable.gender);   
  48.         subMenuGender.setHeaderIcon(R.drawable.gender);   
  49.         male = subMenuGender.add(GENDER_GROUP,MENU_GENDER_MALE,0,R.string.male);   
  50.         male.setChecked(true);   
  51.         subMenuGender.add(GENDER_GROUP,MENU_GENDER_FEMALE,0,R.string.female);   
  52.            
  53.         subMenuGender.setGroupCheckable(GENDER_GROUP, truetrue);   
  54.         SubMenu subMenuHobby = menu.addSubMenu(MAIN_GROUP,MENU_HOBBY,0,R.string.hobby);   
  55.         subMenuHobby.setIcon(R.drawable.hobby);   
  56.         miaHobby[0] = subMenuHobby.add(HOBBY_GROUP,MENU_HOBBY1,0,R.string.hobby1);   
  57.         miaHobby[1] = subMenuHobby.add(HOBBY_GROUP,MENU_HOBBY2,0,R.string.hobby2);   
  58.         miaHobby[2] = subMenuHobby.add(HOBBY_GROUP,MENU_HOBBY3,0,R.string.hobby3);   
  59.         miaHobby[0].setCheckable(true);   
  60.         miaHobby[1].setCheckable(true);   
  61.         miaHobby[2].setCheckable(true);   
  62.            
  63.         MenuItem ok = menu.add(GENDER_GROUP+2,MENU_OK,0,R.string.ok);   
  64.         OnMenuItemClickListener lsn = new OnMenuItemClickListener(){   
  65.   
  66.             public boolean onMenuItemClick(MenuItem item) {   
  67.                 // TODO Auto-generated method stub   
  68.                 appendStateStr();   
  69.                    
  70.                 return true;   
  71.             }   
  72.                
  73.         };   
  74.         ok.setOnMenuItemClickListener(lsn);   
  75.         ok.setAlphabeticShortcut('o');   
  76.         return true;   
  77.     }   
  78.     public boolean onOptionsItemSelected(MenuItem mi){   
  79.         switch(mi.getItemId()){   
  80.         case MENU_GENDER_MALE:   
  81.         case MENU_GENDER_FEMALE:   
  82.             mi.setChecked(true);   
  83.             appendStateStr();   
  84.             break;   
  85.         case MENU_HOBBY1:   
  86.         case MENU_HOBBY2:   
  87.         case MENU_HOBBY3:   
  88.             mi.setChecked(!mi.isChecked());   
  89.             appendStateStr();   
  90.             break;   
  91.         }   
  92.         return true;   
  93.     }   
  94.     public void appendStateStr(){   
  95.         String result = "您选择的性别为:";   
  96.         if(male.isChecked()){   
  97.             result = result +"男";   
  98.         }else{   
  99.             result+="女";   
  100.         }   
  101.         String hobbyStr="";   
  102.         for(MenuItem mi:miaHobby){   
  103.             if(mi.isChecked()){   
  104.                 hobbyStr = hobbyStr+mi.getTitle()+",";   
  105.             }   
  106.         }   
  107.         if(hobbyStr.length()>0){   
  108.             result=result+",您的爱好为:"+hobbyStr.substring(0,hobbyStr.length()-1)+"。\n";   
  109.         }   
  110.         else{   
  111.             result = result+"。\n";   
  112.         }   
  113.         EditText et = (EditText) JavaTest.this.findViewById(R.id.editText1);   
  114.         et.append(result);   
  115.     }   
  116. }  
package qijia.si;

import android.app.Activity;
import android.app.TabActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MenuItem.OnMenuItemClickListener;
import android.view.SubMenu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RatingBar;
import android.widget.TabHost;

public class JavaTest extends Activity {
    /** Called when the activity is first created. */
	final int MENU_GENDER_MALE = 0;
	final int MENU_GENDER_FEMALE = 1;
	final int MENU_HOBBY1=2;
	final int MENU_HOBBY2=3;
	final int MENU_HOBBY3=4;
	final int MENU_OK=5;
	final int MENU_GENDER=6;
	final int MENU_HOBBY=7;
	final int GENDER_GROUP=0;
	final int HOBBY_GROUP=1;
	final int MAIN_GROUP=2;
	MenuItem[] miaHobby = new MenuItem[3];
	MenuItem male = null;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
    } 
    public boolean onCreateOptionsMenu(Menu menu){
    	//初始化菜单通过此函数实现
    	SubMenu subMenuGender = menu.addSubMenu(MAIN_GROUP,MENU_GENDER,0,R.string.gender);
    	subMenuGender.setIcon(R.drawable.gender);
    	subMenuGender.setHeaderIcon(R.drawable.gender);
    	male = subMenuGender.add(GENDER_GROUP,MENU_GENDER_MALE,0,R.string.male);
    	male.setChecked(true);
    	subMenuGender.add(GENDER_GROUP,MENU_GENDER_FEMALE,0,R.string.female);
		
    	subMenuGender.setGroupCheckable(GENDER_GROUP, true, true);
    	SubMenu subMenuHobby = menu.addSubMenu(MAIN_GROUP,MENU_HOBBY,0,R.string.hobby);
    	subMenuHobby.setIcon(R.drawable.hobby);
    	miaHobby[0] = subMenuHobby.add(HOBBY_GROUP,MENU_HOBBY1,0,R.string.hobby1);
    	miaHobby[1] = subMenuHobby.add(HOBBY_GROUP,MENU_HOBBY2,0,R.string.hobby2);
    	miaHobby[2] = subMenuHobby.add(HOBBY_GROUP,MENU_HOBBY3,0,R.string.hobby3);
    	miaHobby[0].setCheckable(true);
    	miaHobby[1].setCheckable(true);
    	miaHobby[2].setCheckable(true);
    	
    	MenuItem ok = menu.add(GENDER_GROUP+2,MENU_OK,0,R.string.ok);
    	OnMenuItemClickListener lsn = new OnMenuItemClickListener(){

			public boolean onMenuItemClick(MenuItem item) {
				// TODO Auto-generated method stub
				appendStateStr();
				
				return true;
			}
    		
    	};
    	ok.setOnMenuItemClickListener(lsn);
    	ok.setAlphabeticShortcut('o');
    	return true;
    }
    public boolean onOptionsItemSelected(MenuItem mi){
    	switch(mi.getItemId()){
    	case MENU_GENDER_MALE:
    	case MENU_GENDER_FEMALE:
    		mi.setChecked(true);
    		appendStateStr();
    		break;
    	case MENU_HOBBY1:
    	case MENU_HOBBY2:
    	case MENU_HOBBY3:
    		mi.setChecked(!mi.isChecked());
    		appendStateStr();
    		break;
    	}
		return true;
    }
    public void appendStateStr(){
    	String result = "您选择的性别为:";
    	if(male.isChecked()){
    		result = result +"男";
    	}else{
    		result+="女";
    	}
    	String hobbyStr="";
    	for(MenuItem mi:miaHobby){
    		if(mi.isChecked()){
    			hobbyStr = hobbyStr+mi.getTitle()+",";
    		}
    	}
    	if(hobbyStr.length()>0){
    		result=result+",您的爱好为:"+hobbyStr.substring(0,hobbyStr.length()-1)+"。\n";
    	}
    	else{
    		result = result+"。\n";
    	}
    	EditText et = (EditText) JavaTest.this.findViewById(R.id.editText1);
    	et.append(result);
    }
}
2. 上下文菜单
ContextMenu继承自Menu。上下文菜单不同于选项菜单,选项菜单服务于Activity,而上下文菜单是注册到某个View对象上的。如果一个View对象注册了上下文菜单,用户可以通过长按该View对象以呼叫上下文菜单。
上下文菜单不支持快捷键,也不能附带图标,但是可以为上下文菜单的标题指定图标。
用法实例:
main.xml:
Xml代码 复制代码
  1. <?xml version="1.0" encoding="utf-8"?>  
  2.     <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_height="fill_parent" android:orientation="vertical" android:layout_width="fill_parent" android:id="@+id/linearLayout1">  
  3.         <EditText android:layout_width="fill_parent" android:layout_height="wrap_content" android:id="@+id/editText1" android:text="@string/et1"></EditText>  
  4.         <EditText android:layout_width="fill_parent" android:layout_height="wrap_content" android:id="@+id/editText2" android:text="@string/et2"></EditText>  
  5.     </LinearLayout>  


Acticity:
Java代码 复制代码
  1. package qijia.si;   
  2.   
  3. import android.app.Activity;   
  4. import android.os.Bundle;   
  5. import android.view.ContextMenu;   
  6. import android.view.MenuItem;   
  7. import android.view.View;   
  8. import android.widget.EditText;   
  9.   
  10. public class ContextMenuDemo extends Activity {   
  11.     //定义菜单编号   
  12.        
  13.     final int MENU1 = 1;   
  14.     final int MENU2 = 2;   
  15.     final int MENU3 = 3;   
  16.     final int MENU4 = 4;   
  17.     final int MENU5 = 5;   
  18.        
  19.     /** Called when the activity is first created. */  
  20.     @Override  
  21.     public void onCreate(Bundle savedInstanceState) {   
  22.         super.onCreate(savedInstanceState);   
  23.         setContentView(R.layout.main);   
  24.         //注册上下文菜单   
  25.         this.registerForContextMenu(findViewById(R.id.editText1));   
  26.         this.registerForContextMenu(findViewById(R.id.editText2));   
  27.     }   
  28.     //此方法在每次调用上下文菜单时都会被调用一次   
  29.     public void onCreateContextMenu (ContextMenu menu,View v,   
  30.                                     ContextMenu.ContextMenuInfo menuInfo){   
  31.         //为上下文设置标题图标   
  32.         menu.setHeaderIcon(R.drawable.header);   
  33.         //若是第一文本框   
  34.         if(v == findViewById(R.id.editText1)){   
  35.             //为上下文菜单添加菜单选项   
  36.             menu.add(0,MENU1,0,R.string.mi1);   
  37.             menu.add(0,MENU2,0,R.string.mi2);   
  38.             menu.add(0,MENU3,0,R.string.mi3);   
  39.                
  40.         }else if(v == findViewById(R.id.editText2)){   
  41.             menu.add(0,MENU4,0,R.string.mi4);   
  42.             menu.add(0,MENU5,0,R.string.mi5);   
  43.         }   
  44.            
  45.     }   
  46.        
  47.     //菜单选项选中状态变化后的回调方法   
  48.     public boolean onContextItemSelected(MenuItem mi){   
  49.         //判断被选中的MenuItem   
  50.         switch(mi.getItemId()){   
  51.         case MENU1:   
  52.         case MENU2:   
  53.         case MENU3:   
  54.                 EditText et1 = (EditText)this.findViewById(R.id.editText1);   
  55.                    
  56.                 et1.append("\n"+mi.getTitle()+" 被按下");   
  57.                    
  58.                 break;   
  59.         case MENU4:   
  60.         case MENU5:   
  61.                 EditText et2 = (EditText)this.findViewById(R.id.editText2);   
  62.                    
  63.                 et2.append("\n"+mi.getTitle()+" 被按下");   
  64.                    
  65.                 break;   
  66.         }   
  67.         return true;   
  68.     }   
  69.        
  70.        
  71. }  
package qijia.si;

import android.app.Activity;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;

public class ContextMenuDemo extends Activity {
	//定义菜单编号
	
	final int MENU1 = 1;
	final int MENU2 = 2;
	final int MENU3 = 3;
	final int MENU4 = 4;
	final int MENU5 = 5;
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        //注册上下文菜单
        this.registerForContextMenu(findViewById(R.id.editText1));
        this.registerForContextMenu(findViewById(R.id.editText2));
    }
    //此方法在每次调用上下文菜单时都会被调用一次
    public void onCreateContextMenu (ContextMenu menu,View v,
    								ContextMenu.ContextMenuInfo menuInfo){
    	//为上下文设置标题图标
    	menu.setHeaderIcon(R.drawable.header);
    	//若是第一文本框
    	if(v == findViewById(R.id.editText1)){
    		//为上下文菜单添加菜单选项
    		menu.add(0,MENU1,0,R.string.mi1);
    		menu.add(0,MENU2,0,R.string.mi2);
    		menu.add(0,MENU3,0,R.string.mi3);
    		
    	}else if(v == findViewById(R.id.editText2)){
    		menu.add(0,MENU4,0,R.string.mi4);
    		menu.add(0,MENU5,0,R.string.mi5);
    	}
    	
    }
    
    //菜单选项选中状态变化后的回调方法
    public boolean onContextItemSelected(MenuItem mi){
    	//判断被选中的MenuItem
    	switch(mi.getItemId()){
    	case MENU1:
    	case MENU2:
    	case MENU3:
    			EditText et1 = (EditText)this.findViewById(R.id.editText1);
    			
    			et1.append("\n"+mi.getTitle()+" 被按下");
    			
    			break;
    	case MENU4:
    	case MENU5:
    			EditText et2 = (EditText)this.findViewById(R.id.editText2);
    			
    			et2.append("\n"+mi.getTitle()+" 被按下");
    			
    			break;
    	}
    	return true;
    }
    
    
}
3. 对话框
对话框是Activity运行时显示的小窗口,当显示对话框时,当前Activity失去焦点而由对话框负责所有的人机交互。一般来说,对话框用于提示消息或弹出一个与程序主进程直接相关的小程序。
Android平台下主要有以下几种对话框:
1) 提示对话框 AlertDialog
AlertDialog对话框可以包含若干按钮和一些可选的单选按钮或复选框。
2) 进度对话框
ProgressDialog可以显示进度轮或进度条,由于ProgressDialog继承自AlertDialog,所以其也可以添加按钮。
3) 日期选择对话框DatePickerDialog
4) 时间选择对话框TimePickerDialog

对话框是作为Activity的一部分被创建和显示的,在程序中通过开发回调方法onCreateDialog来完成对话框的创建,该方法需要传入代表对话框id参数。如果需要显示对话框,则调用showDialog方法传入对话框id来显示指定的对话框。

当对话框第一次被显示时,Android会调用onCreateDialog方法来创建对话框实例,之后将不再重复创建该实例。同时,每次对话框再被显示之前都会调用onPrepareDialog方法,如果补充些该方法,那么每次显示的对话框将是最初创建的那个。

关闭对话框可以调用Dialog类的dismiss方法来实现,但是要注意这种方法不会让对话框彻底消失,如果要对话框被关闭后彻底消失,要调用removeDialog方法并传入Dialog的id。

下面通过普通对话框的例子来说明如何使用:

main.xml:
Xml代码 复制代码
  1. <?xml version="1.0" encoding="utf-8"?>  
  2.     <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/linearLayout1" android:layout_height="fill_parent" android:orientation="vertical" android:layout_width="fill_parent">  
  3.         <EditText android:layout_width="fill_parent" android:layout_height="wrap_content" android:id="@+id/editText1" android:text="@string/blank" android:editable="false" android:cursorVisible="false"></EditText>  
  4.         <Button android:id="@+id/button1" android:layout_height="wrap_content" android:text="@string/btn" android:layout_width="fill_parent"></Button>  
  5.     </LinearLayout>  

Activity:
Java代码 复制代码
  1. package qijia.si;   
  2.   
  3. import android.app.Activity;   
  4. import android.app.AlertDialog;   
  5. import android.app.AlertDialog.Builder;   
  6. import android.app.Dialog;   
  7. import android.content.DialogInterface;   
  8. import android.content.DialogInterface.OnClickListener;   
  9. import android.os.Bundle;   
  10. import android.view.ContextMenu;   
  11. import android.view.MenuItem;   
  12. import android.view.View;   
  13. import android.widget.Button;   
  14. import android.widget.EditText;   
  15.   
  16. public class ContextMenuDemo extends Activity {   
  17.     //普通对话框id   
  18.     final int COMMON_DIALOG = 1;   
  19.     /** Called when the activity is first created. */  
  20.     @Override  
  21.     public void onCreate(Bundle savedInstanceState) {   
  22.         super.onCreate(savedInstanceState);   
  23.         setContentView(R.layout.main);   
  24.            
  25.         //获取Button对象   
  26.         Button btn = (Button)findViewById(R.id.button1);   
  27.         //为Button设置监听器   
  28.         btn.setOnClickListener(new View.OnClickListener() {   
  29.                
  30.             public void onClick(View v) {   
  31.                 // TODO Auto-generated method stub   
  32.                 showDialog(COMMON_DIALOG);   
  33.             }   
  34.         });   
  35.            
  36.     }   
  37.     //重写onCreateDialog方法   
  38.     public Dialog onCreateDialog(int id){   
  39.         //声明一个dialog对象用于返回   
  40.         Dialog dialog = null;   
  41.         switch(id){   
  42.         case COMMON_DIALOG:   
  43.             Builder b = new AlertDialog.Builder(this);   
  44.             //设置对话框图标   
  45.             b.setIcon(R.drawable.header);   
  46.             b.setTitle(R.string.btn);   
  47.             b.setMessage(R.string.dialog_msg);   
  48.             //添加按钮   
  49.             b.setPositiveButton(R.string.ok,    
  50.                     new OnClickListener(){   
  51.   
  52.                         public void onClick(DialogInterface dialog, int which) {   
  53.                             // TODO Auto-generated method stub   
  54.                             EditText et = (EditText)findViewById(R.id.editText1);   
  55.                             et.setText(R.string.dialog_msg);   
  56.                         }   
  57.                    
  58.             });   
  59.             dialog = b.create();   
  60.             break;   
  61.         default:   
  62.             break;   
  63.                
  64.         }   
  65.         return dialog;   
  66.     }   
  67.        
  68.        
  69.        
  70.        
  71. }  
package qijia.si;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class ContextMenuDemo extends Activity {
	//普通对话框id
	final int COMMON_DIALOG = 1;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        //获取Button对象
        Button btn = (Button)findViewById(R.id.button1);
        //为Button设置监听器
        btn.setOnClickListener(new View.OnClickListener() {
			
			public void onClick(View v) {
				// TODO Auto-generated method stub
				showDialog(COMMON_DIALOG);
			}
		});
        
    }
    //重写onCreateDialog方法
    public Dialog onCreateDialog(int id){
    	//声明一个dialog对象用于返回
    	Dialog dialog = null;
    	switch(id){
    	case COMMON_DIALOG:
    		Builder b = new AlertDialog.Builder(this);
    		//设置对话框图标
    		b.setIcon(R.drawable.header);
    		b.setTitle(R.string.btn);
    		b.setMessage(R.string.dialog_msg);
    		//添加按钮
    		b.setPositiveButton(R.string.ok, 
    				new OnClickListener(){

						public void onClick(DialogInterface dialog, int which) {
							// TODO Auto-generated method stub
							EditText et = (EditText)findViewById(R.id.editText1);
							et.setText(R.string.dialog_msg);
						}
    			
    		});
    		dialog = b.create();
    		break;
    	default:
    		break;
    		
    	}
    	return dialog;
    }
    
    
    
    
}
Android开发05—Android常用高级控件(下)

1. 滑块与进度条
1) ProgressBar类
ProgressBar类同样位于android.widget包下,但其继承自View,主要用于显示一些操作的进度。应用程序可以修改其长度表示当前后台操作的完成情况。因为进度条会移动,所以长时间加载某些资源或者执行某些耗时的操作时,不会使用户界面失去响应。

2) SeekBar类
SeekBar类继承自ProgressBar,是用来接收用户输入的控件。SeekBar类似于拖拉条,可以直观地显示用户需要的数据,常用于音量调节等场合。
3) 实例:
main.xml
Xml代码 复制代码
  1. <?xml version="1.0" encoding="utf-8"?>  
  2.     <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" android:id="@+id/linearLayout1">  
  3.         <ProgressBar android:id="@+id/progressBar1" android:layout_height="wrap_content" android:layout_width="fill_parent" android:max="100" android:progress="20" style="@android:style/Widget.ProgressBar.Horizontal"></ProgressBar>  
  4.         <RatingBar android:layout_height="wrap_content" android:layout_width="wrap_content" android:max="5"  android:rating="1" android:id="@+id/ratingBar1"></RatingBar>  
  5.     </LinearLayout>  

Activity:
Java代码 复制代码
  1. package qijia.si;   
  2.   
  3. import android.app.Activity;   
  4. import android.os.Bundle;   
  5. import android.widget.ProgressBar;   
  6. import android.widget.RatingBar;   
  7.   
  8. public class JavaTest extends Activity {   
  9.     /** Called when the activity is first created. */  
  10.     final static double MAX = 100;   
  11.     final static double MAX_STAR = 5;   
  12.     @Override  
  13.     public void onCreate(Bundle savedInstanceState) {   
  14.         super.onCreate(savedInstanceState);   
  15.         setContentView(R.layout.main);   
  16.         RatingBar rb = (RatingBar) findViewById(R.id.ratingBar1);   
  17.            
  18.         rb.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener() {   
  19.                
  20.             public void onRatingChanged(RatingBar ratingBar, float rating,   
  21.                     boolean fromUser) {   
  22.                 // TODO Auto-generated method stub   
  23.                 ProgressBar pb = (ProgressBar) findViewById(R.id.progressBar1);   
  24.                 RatingBar rb = (RatingBar) findViewById(R.id.ratingBar1);   
  25.                 float rate = rb.getRating();   
  26.                 pb.setProgress((int)(rate/MAX_STAR*MAX));   
  27.             }   
  28.         });   
  29.     }   
  30. }  
package qijia.si;

import android.app.Activity;
import android.os.Bundle;
import android.widget.ProgressBar;
import android.widget.RatingBar;

public class JavaTest extends Activity {
    /** Called when the activity is first created. */
	final static double MAX = 100;
	final static double MAX_STAR = 5;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        RatingBar rb = (RatingBar) findViewById(R.id.ratingBar1);
        
        rb.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener() {
			
			public void onRatingChanged(RatingBar ratingBar, float rating,
					boolean fromUser) {
				// TODO Auto-generated method stub
				ProgressBar pb = (ProgressBar) findViewById(R.id.progressBar1);
				RatingBar rb = (RatingBar) findViewById(R.id.ratingBar1);
				float rate = rb.getRating();
				pb.setProgress((int)(rate/MAX_STAR*MAX));
			}
		});
    }
}
2. 选项卡
TabHost类位于android.widget包下,是选项卡的封装类,用于创建创建选项卡的窗口。TabHost继承自FrameLayout是帧布局的一种。
实例:
main.xml:
Xml代码 复制代码
  1. <?xml version="1.0" encoding="utf-8"?>  
  2.     <FrameLayout android:id="@+id/frameLayout1" android:layout_width="fill_parent" android:layout_height="fill_parent" xmlns:android="http://schemas.android.com/apk/res/android">  
  3.         <LinearLayout android:id="@+id/linearLayout1" android:layout_width="fill_parent" android:layout_height="fill_parent" android:gravity="center_horizontal" android:orientation="vertical">  
  4.             <ImageView android:layout_height="wrap_content" android:layout_width="wrap_content" android:id="@+id/imageView1" android:scaleType="fitXY" android:layout_gravity="center" android:src="@drawable/andy"></ImageView>  
  5.             <TextView android:layout_height="wrap_content" android:id="@+id/textView1" android:layout_width="wrap_content" android:text="@string/andy" android:textSize="24dip"></TextView>  
  6.         </LinearLayout>  
  7.         <LinearLayout android:layout_width="fill_parent" android:layout_height="fill_parent" android:gravity="center_horizontal" android:orientation="vertical" android:id="@+id/linearLayout2">  
  8.             <ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/imageView2" android:scaleType="fitXY" android:layout_gravity="center" android:src="@drawable/bill"></ImageView>  
  9.             <TextView android:layout_height="wrap_content" android:text="@string/bill" android:layout_width="wrap_content" android:id="@+id/textView2" android:textSize="24dip"></TextView>  
  10.         </LinearLayout>  
  11.         <LinearLayout android:layout_width="fill_parent" android:orientation="vertical" android:gravity="center_horizontal" android:layout_height="fill_parent" android:id="@+id/linearLayout3">  
  12.             <ImageView android:layout_height="wrap_content" android:layout_width="wrap_content" android:id="@+id/imageView3" android:scaleType="fitXY" android:layout_gravity="center" android:src="@drawable/torvalds"></ImageView>  
  13.             <TextView android:layout_height="wrap_content" android:text="@string/linus" android:layout_width="wrap_content" android:id="@+id/textView3" android:textSize="24dip"></TextView>  
  14.         </LinearLayout>  
  15.     </FrameLayout>  
   

Activity:
Java代码 复制代码
  1. package qijia.si;   
  2.   
  3. import android.app.Activity;   
  4. import android.app.TabActivity;   
  5. import android.os.Bundle;   
  6. import android.view.LayoutInflater;   
  7. import android.widget.ProgressBar;   
  8. import android.widget.RatingBar;   
  9. import android.widget.TabHost;   
  10.   
  11. public class JavaTest extends TabActivity {   
  12.     /** Called when the activity is first created. */  
  13.     private TabHost myTabhost;   
  14.     @Override  
  15.     public void onCreate(Bundle savedInstanceState) {   
  16.         super.onCreate(savedInstanceState);   
  17.         myTabhost = this.getTabHost();   
  18.         LayoutInflater.from(this).inflate(R.layout.main, myTabhost.getTabContentView(),true);   
  19.         myTabhost.addTab(myTabhost.newTabSpec("选项卡1").setIndicator("选项卡1",getResources().getDrawable(R.drawable.png1)).setContent(R.id.linearLayout1));   
  20.         myTabhost.addTab(myTabhost.newTabSpec("选项卡2").setIndicator("选项卡2",getResources().getDrawable(R.drawable.png2)).setContent(R.id.linearLayout2));   
  21.         myTabhost.addTab(myTabhost.newTabSpec("选项卡3").setIndicator("选项卡3",getResources().getDrawable(R.drawable.png3)).setContent(R.id.linearLayout3));   
  22.     }   
  23. }  
package qijia.si;

import android.app.Activity;
import android.app.TabActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.widget.ProgressBar;
import android.widget.RatingBar;
import android.widget.TabHost;

public class JavaTest extends TabActivity {
    /** Called when the activity is first created. */
	private TabHost myTabhost;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        myTabhost = this.getTabHost();
        LayoutInflater.from(this).inflate(R.layout.main, myTabhost.getTabContentView(),true);
        myTabhost.addTab(myTabhost.newTabSpec("选项卡1").setIndicator("选项卡1",getResources().getDrawable(R.drawable.png1)).setContent(R.id.linearLayout1));
        myTabhost.addTab(myTabhost.newTabSpec("选项卡2").setIndicator("选项卡2",getResources().getDrawable(R.drawable.png2)).setContent(R.id.linearLayout2));
        myTabhost.addTab(myTabhost.newTabSpec("选项卡3").setIndicator("选项卡3",getResources().getDrawable(R.drawable.png3)).setContent(R.id.linearLayout3));
    }
}
3. 画廊控件
Gallery是一种水平滚动的列表,一般情况下用来显示图片等资源,可以使图片在屏幕上滑来滑去。Gallery所显示的图片资源同样来自适配器。
Gallery是View的子类,Gallery控件可以在XML中配置,也可以再代码中操作。
实例:将需要显示的控件存放在BaseAdapter中,然后在适当的时间将此BaseAdapter设置Gallery控件使之显示。

main.xml
Xml代码 复制代码
  1. <?xml version="1.0" encoding="utf-8"?>  
  2.     <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" android:id="@+id/linearLayout1" android:gravity="center_vertical">  
  3.         <Gallery android:layout_height="wrap_content" android:layout_width="fill_parent" android:id="@+id/gallery1" android:spacing="10dip" android:unselectedAlpha="1"></Gallery>  
  4.     </LinearLayout>  


Activity:
Java代码 复制代码
  1. package qijia.si;   
  2.   
  3. import android.app.Activity;   
  4. import android.app.TabActivity;   
  5. import android.os.Bundle;   
  6. import android.view.LayoutInflater;   
  7. import android.view.View;   
  8. import android.view.ViewGroup;   
  9. import android.widget.AdapterView;   
  10. import android.widget.AdapterView.OnItemClickListener;   
  11. import android.widget.BaseAdapter;   
  12. import android.widget.Gallery;   
  13. import android.widget.ImageView;   
  14. import android.widget.ProgressBar;   
  15. import android.widget.RatingBar;   
  16. import android.widget.TabHost;   
  17.   
  18. public class JavaTest extends Activity {   
  19.     /** Called when the activity is first created. */  
  20.     int[] imageIds={   
  21.             R.drawable.bbta,R.drawable.bbtb,R.drawable.bbtc,   
  22.             R.drawable.bbtd,R.drawable.bbte,R.drawable.bbtf,   
  23.             R.drawable.bbtg            
  24.     };   
  25.     @Override  
  26.     public void onCreate(Bundle savedInstanceState) {   
  27.         super.onCreate(savedInstanceState);   
  28.         setContentView(R.layout.main);   
  29.         Gallery g1 = (Gallery)this.findViewById(R.id.gallery1);   
  30.         BaseAdapter ba = new BaseAdapter(){   
  31.   
  32.             public int getCount() {   
  33.                 // TODO Auto-generated method stub   
  34.                 return imageIds.length;   
  35.             }   
  36.   
  37.             public Object getItem(int position) {   
  38.                 // TODO Auto-generated method stub   
  39.                 return null;   
  40.             }   
  41.   
  42.             public long getItemId(int position) {   
  43.                 // TODO Auto-generated method stub   
  44.                 return 0;   
  45.             }   
  46.   
  47.             public View getView(int position, View convertView, ViewGroup parent) {   
  48.                 // TODO Auto-generated method stub   
  49.                 ImageView iv = new ImageView(JavaTest.this);   
  50.                    
  51.                 iv.setImageResource(imageIds[position]);   
  52.                 iv.setScaleType(ImageView.ScaleType.FIT_XY);   
  53.                 iv.setLayoutParams(new Gallery.LayoutParams(188,250));   
  54.                 return iv;   
  55.                    
  56.             }   
  57.                
  58.         };   
  59.         g1.setAdapter(ba);   
  60.         g1.setOnItemClickListener(   
  61.             new OnItemClickListener(){   
  62.   
  63.                 public void onItemClick(AdapterView<?> arg0, View arg1,   
  64.                         int arg2, long arg3) {   
  65.                     // TODO Auto-generated method stub   
  66.                     Gallery g1 = (Gallery)findViewById(R.id.gallery1);   
  67.                     g1.setSelection(arg2);   
  68.                 }   
  69.                    
  70.             });   
  71.     }    
  72. }  
package qijia.si;

import android.app.Activity;
import android.app.TabActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RatingBar;
import android.widget.TabHost;

public class JavaTest extends Activity {
    /** Called when the activity is first created. */
	int[] imageIds={
			R.drawable.bbta,R.drawable.bbtb,R.drawable.bbtc,
			R.drawable.bbtd,R.drawable.bbte,R.drawable.bbtf,
			R.drawable.bbtg			
	};
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Gallery g1 = (Gallery)this.findViewById(R.id.gallery1);
        BaseAdapter ba = new BaseAdapter(){

			public int getCount() {
				// TODO Auto-generated method stub
				return imageIds.length;
			}

			public Object getItem(int position) {
				// TODO Auto-generated method stub
				return null;
			}

			public long getItemId(int position) {
				// TODO Auto-generated method stub
				return 0;
			}

			public View getView(int position, View convertView, ViewGroup parent) {
				// TODO Auto-generated method stub
				ImageView iv = new ImageView(JavaTest.this);
				
				iv.setImageResource(imageIds[position]);
				iv.setScaleType(ImageView.ScaleType.FIT_XY);
				iv.setLayoutParams(new Gallery.LayoutParams(188,250));
				return iv;
				
			}
        	
        };
        g1.setAdapter(ba);
        g1.setOnItemClickListener(
        	new OnItemClickListener(){

				public void onItemClick(AdapterView<?> arg0, View arg1,
						int arg2, long arg3) {
					// TODO Auto-generated method stub
					Gallery g1 = (Gallery)findViewById(R.id.gallery1);
					g1.setSelection(arg2);
				}
        		
        	});
    } 
}

Android开发04—Android常用高级控件(上)

1. 自动完成文本框
AutoCompleteTextView类继承自EditText类。自动完成文本框的外观与文本框没什么区别,只是当用户输入某些文字时,会自动出现下拉菜单显示与输入文字相关的信息。
自动完成文本框可以在XML文件中使用属性进行设置,也可以在Java代码中通过方法进行设置。

实例:
main.xml:
Xml代码 复制代码
  1. <?xml version="1.0" encoding="utf-8"?>  
  2.     <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" android:id="@+id/linearLayout1">  
  3.         <AutoCompleteTextView android:text="AutoCompleteTextView" android:layout_width="fill_parent" android:layout_height="wrap_content" android:id="@+id/autoCompleteTextView1"></AutoCompleteTextView>  
  4.     </LinearLayout>  

Activity:
Java代码 复制代码
  1. package qijia.si;   
  2.   
  3. import android.app.Activity;   
  4. import android.graphics.drawable.AnimationDrawable;   
  5. import android.os.Bundle;   
  6. import android.view.View;   
  7. import android.view.View.OnClickListener;   
  8. import android.widget.ArrayAdapter;   
  9. import android.widget.AutoCompleteTextView;   
  10. import android.widget.Button;   
  11. import android.widget.ImageView;   
  12.   
  13.   
  14.   
  15.   
  16. public class MyAndroidProject extends Activity {   
  17.            
  18.     private static final String[] myStr = new String[]{   
  19.             "aaa","bbb","ccc","aab","aac","aad"  
  20.                
  21.     };  //常量数组用于提示   
  22.     /** Called when the activity is first created. */  
  23.     @Override  
  24.     public void onCreate(Bundle savedInstanceState) {   
  25.         super.onCreate(savedInstanceState);      
  26.         setContentView(R.layout.main);   
  27.         ArrayAdapter<String> aa = new ArrayAdapter<String>(   
  28.                 this,   
  29.                 android.R.layout.simple_dropdown_item_1line,   
  30.                 myStr   
  31.         );//使用适配器   
  32.         AutoCompleteTextView myAuto = (AutoCompleteTextView) findViewById(R.id.autoCompleteTextView1);   
  33.         myAuto.setAdapter(aa);   
  34.         myAuto.setThreshold(1);   
  35.     }   
  36. }  
package qijia.si;

import android.app.Activity;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.ImageView;




public class MyAndroidProject extends Activity {
		
	private static final String[] myStr = new String[]{
			"aaa","bbb","ccc","aab","aac","aad"
			
	};	//常量数组用于提示
	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);   
        setContentView(R.layout.main);
        ArrayAdapter<String> aa = new ArrayAdapter<String>(
        		this,
        		android.R.layout.simple_dropdown_item_1line,
        		myStr
        );//使用适配器
    	AutoCompleteTextView myAuto = (AutoCompleteTextView) findViewById(R.id.autoCompleteTextView1);
    	myAuto.setAdapter(aa);
    	myAuto.setThreshold(1);
    }
}

2. 滚动视图
ScrollView类继承自FrameLayout类。ScrollView其实是一个帧布局,一般情况下,其中的控件是按照线性进行布局的,用户可以对其进行滚动。
ScrollView既可以在XML中配置也可在Java代码中进行配置。
ScrollView的使用方法比较简单,只需要将需要滚动的控件添加到ScrollView中即可。ScrollView同一时刻只能包含一个View。

具体方法:
Java代码 复制代码
  1. package qijia.si;   
  2.   
  3. import android.app.Activity;   
  4. import android.graphics.drawable.AnimationDrawable;   
  5. import android.os.Bundle;   
  6. import android.view.View;   
  7. import android.view.View.OnClickListener;   
  8. import android.widget.ArrayAdapter;   
  9. import android.widget.AutoCompleteTextView;   
  10. import android.widget.Button;   
  11. import android.widget.ImageView;   
  12. import android.widget.ScrollView;   
  13. import android.widget.TextView;   
  14.   
  15.   
  16.   
  17.   
  18. public class MyAndroidProject extends Activity {   
  19.            
  20.     ScrollView scrollView;   
  21.     String msg = "我是字符串,我很长很长!我是字符串,我很长很长!";   
  22.     String str = "";   
  23.        
  24.     /** Called when the activity is first created. */  
  25.     @Override  
  26.     public void onCreate(Bundle savedInstanceState) {   
  27.         super.onCreate(savedInstanceState);      
  28.         setContentView(R.layout.main);   
  29.         scrollView = new ScrollView(this);   
  30.         TextView tv = new TextView(this);   
  31.         tv.setTextSize(23);   
  32.         for(int i = 0;i<10;i++){   
  33.             str = str + msg;   
  34.         }   
  35.         tv.setText(str);   
  36.         scrollView.addView(tv);   
  37.         setContentView(scrollView);   
  38.            
  39.     }     
  40. }  
package qijia.si;

import android.app.Activity;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ScrollView;
import android.widget.TextView;




public class MyAndroidProject extends Activity {
		
	ScrollView scrollView;
	String msg = "我是字符串,我很长很长!我是字符串,我很长很长!";
	String str = "";
	
	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);   
        setContentView(R.layout.main);
        scrollView = new ScrollView(this);
        TextView tv = new TextView(this);
        tv.setTextSize(23);
        for(int i = 0;i<10;i++){
        	str = str + msg;
        }
        tv.setText(str);
        scrollView.addView(tv);
        setContentView(scrollView);
        
    }  
}


3. 列表视图
ListView类是一种列表视图,将ListAdapter所提供的各个控件显示在一个垂直且可以滚动的列表中。
该类使用方法简单,只需要先初始化所需要得数据,然后创建适配器并将其设置给ListView,ListView便将信息以列表的形式显示到页面中。

使用案例:

string.xml
Xml代码 复制代码
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <resources>  
  3.     <string name="app_name">AbsoluteExample</string>  
  4.     <string name="hello">您选择了</string>  
  5.     <string name="andy">Andy Rubin \nAndroid的创造者之一</string>  
  6.     <string name="Bill">Bill Joy \nJava创造者之一</string>  
  7.     <string name="edgar">Edgar F. Codd \n关系数据库之父</string>  
  8.     <string name="torvalds">Linus Torvalds \nLinux之父</string>  
  9.     <string name="turing">Turing Alan \nIT的祖师爷</string>  
  10.     <string name="ys">您选择了</string>  
  11. </resources>  

colors.xml
Xml代码 复制代码
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <resources>  
  3.     <color name="white">#ffffff</color>  
  4.     <color name="red">#ff0000</color>  
  5.     <color name="black">#000000</color>  
  6.     <color name="green">#00ff00</color>  
  7.     <color name="gray">#050505</color>  
  8.     <color name="blue">#0000ff</color>  
  9. </resources>  
main.xml
Xml代码 复制代码
  1. <?xml version="1.0" encoding="utf-8"?>  
  2.     <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:id="@+id/linearLayout1" android:layout_width="fill_parent" android:layout_height="fill_parent">  
  3.         <TextView android:layout_height="wrap_content" android:id="@+id/textView1" android:layout_width="fill_parent" android:textSize="24dip" android:textColor="@color/white" android:text="@string/hello"></TextView>  
  4.         <ListView android:layout_height="wrap_content" android:layout_width="fill_parent" android:id="@+id/listView1" android:choiceMode="singleChoice"></ListView>  
  5.     </LinearLayout>  
  
  
   
   

Activity:
Java代码 复制代码
  1. package qijia.si;   
  2.   
  3. import android.app.Activity;   
  4. import android.graphics.drawable.AnimationDrawable;   
  5. import android.os.Bundle;   
  6. import android.view.View;   
  7. import android.view.View.OnClickListener;   
  8. import android.view.ViewGroup;   
  9. import android.widget.AdapterView;   
  10. import android.widget.AdapterView.OnItemClickListener;   
  11. import android.widget.AdapterView.OnItemSelectedListener;   
  12. import android.widget.ArrayAdapter;   
  13. import android.widget.AutoCompleteTextView;   
  14. import android.widget.BaseAdapter;   
  15. import android.widget.Button;   
  16. import android.widget.Gallery;   
  17. import android.widget.ImageView;   
  18. import android.widget.LinearLayout;   
  19. import android.widget.ListView;   
  20. import android.widget.ScrollView;   
  21. import android.widget.TextView;   
  22.   
  23.   
  24.   
  25.   
  26. public class MyAndroidProject extends Activity {   
  27.            
  28.     int[] drawableIds = {R.drawable.andy,R.drawable.bill,R.drawable.edgar,R.drawable.torvalds,   
  29.                 R.drawable.turing};   
  30.     int[] msgIds = {R.string.andy,R.string.Bill,R.string.edgar,R.string.torvalds,R.string.turing};   
  31.     /** Called when the activity is first created. */  
  32.     @Override  
  33.     public void onCreate(Bundle savedInstanceState) {   
  34.         super.onCreate(savedInstanceState);      
  35.         setContentView(R.layout.main);   
  36.         ListView lv = (ListView) findViewById(R.id.listView1);   
  37.            
  38.         BaseAdapter ba = new BaseAdapter(){   
  39.             public int  getCount() {return 5;}   
  40.             public Object getItem(int arg0){return null;}   
  41.             public long getItemId(int arg0){return 0;}   
  42.             public View getView(int arg0,View arg1, ViewGroup arg2){   
  43.                 //动态生成每一个下拉项对应的View,每个下拉项View由LinearLayout   
  44.                 //中包含一个ImageView及一个TextView,由代码动态生成   
  45.                 LinearLayout ll = new LinearLayout(MyAndroidProject.this);   
  46.                    
  47.                 ll.setOrientation(LinearLayout.HORIZONTAL);   
  48.                 ll.setPadding(5555);   
  49.                 ImageView ii = new ImageView(MyAndroidProject.this);   
  50.                 ii.setImageDrawable(getResources().getDrawable(drawableIds[arg0]));   
  51.                 ii.setScaleType(ImageView.ScaleType.FIT_XY);   
  52.                 ii.setLayoutParams(new Gallery.LayoutParams(100,98));   
  53.                 ll.addView(ii);   
  54.                 TextView tv = new TextView(MyAndroidProject.this);   
  55.                 tv.setText(getResources().getText(msgIds[arg0]));   
  56.                 tv.setTextSize(24);   
  57.                 tv.setTextColor(MyAndroidProject.this.getResources().getColor(R.color.white));   
  58.                 tv.setPadding(5555);   
  59.                 ll.addView(tv);   
  60.                 return ll;   
  61.                
  62.                 }   
  63.                
  64.         };   
  65.         lv.setAdapter(ba);   
  66.         lv.setOnItemSelectedListener(new OnItemSelectedListener(){   
  67.             public void onItemSelected(AdapterView<?> arg0,View arg1, int arg2,long arg3){   
  68.                 TextView tv = (TextView) findViewById(R.id.textView1);   
  69.                    
  70.                 LinearLayout ll = (LinearLayout)arg1;   
  71.                    
  72.                 TextView tvn = (TextView)ll.getChildAt(1);   
  73.                 StringBuilder sb = new StringBuilder();   
  74.                    
  75.                 sb.append(getResources().getText(R.string.ys));   
  76.                 sb.append(":");   
  77.                 sb.append(tvn.getText());   
  78.                 String stemp = sb.toString();   
  79.                 tv.setText(stemp.split("\\n")[0]);   
  80.             }   
  81.             public void onNothingSelected(AdapterView<?> arg0){}   
  82.         });   
  83.         lv.setOnItemClickListener(new OnItemClickListener(){   
  84.                 public void onItemClick(AdapterView<?> arg0,View arg1,int arg2,long arg3){   
  85.                     TextView tv = (TextView) findViewById(R.id.textView1);   
  86.                     LinearLayout ll =(LinearLayout) arg1;   
  87.                        
  88.                     TextView tvn = (TextView)ll.getChildAt(1);   
  89.                     StringBuilder sb = new StringBuilder();   
  90.                        
  91.                     sb.append(getResources().getText(R.string.ys));   
  92.                     sb.append(":");   
  93.                     sb.append(tvn.getText());   
  94.                     String stemp  = sb.toString();   
  95.                     tv.setText(stemp.split("\\n")[0]);   
  96.                 }   
  97.         });   
  98.     }     
  99. }  
package qijia.si;

import android.app.Activity;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ScrollView;
import android.widget.TextView;




public class MyAndroidProject extends Activity {
		
	int[] drawableIds = {R.drawable.andy,R.drawable.bill,R.drawable.edgar,R.drawable.torvalds,
				R.drawable.turing};
	int[] msgIds = {R.string.andy,R.string.Bill,R.string.edgar,R.string.torvalds,R.string.turing};
	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);   
        setContentView(R.layout.main);
        ListView lv = (ListView) findViewById(R.id.listView1);
        
        BaseAdapter ba = new BaseAdapter(){
        	public int  getCount() {return 5;}
        	public Object getItem(int arg0){return null;}
        	public long getItemId(int arg0){return 0;}
        	public View getView(int arg0,View arg1, ViewGroup arg2){
        		//动态生成每一个下拉项对应的View,每个下拉项View由LinearLayout
        		//中包含一个ImageView及一个TextView,由代码动态生成
        		LinearLayout ll = new LinearLayout(MyAndroidProject.this);
        		
        		ll.setOrientation(LinearLayout.HORIZONTAL);
        		ll.setPadding(5, 5, 5, 5);
        		ImageView ii = new ImageView(MyAndroidProject.this);
        		ii.setImageDrawable(getResources().getDrawable(drawableIds[arg0]));
        		ii.setScaleType(ImageView.ScaleType.FIT_XY);
        		ii.setLayoutParams(new Gallery.LayoutParams(100,98));
        		ll.addView(ii);
        		TextView tv = new TextView(MyAndroidProject.this);
        		tv.setText(getResources().getText(msgIds[arg0]));
        		tv.setTextSize(24);
        		tv.setTextColor(MyAndroidProject.this.getResources().getColor(R.color.white));
        		tv.setPadding(5, 5, 5, 5);
        		ll.addView(tv);
        		return ll;
        	
        		}
        	
        };
        lv.setAdapter(ba);
        lv.setOnItemSelectedListener(new OnItemSelectedListener(){
        	public void onItemSelected(AdapterView<?> arg0,View arg1, int arg2,long arg3){
        		TextView tv = (TextView) findViewById(R.id.textView1);
        		
        		LinearLayout ll = (LinearLayout)arg1;
        		
        		TextView tvn = (TextView)ll.getChildAt(1);
        		StringBuilder sb = new StringBuilder();
        		
        		sb.append(getResources().getText(R.string.ys));
        		sb.append(":");
        		sb.append(tvn.getText());
        		String stemp = sb.toString();
        		tv.setText(stemp.split("\\n")[0]);
        	}
        	public void onNothingSelected(AdapterView<?> arg0){}
        });
        lv.setOnItemClickListener(new OnItemClickListener(){
        		public void onItemClick(AdapterView<?> arg0,View arg1,int arg2,long arg3){
        			TextView tv = (TextView) findViewById(R.id.textView1);
        			LinearLayout ll =(LinearLayout) arg1;
        			
        			TextView tvn = (TextView)ll.getChildAt(1);
        			StringBuilder sb = new StringBuilder();
        			
        			sb.append(getResources().getText(R.string.ys));
        			sb.append(":");
        			sb.append(tvn.getText());
        			String stemp  = sb.toString();
        			tv.setText(stemp.split("\\n")[0]);
        		}
        });
    }  
}
4. 网络视图
GridView类同样位于android.widget包下。该视图将其空间以二维格式显示到表格中,而这些控件全部来自于ListAdapter适配器。
strings.xml
Xml代码 复制代码
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <resources>  
  3.     <string name="hello">当前无选中选项</string>  
  4.     <string name="app_name">Sample_5_3</string>  
  5.     <string name="andy">Andy Rubin</string>  
  6.     <string name="bill">Bill Joy</string>  
  7.     <string name="edgar">Edgar F. Codd</string>  
  8.     <string name="torvalds">Linus Torvalds</string>  
  9.     <string name="turing">Turing Alan</string>  
  10.     <string name="andydis">Android的创造者</string>  
  11.     <string name="billdis">Java创造者之一</string>  
  12.     <string name="edgardis">关系数据库之父</string>  
  13.     <string name="torvaldsdis">Linux之父</string>  
  14.     <string name="turingdis">IT的祖师爷</string>            
  15. </resources>  

colors.xml
Xml代码 复制代码
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <resources>  
  3.     <color name="red">#fd8d8d</color>  
  4.     <color name="green">#9cfda3</color>  
  5.     <color name="blue">#8d9dfd</color>  
  6.     <color name="white">#FFFFFF</color>  
  7.     <color name="black">#000000</color>  
  8.     <color name="gray">#050505</color>  
  9. </resources>  
main.xml
Xml代码 复制代码
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:orientation="vertical"  
  4.     android:layout_width="fill_parent"  
  5.     android:layout_height="fill_parent">  
  6.     <TextView     
  7.         android:id="@+id/TextView01"  
  8.         android:layout_width="fill_parent"    
  9.         android:layout_height="wrap_content"    
  10.         android:text="@string/hello"  
  11.         android:textColor="@color/white"  
  12.         android:textSize="24dip"/>  
  13.     <GridView    
  14.         android:id="@+id/GridView01"    
  15.         android:layout_width="fill_parent"    
  16.         android:layout_height="fill_parent"  
  17.         android:verticalSpacing="5dip"  
  18.         android:horizontalSpacing="5dip"  
  19.         android:stretchMode="columnWidth"/>  
  20. </LinearLayout>  
grid_row.xml
Xml代码 复制代码
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout    
  3.   android:id="@+id/LinearLayout01"    
  4.   android:layout_width="fill_parent"    
  5.   android:layout_height="wrap_content"    
  6.   android:orientation="horizontal"  
  7.   xmlns:android="http://schemas.android.com/apk/res/android">     
  8.     <ImageView    
  9.        android:id="@+id/ImageView01"    
  10.        android:scaleType="fitXY"  
  11.        android:layout_width="100dip"  
  12.        android:layout_height="98dip"/>  
  13.     <TextView    
  14.         android:id="@+id/TextView02"    
  15.         android:layout_width="100dip"    
  16.         android:layout_height="wrap_content"  
  17.         android:textColor="@color/white"  
  18.         android:textSize="24dip"  
  19.         android:paddingLeft="5dip"/>  
  20.     <TextView    
  21.         android:id="@+id/TextView03"    
  22.         android:layout_width="wrap_content"    
  23.         android:layout_height="wrap_content"  
  24.         android:textColor="@color/white"  
  25.         android:textSize="24dip"  
  26.         android:paddingLeft="5dip"/>  
  27. </LinearLayout>  
Activity:

Java代码 复制代码
  1. package qijia.si;   
  2. import java.util.ArrayList;   
  3. import java.util.HashMap;   
  4. import java.util.List;   
  5. import java.util.Map;   
  6. import android.app.Activity;   
  7. import android.os.Bundle;   
  8. import android.view.View;   
  9. import android.widget.AdapterView;   
  10. import android.widget.GridView;   
  11. import android.widget.LinearLayout;   
  12. import android.widget.SimpleAdapter;   
  13. import android.widget.TextView;   
  14. import android.widget.AdapterView.OnItemClickListener;   
  15. import android.widget.AdapterView.OnItemSelectedListener;   
  16. public class GridDemo extends Activity {   
  17.     //所有资源图片(andy、bill、edgar、torvalds、turing)id的数组   
  18.     int[] drawableIds=   
  19.         {R.drawable.andy,R.drawable.bill,R.drawable.edgar,R.drawable.torvalds,R.drawable.turing};   
  20.     //所有资源字符串(andy、bill、edgar、torvalds、turing)id的数组   
  21.     int[] nameIds=   
  22.         {R.string.andy,R.string.bill,R.string.edgar,R.string.torvalds,R.string.turing};   
  23.     int[] msgIds=   
  24.         {R.string.andydis,R.string.billdis,R.string.edgardis,   
  25.             R.string.torvaldsdis,R.string.turingdis};   
  26.     public List<? extends Map<String, ?>> generateDataList(){   
  27.         ArrayList<Map<String,Object>> list=new ArrayList<Map<String,Object>>();;   
  28.         int rowCounter=drawableIds.length;//得到表格的行数   
  29.         for(int i=0;i<rowCounter;i++){//循环生成每行的包含对应各个列数据的Map;col1、col2、col3为列名   
  30.             HashMap<String,Object> hmap=new HashMap<String,Object>();   
  31.             hmap.put("col1", drawableIds[i]);   //第一列为图片           
  32.             hmap.put("col2"this.getResources().getString(nameIds[i]));//第二例为姓名   
  33.             hmap.put("col3"this.getResources().getString(msgIds[i]));//第三列为描述   
  34.             list.add(hmap);   
  35.         }          
  36.         return list;   
  37.     }   
  38.     public void onCreate(Bundle savedInstanceState) {   
  39.         super.onCreate(savedInstanceState);   
  40.         setContentView(R.layout.main);   
  41.         GridView gv=(GridView)this.findViewById(R.id.GridView01);           
  42.         SimpleAdapter sca=new SimpleAdapter(   
  43.             this,   
  44.             generateDataList(), //数据List   
  45.             R.layout.grid_row, //行对应layout id   
  46.             new String[]{"col1","col2","col3"}, //列名列表   
  47.             new int[]{R.id.ImageView01,R.id.TextView02,R.id.TextView03}//列对应控件id列表   
  48.         );   
  49.         gv.setAdapter(sca);//为GridView设置数据适配器   
  50.         gv.setOnItemSelectedListener(//设置选项选中的监听器   
  51.            new OnItemSelectedListener(){   
  52.                public void onItemSelected(AdapterView<?> arg0, View arg1,   
  53.                     int arg2, long arg3) {//重写选项被选中事件的处理方法   
  54.                    TextView tv=(TextView)findViewById(R.id.TextView01);//获取主界面TextView   
  55.                    LinearLayout ll=(LinearLayout)arg1;//获取当前选中选项对应的LinearLayout   
  56.                    TextView tvn=(TextView)ll.getChildAt(1);//获取其中的TextView    
  57.                    TextView tvnL=(TextView)ll.getChildAt(2);//获取其中的TextView    
  58.                    StringBuilder sb=new StringBuilder();   
  59.                    sb.append(tvn.getText());//获取姓名信息   
  60.                    sb.append(" ");   
  61.                    sb.append(tvnL.getText());//获取描述信息                  
  62.                    tv.setText(sb.toString());//信息设置进主界面TextView        
  63.                }   
  64.                public void onNothingSelected(AdapterView<?> arg0){}   
  65.             }   
  66.         );     
  67.         gv.setOnItemClickListener( //设置选项被单击的监听器   
  68.             new OnItemClickListener(){   
  69.                public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,   
  70.                     long arg3) {//重写选项被单击事件的处理方法   
  71.                    TextView tv=(TextView)findViewById(R.id.TextView01);//获取主界面TextView   
  72.                    LinearLayout ll=(LinearLayout)arg1;//获取当前选中选项对应的LinearLayout   
  73.                    TextView tvn=(TextView)ll.getChildAt(1);//获取其中的TextView    
  74.                    TextView tvnL=(TextView)ll.getChildAt(2);//获取其中的TextView    
  75.                    StringBuilder sb=new StringBuilder();   
  76.                    sb.append(tvn.getText());//获取姓名信息   
  77.                    sb.append(" ");   
  78.                    sb.append(tvnL.getText());//获取描述信息                  
  79.                    tv.setText(sb.toString());//信息设置进主界面TextView    
  80.                }                  
  81.             }   
  82.         );           
  83.     }   
  84. }  
package qijia.si;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
public class GridDemo extends Activity {
	//所有资源图片(andy、bill、edgar、torvalds、turing)id的数组
	int[] drawableIds=
		{R.drawable.andy,R.drawable.bill,R.drawable.edgar,R.drawable.torvalds,R.drawable.turing};
	//所有资源字符串(andy、bill、edgar、torvalds、turing)id的数组
	int[] nameIds=
		{R.string.andy,R.string.bill,R.string.edgar,R.string.torvalds,R.string.turing};
	int[] msgIds=
		{R.string.andydis,R.string.billdis,R.string.edgardis,
			R.string.torvaldsdis,R.string.turingdis};
    public List<? extends Map<String, ?>> generateDataList(){
    	ArrayList<Map<String,Object>> list=new ArrayList<Map<String,Object>>();;
    	int rowCounter=drawableIds.length;//得到表格的行数
    	for(int i=0;i<rowCounter;i++){//循环生成每行的包含对应各个列数据的Map;col1、col2、col3为列名
    		HashMap<String,Object> hmap=new HashMap<String,Object>();
    		hmap.put("col1", drawableIds[i]);   //第一列为图片 		
    		hmap.put("col2", this.getResources().getString(nameIds[i]));//第二例为姓名
    		hmap.put("col3", this.getResources().getString(msgIds[i]));//第三列为描述
    		list.add(hmap);
    	}    	
    	return list;
	}
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        GridView gv=(GridView)this.findViewById(R.id.GridView01);        
        SimpleAdapter sca=new SimpleAdapter(
        	this,
        	generateDataList(), //数据List
        	R.layout.grid_row, //行对应layout id
        	new String[]{"col1","col2","col3"}, //列名列表
        	new int[]{R.id.ImageView01,R.id.TextView02,R.id.TextView03}//列对应控件id列表
        );
        gv.setAdapter(sca);//为GridView设置数据适配器
        gv.setOnItemSelectedListener(//设置选项选中的监听器
           new OnItemSelectedListener(){
        	   public void onItemSelected(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {//重写选项被选中事件的处理方法
        		   TextView tv=(TextView)findViewById(R.id.TextView01);//获取主界面TextView
        		   LinearLayout ll=(LinearLayout)arg1;//获取当前选中选项对应的LinearLayout
        		   TextView tvn=(TextView)ll.getChildAt(1);//获取其中的TextView 
        		   TextView tvnL=(TextView)ll.getChildAt(2);//获取其中的TextView 
        		   StringBuilder sb=new StringBuilder();
        		   sb.append(tvn.getText());//获取姓名信息
        		   sb.append(" ");
        		   sb.append(tvnL.getText());//获取描述信息				
        		   tv.setText(sb.toString());//信息设置进主界面TextView		
        	   }
        	   public void onNothingSelected(AdapterView<?> arg0){}
           	}
        );  
        gv.setOnItemClickListener( //设置选项被单击的监听器
        	new OnItemClickListener(){
        	   public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {//重写选项被单击事件的处理方法
        		   TextView tv=(TextView)findViewById(R.id.TextView01);//获取主界面TextView
        		   LinearLayout ll=(LinearLayout)arg1;//获取当前选中选项对应的LinearLayout
        		   TextView tvn=(TextView)ll.getChildAt(1);//获取其中的TextView 
        		   TextView tvnL=(TextView)ll.getChildAt(2);//获取其中的TextView 
        		   StringBuilder sb=new StringBuilder();
        		   sb.append(tvn.getText());//获取姓名信息
        		   sb.append(" ");
        		   sb.append(tvnL.getText());//获取描述信息				
        		   tv.setText(sb.toString());//信息设置进主界面TextView	
        	   }        	   
           	}
        );        
    }
}
Android的adapter总结和深入研究

Adapter是把数据和用户界面视图绑定的桥梁类。Adapter负责创建用来表示父视图中的每一个条目的子视图,并且提供对底层数据的访问。
支持Adapter绑定的用户界面必须对AdapterView抽象类进行拓展。也可以创建新的由AdapterView派生的控件,创建新的Adapter类绑定他们。

两个最通用的本地Adapter
ArrayAdapter ArrayAdapter使用泛型来把Adapter视图(View)绑定到一个指定类的对象的数组。默认情况下,ArrayAdapter使用数组中每个对象的toString值来创建和填充文本视图。

SimpleCursorAdapter SimpleCursorAdapter可以把一个布局中指定的视图和内容提供器查询返回的游标列绑定在一起。
定制ArrayAdapter
默认情况下,ArrayAdapter将使用它绑定到的对象数组的toString值来填充指定布局中可用的TextView
最常见的例子便是ListView
我们在定义一个ListView组件后,在向ListView组件装载数据之前需要创建一个Adapter对象,

ArrayAdapter<String> AdapterName = new ArrayAdapter<String>(
this,
android.R.layout.simple_list_itme_1,
data);
以上代码中创建了一个android.wedget.ArrayAdapter 对象。ArrayAdapter类的构造方法需要一个android.content.Context对象,因此传入当前Activity的对象实例(this)作为ArrayAdapter类的构造方法的第一个参数值。除此之外,ArrayAdapter还需要完成:
指定列表项模板(第二个参数)
指定列表项中的数据。(第三个参数)
在创建玩Adapter对象后,调用setAdapter方法,ListView组件的每一个列表都会使用simple_list_item_1.xml文件定义的模板来显示,并将data数组中的每一个元素复制给每一个列表项

下面我们来讨论下定制ArrayAdapter
在大多数情况下,我们都要定制用于表示每个视图的布局。所以,需要使用特定类型的变体Adapter来扩展ArrayAdapter,并重写getView方法来向布局视图分配对象属性。
getView方法用于构造,扩充和填充将在父AdapterView类(如ListView)中显示的视图,该父AdapterView类使用这个Adapter绑定到底层的数组。
getView方法接收描述要显示的条目的位置,要更新的视图(或null),以及将包含这个视图的视图组作为参数。调用getItem将返回存储在底层数组的指定索引位置的值。
例如对与ListView来说:
自定义的Adapter类一般需要从android.widget.BaseAdapter类继承。在BaseAdapter类中有两个重要方法:getView和getCount。其中ListView在显示某一列表项是会调用getView方法返回要显示的列表项的View对象,这一点我们上面已经提到了。getCount方法返回当前ListView组件中列表项的总数。
注意:列表项的View对象一定要在getView方法中创建。不能事先创建好View对象,然后再getView方法中返回这些View对象。如果这样做,系统可能会出现一些异常现象

Android开发03—Android常用基本控件(下)



1. 单选按钮和复选按钮
CheckBox和RadioButton控件都只有选中和未选中两种状态,不同的是RadioButton是单选按钮,需要便知道RadioGroup中,同一时刻一个RadioGroup中只能有一个按钮处于选中状态。

使用举例:
Java代码 复制代码
  1. public class SampleDemo extends Activity   
  2. {   
  3.     public void onCreate(Bundle savedInstanceState){   
  4.         super.onCreate(savedInstatceState);   
  5.         setContentView(R.layout.main);   
  6.         CheckBox cb = (CheckBox) findViewById(R.id.CheckBox1);   
  7.         cb.setOnCheckedChangeListener(new OnCheckedChangeListener(){   
  8.                         public void onCheckedChanged(CompoundButton buttonView,boolean isChecked){   
  9.                                 setBulbState(isChecked);   
  10.                                
  11.                         }   
  12.         });   
  13.         RadioButton rb = (RadioButton) findViewById(R.id.off);   
  14.         rb.setOnCheckedChangeListener(new OnCheckedChangeListener(){   
  15.                         public void onCheckedChanged(CompoundButton buttonView,boolean isChecked){   
  16.                                 setBulbState(isChecked);   
  17.                            
  18.                            
  19.                         }   
  20.         });   
  21.     }   
  22.     public void setBulbState(boolean state){   
  23.         ImageView iv = (ImageView) findViewById(R.id.ImageView01);   
  24.         iv.setImageResource((state)?R.drawable.bulb_on:R.drawable.bulb_off);   
  25.         CheckBox cb = (CheckBox) this.findViewById(R.id.CheckBox1);   
  26.   
  27.         cb.setText((state)?R.string.off:R.string.on);   
  28.         cb.setChecked(state);   
  29.         RadioButton rb = (RadioButton) this.findViewById(R.id.off);   
  30.   
  31.         rb.setChecked(state);   
  32.         rb = (RadioButton) findViewById(R.id.on);   
  33.         rb.setChecked(state);   
  34.        
  35.     }   
  36. }  
public class SampleDemo extends Activity
{
	public void onCreate(Bundle savedInstanceState){
		super.onCreate(savedInstatceState);
		setContentView(R.layout.main);
		CheckBox cb = (CheckBox) findViewById(R.id.CheckBox1);
		cb.setOnCheckedChangeListener(new OnCheckedChangeListener(){
						public void onCheckedChanged(CompoundButton buttonView,boolean isChecked){
								setBulbState(isChecked);
							
						}
		});
		RadioButton rb = (RadioButton) findViewById(R.id.off);
		rb.setOnCheckedChangeListener(new OnCheckedChangeListener(){
						public void onCheckedChanged(CompoundButton buttonView,boolean isChecked){
								setBulbState(isChecked);
						
						
						}
		});
	}
	public void setBulbState(boolean state){
		ImageView iv = (ImageView) findViewById(R.id.ImageView01);
		iv.setImageResource((state)?R.drawable.bulb_on:R.drawable.bulb_off);
		CheckBox cb = (CheckBox) this.findViewById(R.id.CheckBox1);

		cb.setText((state)?R.string.off:R.string.on);
		cb.setChecked(state);
		RadioButton rb = (RadioButton) this.findViewById(R.id.off);

		rb.setChecked(state);
		rb = (RadioButton) findViewById(R.id.on);
		rb.setChecked(state);
	
	}
}
2. 图片控件
ImageView控件负责显示图片,其图片的来源既可以是资源文件的id,也可以是Drawable对象或BitMap对象,还可以是ContentProvider的Uri。

实例:ImageView的用法
string.xml
Xml代码 复制代码
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. lt;resources>  
  3.    <string name="app_name">AbsoluteExample</string>  
  4.    <string name="next">下一张</string>  
  5.    <string name="previous">上一张</string>  
  6.    <string name="alpha_plus">透明度增加</string>  
  7.    <string name="alpha_minus">透明度减少</string>  
  8. lt;/resources>  
main.xml
Xml代码 复制代码
  1. <?xml version="1.0" encoding="utf-8"?>  
  2.     <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/linearLayout1" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical">  
  3.         <ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/iv" android:layout_gravity="center_horizontal" android:src="@drawable/pic1" ></ImageView>  
  4.         <LinearLayout android:layout_height="wrap_content" android:id="@+id/linearLayout2" android:layout_gravity="center_horizontal" android:layout_width="fill_parent" android:orientation="horizontal">  
  5.             <Button android:layout_height="wrap_content" android:layout_width="wrap_content" android:id="@+id/previous" android:text="@string/previous" android:gravity="center_horizontal" android:layout_gravity="center_horizontal"></Button>  
  6.             <Button android:layout_height="wrap_content" android:id="@+id/alpha_plus" android:layout_width="wrap_content" android:text="@string/alpha_plus" android:gravity="center_horizontal" android:layout_gravity="center_horizontal"></Button>  
  7.             <Button android:layout_height="wrap_content" android:id="@+id/alpha_minus" android:layout_width="wrap_content" android:text="@string/alpha_minus" android:gravity="center_horizontal" android:layout_gravity="center_horizontal"></Button>  
  8.             <Button android:layout_height="wrap_content" android:id="@+id/next" android:layout_width="wrap_content" android:text="@string/next" android:gravity="center_horizontal" android:layout_gravity="center_horizontal"></Button>  
  9.         </LinearLayout>  
  10.     </LinearLayout>  

Activity部分代码:
Java代码 复制代码
  1. import android.app.Activity;   
  2. import android.os.Bundle;   
  3. import android.view.View;   
  4. import android.widget.Button;   
  5. import android.widget.EditText;   
  6. import android.widget.ImageView;   
  7.   
  8.   
  9. public class MyAndroidProject extends Activity {   
  10.     ImageView iv;   
  11.     Button btnNext;   
  12.     Button btnPrevious;   
  13.     Button btnAlphaPlus;   
  14.     Button btnAlphaMinus;   
  15.     int currImgId = 0;   
  16.     int alpha = 255;   
  17.     int[] imgId ={   
  18.             R.drawable.pic1,   
  19.             R.drawable.pic2,   
  20.             R.drawable.pic3   
  21.     };   
  22.     private View.OnClickListener myListener = new View.OnClickListener() {   
  23.            
  24.         public void onClick(View v) {   
  25.             // TODO Auto-generated method stub   
  26.             if(v == btnNext){   
  27.                 currImgId = (currImgId+1) %imgId.length;   
  28.                 iv.setImageResource(imgId[currImgId]);   
  29.             }   
  30.             else if(v == btnPrevious){   
  31.                 currImgId = (currImgId-1+imgId.length) %imgId.length;   
  32.                 iv.setImageResource(imgId[currImgId]);   
  33.             }   
  34.             else if(v == btnAlphaPlus){   
  35.                 alpha -= 25;   
  36.                 if(alpha < 0){   
  37.                     alpha = 0;   
  38.                 }   
  39.                 iv.setAlpha(alpha);   
  40.             }   
  41.             else if(v == btnAlphaMinus){   
  42.                 alpha +=25;   
  43.                 if(alpha >255){   
  44.                     alpha = 255;   
  45.                 }   
  46.                 iv.setAlpha(alpha);   
  47.             }   
  48.         }   
  49.     };   
  50.     /** Called when the activity is first created. */  
  51.     @Override  
  52.     public void onCreate(Bundle savedInstanceState) {   
  53.         super.onCreate(savedInstanceState);      
  54.         setContentView(R.layout.main);   
  55.         iv = (ImageView) findViewById(R.id.iv);   
  56.         btnNext = (Button) findViewById(R.id.next);   
  57.         btnPrevious = (Button) findViewById(R.id.previous);   
  58.         btnAlphaPlus = (Button) findViewById(R.id.alpha_plus);   
  59.         btnAlphaMinus = (Button) findViewById(R.id.alpha_minus);   
  60.            
  61.         btnNext.setOnClickListener(myListener);   
  62.         btnPrevious.setOnClickListener(myListener);   
  63.         btnAlphaPlus.setOnClickListener(myListener);   
  64.         btnAlphaMinus.setOnClickListener(myListener);      
  65.     }   
  66. }  
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;


public class MyAndroidProject extends Activity {
	ImageView iv;
	Button btnNext;
	Button btnPrevious;
	Button btnAlphaPlus;
	Button btnAlphaMinus;
	int currImgId = 0;
	int alpha = 255;
	int[] imgId ={
			R.drawable.pic1,
			R.drawable.pic2,
			R.drawable.pic3
	};
	private View.OnClickListener myListener = new View.OnClickListener() {
		
		public void onClick(View v) {
			// TODO Auto-generated method stub
			if(v == btnNext){
				currImgId = (currImgId+1) %imgId.length;
				iv.setImageResource(imgId[currImgId]);
			}
			else if(v == btnPrevious){
				currImgId = (currImgId-1+imgId.length) %imgId.length;
				iv.setImageResource(imgId[currImgId]);
			}
			else if(v == btnAlphaPlus){
				alpha -= 25;
				if(alpha < 0){
					alpha = 0;
				}
				iv.setAlpha(alpha);
			}
			else if(v == btnAlphaMinus){
				alpha +=25;
				if(alpha >255){
					alpha = 255;
				}
				iv.setAlpha(alpha);
			}
		}
	};
	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);   
        setContentView(R.layout.main);
        iv = (ImageView) findViewById(R.id.iv);
        btnNext = (Button) findViewById(R.id.next);
        btnPrevious = (Button) findViewById(R.id.previous);
        btnAlphaPlus = (Button) findViewById(R.id.alpha_plus);
        btnAlphaMinus = (Button) findViewById(R.id.alpha_minus);
        
        btnNext.setOnClickListener(myListener);
        btnPrevious.setOnClickListener(myListener);
        btnAlphaPlus.setOnClickListener(myListener);
        btnAlphaMinus.setOnClickListener(myListener);   
    }
}

3. 时钟控件
AnalogClock和DigitalClock都负责显示时钟,所不同的是AnalogClock控件显示模拟时钟,且只显示时针和分针,而digital显示数字时钟,可精确到秒
直接在main.xml中定义时钟控件即可。


4. 日期与时间选择控件
DatePicker继承自FrameLayout类,主要功能是向用户提供包含年,月,日的日期数据,并允许用户进行选择。如果要捕获用户修改日期选择控件中数据的时间,需要为DatePicker添加onDateChangedListener监听器。
TimePicker同样继承自FrameLayout类。时间选择控件向用户显示一天中的时间,并允许用户进行选择,如果要捕获用户修改时间数据的时间,便需要为TimePicker添加OnTimeChangedListener监听器。

案例:
main.xml
Xml代码 复制代码
  1. <?xml version="1.0" encoding="utf-8"?>  
  2.    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/linearLayout1" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent">  
  3.        <DatePicker android:layout_gravity="center_horizontal" android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/datePicker1"></DatePicker>  
  4.        <EditText android:layout_height="wrap_content" android:text="EditText" android:layout_width="fill_parent" android:id="@+id/editText1" android:cursorVisible="false" android:editable="false"></EditText>  
  5.        <TimePicker android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/timePicker1" android:layout_gravity="center_horizontal"></TimePicker>  
  6.        <EditText android:layout_height="wrap_content" android:text="EditText" android:layout_width="fill_parent" android:id="@+id/editText2" android:cursorVisible="false" android:editable="false"></EditText>  
  7.    </LinearLayout>  


Activity:
Java代码 复制代码
  1. package qijia.si;   
  2.   
  3. import java.util.Calendar;   
  4.   
  5. import android.app.Activity;   
  6. import android.os.Bundle;   
  7. import android.widget.DatePicker;   
  8. import android.widget.EditText;   
  9. import android.widget.DatePicker.OnDateChangedListener;   
  10. import android.widget.TimePicker;   
  11. import android.widget.TimePicker.OnTimeChangedListener;   
  12.   
  13.   
  14.   
  15. public class MyAndroidProject extends Activity {   
  16.            
  17.            
  18.     /** Called when the activity is first created. */  
  19.     @Override  
  20.     public void onCreate(Bundle savedInstanceState) {   
  21.         super.onCreate(savedInstanceState);      
  22.         setContentView(R.layout.main);   
  23.         DatePicker dp = (DatePicker) findViewById(R.id.datePicker1);   
  24.         TimePicker tp = (TimePicker) findViewById(R.id.timePicker1);   
  25.            
  26.         Calendar c = Calendar.getInstance();   
  27.         int year = c.get(Calendar.YEAR);   
  28.         int monthOfYear = c.get(Calendar.MONTH);   
  29.         int dayOfMonth = c.get(Calendar.DAY_OF_MONTH);   
  30.            
  31.         dp.init(year, monthOfYear, dayOfMonth, new OnDateChangedListener(){   
  32.                     public void onDateChanged(DatePicker view,int year, int monthOfYear,int dayOfMonth){   
  33.                         flushDate(year,monthOfYear,dayOfMonth);   
  34.                     }   
  35.         });   
  36.            
  37.         tp.setOnTimeChangedListener(new OnTimeChangedListener(){   
  38.                     public void onTimeChanged(TimePicker view,int hourOfDay,int minute){   
  39.                         flushTime(hourOfDay,minute);   
  40.                     }   
  41.         });   
  42.     }   
  43.     public void flushDate(int year,int monthOfYear,int dayOfMonth){   
  44.         EditText et = (EditText) findViewById(R.id.editText1);   
  45.         et.setText("您选择的日期是: "+year+"年"+(monthOfYear+1)+"月"+dayOfMonth+"日");   
  46.     }   
  47.     public void flushTime(int hourOfDay,int minute){   
  48.         EditText et = (EditText) findViewById(R.id.editText2);   
  49.         et.setText("您选择的时间是: "+hourOfDay+"时"+minute+"分");   
  50.            
  51.     }   
  52. }  
package qijia.si;

import java.util.Calendar;

import android.app.Activity;
import android.os.Bundle;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.DatePicker.OnDateChangedListener;
import android.widget.TimePicker;
import android.widget.TimePicker.OnTimeChangedListener;



public class MyAndroidProject extends Activity {
		
		
	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);   
        setContentView(R.layout.main);
        DatePicker dp = (DatePicker) findViewById(R.id.datePicker1);
        TimePicker tp = (TimePicker) findViewById(R.id.timePicker1);
        
        Calendar c = Calendar.getInstance();
        int year = c.get(Calendar.YEAR);
        int monthOfYear = c.get(Calendar.MONTH);
        int dayOfMonth = c.get(Calendar.DAY_OF_MONTH);
        
        dp.init(year, monthOfYear, dayOfMonth, new OnDateChangedListener(){
        			public void onDateChanged(DatePicker view,int year, int monthOfYear,int dayOfMonth){
        				flushDate(year,monthOfYear,dayOfMonth);
        			}
        });
        
        tp.setOnTimeChangedListener(new OnTimeChangedListener(){
        			public void onTimeChanged(TimePicker view,int hourOfDay,int minute){
        				flushTime(hourOfDay,minute);
        			}
        });
    }
    public void flushDate(int year,int monthOfYear,int dayOfMonth){
    	EditText et = (EditText) findViewById(R.id.editText1);
    	et.setText("您选择的日期是: "+year+"年"+(monthOfYear+1)+"月"+dayOfMonth+"日");
    }
    public void flushTime(int hourOfDay,int minute){
    	EditText et = (EditText) findViewById(R.id.editText2);
    	et.setText("您选择的时间是: "+hourOfDay+"时"+minute+"分");
    	
    }
}

5. 动画播放技术
动画播放技术主要有两种:帧动画和补间动画。
1) 帧动画
帧动画主要用到的类是AnimationDrawable,每个帧动画都是一个AnimationDrawable对象
定义帧动画可以在代码中直接进行,也可以通过XML文件进行定义,定义帧动画的XML文件将存放在res/anim目录下。XML文件中指定了图片图片帧出现的顺序及每个帧的连续时间。

anim.xml
Xml代码 复制代码
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <animation-list xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:oneshot = "false">  
  4.     <item android:drawable = "@drawable/f1" android:duration="500" android:visible  =    
  5.     "true"/>  
  6.     <item android:drawable = "@drawable/f2" android:duration="500" android:visible  =    
  7.     "true"/>  
  8.     <item android:drawable = "@drawable/f3" android:duration="500" android:visible  =    
  9.     "true"/>  
  10.     <item android:drawable = "@drawable/f4" android:duration="500" android:visible  =    
  11.     "true"/>  
  12. </animation-list>  


main.xml
Xml代码 复制代码
  1. <?xml version="1.0" encoding="utf-8"?>  
  2.     <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" android:id="@+id/linearLayout1">  
  3.         <ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/imageView1" android:layout_gravity="center_horizontal" android:src="@anim/anim"></ImageView>  
  4.         <Button android:layout_height="wrap_content" android:id="@+id/button1" android:text="click" android:layout_width="fill_parent" android:layout_gravity="center_horizontal"></Button>  
  5.     </LinearLayout>  
   
   

Activity:
Java代码 复制代码
  1. package qijia.si;   
  2.   
  3. import android.app.Activity;   
  4. import android.graphics.drawable.AnimationDrawable;   
  5. import android.os.Bundle;   
  6. import android.view.View;   
  7. import android.view.View.OnClickListener;   
  8. import android.widget.Button;   
  9. import android.widget.ImageView;   
  10.   
  11.   
  12.   
  13.   
  14. public class MyAndroidProject extends Activity {   
  15.            
  16.            
  17.     /** Called when the activity is first created. */  
  18.     @Override  
  19.     public void onCreate(Bundle savedInstanceState) {   
  20.         super.onCreate(savedInstanceState);      
  21.         setContentView(R.layout.main);   
  22.         Button btn = (Button) findViewById(R.id.button1);   
  23.         btn.setOnClickListener(new OnClickListener(){   
  24.                 public void onClick(View v){   
  25.                     ImageView iv = (ImageView) findViewById(R.id.imageView1);   
  26.                     iv.setBackgroundResource(R.anim.anim);   
  27.                     AnimationDrawable ad = (AnimationDrawable) iv.getBackground();   
  28.                     ad.start();   
  29.                 }   
  30.         });   
  31.            
  32.     }   
  33. }  
package qijia.si;

import android.app.Activity;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;




public class MyAndroidProject extends Activity {
		
		
	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);   
        setContentView(R.layout.main);
        Button btn = (Button) findViewById(R.id.button1);
        btn.setOnClickListener(new OnClickListener(){
        		public void onClick(View v){
        			ImageView iv = (ImageView) findViewById(R.id.imageView1);
        			iv.setBackgroundResource(R.anim.anim);
        			AnimationDrawable ad = (AnimationDrawable) iv.getBackground();
        			ad.start();
        		}
        });
    	
    }
}
2)补间动画
补间动画作用于View对象,主要包括View对象的位置,尺寸,旋转角度和透明度的变换。
补间动画可以通过XML声明也可以在代码中动态定义。推荐使用XML因为XML文件可读性及可用性高,方便替换。

Android开发03—Android常用基本控件(上)

1. 文本控件介绍
1) TextView类
TextView类继承自View类。TextView控件的功能是向用户显示文本内容,同时可选择性的让用户编辑文本。其自身被设置为不可编辑,其子类EditText被设置为可以编辑。
2) EditText类
EditText继承自TextView。EditText与TextView最大的不同就是用户可以对EditText控件进行编辑,同时还可以为EditText设置监听器,用来检测用户输入是否合法。
实例1:接收用户输入的电子邮箱地址和电话号码:
color.xml
Xml代码 复制代码
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <resources>  
  3.     <color name="shadow">#fd8d8d</color>  
  4. </resources>  


string.xml
Xml代码 复制代码
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <resources>  
  3.     <string name="hello">Hello World, AndroidTest!</string>  
  4.     <string name="app_name">AndroidTest</string>  
  5.     <string name="tvEmail">邮箱地址</string>  
  6.     <string name="etEmail">请输入电子邮件地址</string>  
  7.     <string name="tvPhone">电话号码</string>  
  8.     <string name="etPhone">请输入电话号码</string>  
  9.     <string name="etInfo">此处显示登记信息</string>  
  10. </resources>  

main.xml
Xml代码 复制代码
  1. <?xml version="1.0" encoding="utf-8"?>  
  2.     <TableLayout xmlns:android="http://schemas.android.com/apk/res/android" android:shrinkColumns="0,2" android:layout_width="fill_parent" android:id="@+id/tableLayout1" android:layout_height="fill_parent">  
  3.         <TableRow android:id="@+id/tableRow1" android:layout_width="wrap_content" android:layout_height="wrap_content">  
  4.             <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/tvEmail" android:ellipsize="end" android:autoLink="email" android:id="@+id/tvEmail"></TextView>  
  5.             <EditText android:layout_width="wrap_content" android:layout_height="wrap_content" android:selectAllOnFocus="true" android:hint="@string/etEmail" android:id="@+id/etEmail"></EditText>  
  6.         </TableRow>  
  7.         <TableRow android:id="@+id/tableRow2" android:layout_width="wrap_content" android:layout_height="wrap_content">  
  8.             <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/tvPhone" android:ellipsize="middle" android:autoLink="phone" android:id="@+id/tvPhone"></TextView>  
  9.             <EditText android:layout_width="wrap_content" android:layout_height="wrap_content" android:hint="@string/etPhone" android:selectAllOnFocus="true" android:maxWidth="160px" android:phoneNumber="true" android:singleLine="true" android:id="@+id/etPhone"></EditText>  
  10.         </TableRow>  
  11.         <EditText android:id="@+id/editText3" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="EditText" android:editable="false" android:hint="@string/etInfo" android:cursorVisible="false" android:lines="5" android:shadowColor="@color/shadow" android:shadowDx="2.5" android:shadowDy="2.5" android:shadowRadius="5.0"></EditText>  
  12.     </TableLayout>  

 
MyAndroidTest.java
Java代码 复制代码
  1. package qijia.si;   
  2.   
  3. import android.app.Activity;   
  4. import android.os.Bundle;   
  5. import android.view.KeyEvent;   
  6. import android.view.View;   
  7. import android.view.View.OnKeyListener;   
  8. import android.widget.EditText;   
  9.   
  10. public class AndroidTest extends Activity {   
  11.     /** Called when the activity is first created. */  
  12.        
  13.     @Override  
  14.     public void onCreate(Bundle savedInstanceState) {   
  15.         super.onCreate(savedInstanceState);   
  16.         setContentView(R.layout.main);   
  17.         EditText etEmail = (EditText) findViewById(R.id.etEmail);   
  18.         etEmail.setOnKeyListener(myOnKeyListener);   
  19.            
  20.     }   
  21.     private OnKeyListener myOnKeyListener = new OnKeyListener(){   
  22.            
  23.         public boolean onKey(View v,int keyCode, KeyEvent event){   
  24.             EditText etInfo = (EditText) findViewById(R.id.editText3);   
  25.             EditText etEmail = (EditText) findViewById(R.id.etEmail);   
  26.             etInfo.setText("您输入的邮箱地址是:"+etEmail.getText());   
  27.             return true;   
  28.         }   
  29.     };   
  30.        
  31. }  
package qijia.si;

import android.app.Activity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnKeyListener;
import android.widget.EditText;

public class AndroidTest extends Activity {
    /** Called when the activity is first created. */
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        EditText etEmail = (EditText) findViewById(R.id.etEmail);
        etEmail.setOnKeyListener(myOnKeyListener);
        
    }
    private OnKeyListener myOnKeyListener = new OnKeyListener(){
    	
    	public boolean onKey(View v,int keyCode, KeyEvent event){
    		EditText etInfo = (EditText) findViewById(R.id.editText3);
    		EditText etEmail = (EditText) findViewById(R.id.etEmail);
    		etInfo.setText("您输入的邮箱地址是:"+etEmail.getText());
    		return true;
    	}
    };
    
}

2. 按钮控件
1) Button类简介
Button继承自TextView类,用户可以对Button控件执行按下或单击操作。Button控件的用法简单,主要是为Button控件设置View.OnClickListener监听器并在监听器的实现代码中开发按钮按下的事件。
一般格式:
Java代码 复制代码
  1. public void onCreate(Bundle savedInstanceState){   
  2.         super.onCreate(savedInstanceState);   
  3.         setContentView(R.layout.main);   
  4.         Button btn = (Button) findViewById(R.Id.ID);   
  5.         btn.setOnClickListener(new OnClickListener){   
  6.             public void onClick(View v){   
  7.                 //处理的事件   
  8.                
  9.             }   
  10.         };   
  11.   
  12.   
  13. }  
public void onCreate(Bundle savedInstanceState){
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		Button btn = (Button) findViewById(R.Id.ID);
		btn.setOnClickListener(new OnClickListener){
			public void onClick(View v){
				//处理的事件
			
			}
		};


}

2) ImageButton类
ImageButton类继承自ImageView类,ImageButton控件与Button控件的主要区别在于,ImageButton类没有text属性,即按钮显示图片而不是文本。ImageButton控件设置按钮显示的图片通过android:src属性,也可以通过setImageResource(int)方法来实现。
默认情况下,ImageButton同Button一样具有背景色,当按钮处于不同状态喜爱时,背景色也会变化。当ImageButton所显示图片不能完全覆盖掉背景色时,这种显示效果会相当恶心,所以使用ImageButton一般要将背景色设置为其他图片或直接设置为透明。
注意:新建xml文件文件名不能是大写字母
实例2:为ImageButton按钮控件的不同状态设置不同的图片。
color.xml:
Xml代码 复制代码
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <resources>  
  3.     <color name="back">#000000</color>  
  4. </resources>  


myselector.xml:

Xml代码 复制代码
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <selector xmlns:android="http://schemas.android.com/apk/res/android">  
  3.     <item    
  4.         android:state_pressed="false"  
  5.         android:drawable="@drawable/back"/>             
  6.     <item  
  7.         android:state_pressed="true"  
  8.         android:drawable="@drawable/backdown"/>     
  9. </selector>  

main.xml:
Xml代码 复制代码
  1. <?xml version="1.0" encoding="utf-8"?>  
  2.     <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:id="@+id/linearLayout1" android:layout_height="fill_parent" android:layout_width="fill_parent">  
  3.         <ImageButton android:id="@+id/imageButton1" android:layout_height="wrap_content" android:layout_width="wrap_content" android:background="@color/back" android:src="@drawable/myselector"></ImageButton>  
  4.     </LinearLayout>  

 
3. 状态开关
1) ToggleButton类
ToggleButton的状态只能是选中和未选中,并且需要为不同的状态设置不同的文本。
android:Off  未被选中时显示的文本
android:On  选中时显示的文本

实例3:ToggleButton的用法:

strings.xml:
Xml代码 复制代码
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <resources>  
  3.     <string name="hello">Hello World, AndroidTest!</string>  
  4.     <string name="app_name">AndroidTest</string>  
  5.     <string name="off">关灯</string>  
  6.     <string name="on">开灯</string>  
  7.     
  8. </resources>  


main.xml
Xml代码 复制代码
  1. <?xml version="1.0" encoding="utf-8"?>  
  2.     <LinearLayout android:id="@+id/linearLayout1" android:layout_width="fill_parent" android:layout_height="fill_parent" xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical">  
  3.         <ImageView android:layout_height="wrap_content" android:layout_width="wrap_content" android:src="@drawable/bulb_off" android:id="@+id/ImageView01" android:layout_gravity="center_horizontal"></ImageView>  
  4.         <ToggleButton android:layout_gravity="center_horizontal" android:layout_height="wrap_content" android:layout_width="140dip" android:textOff="@string/on" android:textOn="@string/off" android:id="@+id/Tb"></ToggleButton>  
  5.     </LinearLayout>  


  MyAnroidTest.java:
  package qijia.si;

Java代码 复制代码
  1. import android.app.Activity;   
  2. import android.os.Bundle;   
  3. import android.view.KeyEvent;   
  4. import android.view.View;   
  5. import android.view.View.OnKeyListener;   
  6. import android.widget.CompoundButton;   
  7. import android.widget.CompoundButton.OnCheckedChangeListener;   
  8. import android.widget.EditText;   
  9. import android.widget.ImageView;   
  10. import android.widget.ToggleButton;   
  11.   
  12. public class AndroidTest extends Activity {   
  13.     /** Called when the activity is first created. */  
  14.        
  15.     @Override  
  16.     public void onCreate(Bundle savedInstanceState) {   
  17.         super.onCreate(savedInstanceState);   
  18.         setContentView(R.layout.main);   
  19.         ToggleButton tb =(ToggleButton) findViewById(R.id.Tb);   
  20.         tb.setOnCheckedChangeListener(new OnCheckedChangeListener(){   
  21.                 //添加监听器   
  22.             public void onCheckedChanged(CompoundButton buttonView,   
  23.                     boolean isChecked){   
  24.                 setBulbState(isChecked);   
  25.             }   
  26.         });   
  27.            
  28.     }   
  29.    public void setBulbState(boolean state){   
  30.        ImageView iv = (ImageView) findViewById(R.id.ImageView01);   
  31.        iv.setImageResource((state)?R.drawable.bulb_on:R.drawable.bulb_off);   
  32.                 //设置图片资源   
  33.        ToggleButton tb = (ToggleButton) this.findViewById(R.id.Tb);   
  34.        tb.setChecked(state);   
  35.                 //设置为选中状态   
  36.    }   
  37.        
  38. }  
import android.app.Activity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnKeyListener;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ToggleButton;

public class AndroidTest extends Activity {
    /** Called when the activity is first created. */
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        ToggleButton tb =(ToggleButton) findViewById(R.id.Tb);
        tb.setOnCheckedChangeListener(new OnCheckedChangeListener(){
        		//添加监听器
        	public void onCheckedChanged(CompoundButton buttonView,
        			boolean isChecked){
        		setBulbState(isChecked);
        	}
        });
        
    }
   public void setBulbState(boolean state){
	   ImageView iv = (ImageView) findViewById(R.id.ImageView01);
	   iv.setImageResource((state)?R.drawable.bulb_on:R.drawable.bulb_off);
	   			//设置图片资源
	   ToggleButton tb = (ToggleButton) this.findViewById(R.id.Tb);
	   tb.setChecked(state);
	   			//设置为选中状态
   }
    
}

Android系统开发02—Android布局管理器

1. View,ViewGroup
1) View类
View类为所有可视化控件的基类,主要提供了空间绘制和事件处理。
2)ViewGroup类
ViewGroup类也是View类的子类,但是可以充当其他控件的容器。

2. 线性布局
线性布局是最简单的布局,它提供了控件水平或者垂直排列的模型。使用此布局时可以通过设置控件的weight参数控制各个控件在容器中的相对大小。
线性布局实例:
string.xml:
Xml代码 复制代码
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <resources>  
  3.     <string name="app_name">LinearExample</string>  
  4.     <string name="button">按钮</string>  
  5.     <string name="add">添加</string>  
  6. </resources>  

main.xml:
Xml代码 复制代码
  1. <?xml version="1.0" encoding="utf-8"?>  
  2.     <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_height="fill_parent" android:layout_width="fill_parent" android:id="@+id/lla" android:orientation="vertical" android:gravity="right">  
  3.         <Button android:layout_height="wrap_content" android:layout_width="wrap_content" android:id="@+id/Button01" android:text="@string/add"></Button>  
  4.     </LinearLayout>  

MyAndroidProject.java:
Java代码 复制代码
  1. package qijia.si;   
  2.   
  3. import android.app.Activity;   
  4. import android.os.Bundle;   
  5. import android.view.View;   
  6. import android.widget.Button;   
  7. import android.widget.LinearLayout;   
  8.   
  9.   
  10. public class MyAndroidProject extends Activity {   
  11.     int count = 0;   
  12.     /** Called when the activity is first created. */  
  13.     @Override  
  14.     public void onCreate(Bundle savedInstanceState) {   
  15.         super.onCreate(savedInstanceState);      
  16.         setContentView(R.layout.main);   
  17.         Button btn = (Button) findViewById(R.id.Button01);   
  18.            
  19.         btn.setOnClickListener(   
  20.                 new View.OnClickListener() {   
  21.                        
  22.                     public void onClick(View v) {   
  23.                         // TODO Auto-generated method stub   
  24.                         LinearLayout ll = (LinearLayout) findViewById(R.id.lla);   
  25.                            
  26.                         String msg = MyAndroidProject.this.getResources().getString(R.string.button);   
  27.                         Button tempbutton = new Button(MyAndroidProject.this);   
  28.                            
  29.                         tempbutton.setText(msg+(++count));   
  30.                         tempbutton.setWidth(80);   
  31.                         ll.addView(tempbutton);   
  32.                            
  33.                     }   
  34.                 }   
  35.            
  36.            
  37.            
  38.            
  39.         );   
  40.            
  41.              
  42.     }   
  43. }  
package qijia.si;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;


public class MyAndroidProject extends Activity {
	int count = 0;
	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);   
        setContentView(R.layout.main);
        Button btn = (Button) findViewById(R.id.Button01);
        
        btn.setOnClickListener(
        		new View.OnClickListener() {
					
					public void onClick(View v) {
						// TODO Auto-generated method stub
						LinearLayout ll = (LinearLayout) findViewById(R.id.lla);
						
						String msg = MyAndroidProject.this.getResources().getString(R.string.button);
						Button tempbutton = new Button(MyAndroidProject.this);
						
						tempbutton.setText(msg+(++count));
						tempbutton.setWidth(80);
						ll.addView(tempbutton);
						
					}
				}
        
        
        
        
        );
        
          
    }
}
3. 表格布局
TableLayout类以行和列的形式管理控件,每行为一个TableRow对象,也可以为一个View对象,当为View对象时,该View对象将跨越该行的所有列。在TableRow中可以添加子空间,每添加一个子空间为一列。
在TableLayout中,可以为列设置三种属性:
1) Shrinkable,该列宽度可以进行收缩,以使表格能够适应期父容器的大小
2) Stretchable,该列的宽度可以进行拉伸,以使填满表格中空闲的空间。
3) Collapsed,该列将被隐藏。
注意:一个列可以同时拥有1,2的属性。
案例:
color.xml
Xml代码 复制代码
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <resources>  
  3.     <color name="white">#ffffff</color>  
  4.     <color name="red">#ff0000</color>  
  5.     <color name="black">#000000</color>  
  6.     <color name="green">#00ff00</color>  
  7.     <color name="blue">#0000ff</color>  
  8. </resources>  

string.xml
Xml代码 复制代码
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <resources>  
  3.     <string name="app_name">TableExample</string>  
  4.     <string name="tv1">我自己是一行…………我自己是一行</string>  
  5.     <string name="tvShort">我的内容少</string>  
  6.     <string name="tvStrech">我是被拉伸的一行</string>  
  7.     <string name="tvShrink">我是被收缩的一行被收缩的一行</string>  
  8.     <string name="tvLong">我的内容很多很多很多很多很多很多</string>  
  9. </resources>  

main.xml

Xml代码 复制代码
  1. <?xml version="1.0" encoding="utf-8"?>  
  2.     <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/LinearLayout01" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" android:background="@drawable/pic" android:gravity="bottom">  
  3.         <TableLayout android:layout_height="wrap_content" android:layout_width="fill_parent" android:id="@+id/TableLayout03" android:background="@color/white" android:stretchColumns="0" android:collapseColumns="1">  
  4.         </TableLayout>  
  5.         <TableLayout android:layout_height="wrap_content" android:layout_width="fill_parent" android:id="@+id/TableLayout02" android:background="@color/white" android:stretchColumns="0">  
  6.             <TableRow android:layout_height="wrap_content" android:layout_width="wrap_content" android:id="@+id/TableRow01">  
  7.                 <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/TextView02" android:text="@string/tvStrech" android:layout_margin="4px" android:background="@color/green" android:textColor="@color/blue"></TextView>  
  8.                 <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/TextView03" android:text="@string/tvShort" android:textColor="@color/black" android:background="@color/blue" android:layout_margin="4px"></TextView>  
  9.             </TableRow>  
  10.         </TableLayout>  
  11.         <TableLayout android:layout_height="wrap_content" android:layout_width="fill_parent" android:id="@+id/TableLayout01" android:background="@color/white">  
  12.             <TextView android:textColor="@color/black" android:layout_margin="4px" android:text="@string/tv1" android:background="@color/red" android:layout_height="wrap_content" android:layout_width="wrap_content" android:id="@+id/TextView01"></TextView>  
  13.         </TableLayout>  
  14.     </LinearLayout>  

MyAndroidProject.java
Java代码 复制代码
  1. package qijia.si;   
  2.   
  3. import android.app.Activity;   
  4. import android.os.Bundle;   
  5.   
  6.   
  7.   
  8. public class MyAndroidProject extends Activity {   
  9.     /** Called when the activity is first created. */  
  10.     @Override  
  11.     public void onCreate(Bundle savedInstanceState) {   
  12.         super.onCreate(savedInstanceState);      
  13.         setContentView(R.layout.main);   
  14.              
  15.     }   
  16. }  
package qijia.si;

import android.app.Activity;
import android.os.Bundle;



public class MyAndroidProject extends Activity {
	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);   
        setContentView(R.layout.main);
          
    }
}

4. 相对布局
在相对布局中,子控件的位置是相对兄弟控件或父容器而决定的。
需要注意的是,相对布局中要避免出现循环依赖。
5. 帧布局
FrameLayout帧布局在屏幕上开辟出了一块区域,在这块区域中可以添加多个子控件,但是所有的子空间都被对齐到屏幕的左上角。帧布局的大小由子控件中尺寸最大的那个控件决定。
6. 绝对布局
绝对布局是指屏幕中所有控件的摆放由开发人员通过设置控件的坐标来指定,控件容器不再负责管理其子控件的位置。
案例:
string.xml
Xml代码 复制代码
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <resources>  
  3.     <string name="app_name">AbsoluteExample</string>  
  4.     <string name="uid">用户名</string>  
  5.     <string name="pwd">密码</string>  
  6.     <string name="ok">确定</string>  
  7.     <string name="cancel">取消</string>  
  8. </resources>  

color.xml
Xml代码 复制代码
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <resources>  
  3.     <color name="white">#ffffff</color>  
  4.     <color name="red">#ff0000</color>  
  5.     <color name="black">#000000</color>  
  6.     <color name="green">#00ff00</color>  
  7.     <color name="blue">#0000ff</color>  
  8. </resources>  

main.xml
Xml代码 复制代码
  1. <?xml version="1.0" encoding="utf-8"?>  
  2.     <AbsoluteLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:background="@color/white" android:id="@+id/absoluteLayout1" android:layout_height="fill_parent">  
  3.         <TextView android:layout_height="wrap_content" android:layout_width="wrap_content" android:layout_x="20dip" android:layout_y="20dip" android:id="@+id/TextView01" android:text="@string/uid"></TextView>  
  4.         <TextView android:layout_height="wrap_content" android:layout_width="wrap_content" android:id="@+id/TextView02" android:text="@string/pwd" android:layout_x="20dip" android:layout_y="80dip"></TextView>  
  5.         <EditText android:text="EditText" android:layout_height="wrap_content" android:layout_y="20dip" android:id="@+id/EditText01" android:layout_x="80dip" android:layout_width="180dip"></EditText>  
  6.         <EditText android:text="EditText" android:layout_height="wrap_content" android:id="@+id/EditText02" android:password="true" android:layout_x="80dip" android:layout_y="80dip" android:layout_width="180dip"></EditText>  
  7.         <Button android:layout_height="wrap_content" android:layout_width="wrap_content" android:id="@+id/Button01" android:text="@string/ok" android:layout_x="155dip" android:layout_y="140dip"></Button>  
  8.         <Button android:layout_height="wrap_content" android:layout_width="wrap_content" android:id="@+id/Button02" android:text="@string/cancel" android:layout_x="210dip" android:layout_y="140dip"></Button>  
  9.         <ScrollView android:layout_x="10dip" android:layout_y="200dip" android:layout_height="150dip" android:layout_width="250dip" android:id="@+id/ScrollView01">  
  10.             <EditText android:text="EditText" android:layout_height="wrap_content" android:layout_width="fill_parent" android:singleLine="false" android:gravity="top" android:id="@+id/EditText03"></EditText>  
  11.         </ScrollView>  
  12.     </AbsoluteLayout>  

MyAndroidProject.java
Java代码 复制代码
  1. package qijia.si;   
  2.   
  3. import android.app.Activity;   
  4. import android.os.Bundle;   
  5. import android.view.View;   
  6. import android.widget.Button;   
  7. import android.widget.EditText;   
  8.   
  9.   
  10. public class MyAndroidProject extends Activity {   
  11.     /** Called when the activity is first created. */  
  12.     @Override  
  13.     public void onCreate(Bundle savedInstanceState) {   
  14.         super.onCreate(savedInstanceState);      
  15.         setContentView(R.layout.main);   
  16.         final Button okButton = (Button) findViewById(R.id.Button01);   
  17.         final Button cancelButton = (Button) findViewById(R.id.Button02);   
  18.            
  19.         final EditText uid = (EditText) findViewById(R.id.EditText01);   
  20.         final EditText pwd = (EditText) findViewById(R.id.EditText02);     
  21.         final EditText log = (EditText) findViewById(R.id.EditText03);   
  22.            
  23.         okButton.setOnClickListener(   
  24.                     new View.OnClickListener() {   
  25.                            
  26.                         public void onClick(View v) {   
  27.                             // TODO Auto-generated method stub   
  28.                             String uidStr = uid.getText().toString();   
  29.                             String pwdStr = pwd.getText().toString();   
  30.                                
  31.                             log.append("用户名:"+uidStr+"密码:"+pwdStr+"\n");   
  32.                                
  33.                         }   
  34.                     }   
  35.            
  36.         );   
  37.            
  38.         cancelButton.setOnClickListener(   
  39.                     new View.OnClickListener() {   
  40.                            
  41.                         public void onClick(View v) {   
  42.                             // TODO Auto-generated method stub   
  43.                             uid.setText("");   
  44.                             pwd.setText("");   
  45.                         }   
  46.                     }   
  47.            
  48.            
  49.         );   
  50.            
  51.        
  52.        
  53.     }   
  54. }  
package qijia.si;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;


public class MyAndroidProject extends Activity {
	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);   
        setContentView(R.layout.main);
        final Button okButton = (Button) findViewById(R.id.Button01);
        final Button cancelButton = (Button) findViewById(R.id.Button02);
        
        final EditText uid = (EditText) findViewById(R.id.EditText01);
        final EditText pwd = (EditText) findViewById(R.id.EditText02);  
        final EditText log = (EditText) findViewById(R.id.EditText03);
        
        okButton.setOnClickListener(
        			new View.OnClickListener() {
						
						public void onClick(View v) {
							// TODO Auto-generated method stub
							String uidStr = uid.getText().toString();
							String pwdStr = pwd.getText().toString();
							
							log.append("用户名:"+uidStr+"密码:"+pwdStr+"\n");
							
						}
					}
        
        );
        
        cancelButton.setOnClickListener(
        			new View.OnClickListener() {
						
						public void onClick(View v) {
							// TODO Auto-generated method stub
							uid.setText("");
							pwd.setText("");
						}
					}
        
        
        );
        
    
    
    }
}
Android系统开发01—Android基本组件

1. 应用程序生命周期
应用程序进程从创建到结束的全过程便是应用程序的生命周期。与其他系统不同,Android应用程序的生命周期是不受进程自身控制的,而是由Android系统决定的。
Android系统将所有的进程分为5类进行管理:
1. 前台进程
2. 可见进程:还在屏幕中,但是用户并没有直接与之进行交互。
3. 服务进程
4. 后台进程
5. 空进程
从1到5,重要顺序递减。
注意:应用程序在运行时,其状态的切换可能是通过自身实现的,可也能是系统将其改变的。
2. Activity
Activity是Android中最常用的组件,是应用程序的表示层,Activity一般通过View来实现应用程序的用户界面,相当于一个屏幕,用户与程序的交互式通过该类实现的。
Activity的生命周期主要包含三个状态:运行态,暂停态,停止态。
Activity的显示内容跟是由View对象提供的,View对象继承自View类,其中每个View对象管理屏幕中的一个矩形区域。Android自带了许多View对象,而除了使用Android自带的View外,还可以自定义View。
例子:
Java代码 复制代码
  1. MyView.java:   
  2. package qijia.si;   
  3. import android.content.Context;   
  4. import android.graphics.Canvas;   
  5. import android.graphics.Color;   
  6. import android.graphics.Paint;   
  7. import android.view.View;   
  8.   
  9. public class MyView extends View {   
  10.     Paint paint;   
  11.     public MyView(Context context){   
  12.            
  13.         super(context);   
  14.         paint = new Paint();   
  15.         paint.setColor(Color.WHITE);   
  16.         paint.setTextSize(20);   
  17.         paint.setAntiAlias(true);   
  18.                
  19.     }   
  20.     protected void onDraw(Canvas canvas){   
  21.            
  22.         super.onDraw(canvas);   
  23.         canvas.drawColor(Color.GRAY);   
  24.         canvas.drawRect(10,10,110,110, paint);   
  25.         canvas.drawText("fuck you"60170, paint);   
  26.            
  27.            
  28.     }   
  29. }   
  30. MyAndroidProject.java:   
  31. package qijia.si;   
  32.   
  33. import android.app.Activity;   
  34. import android.os.Bundle;   
  35.   
  36. public class MyAndroidProject extends Activity {   
  37.     /** Called when the activity is first created. */  
  38.     MyView myView;   
  39.     @Override  
  40.     public void onCreate(Bundle savedInstanceState) {   
  41.         super.onCreate(savedInstanceState);   
  42.         myView = new MyView(this);   
  43.         this.setContentView(myView);   
  44.     }   
  45. }  
MyView.java:
package qijia.si;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.view.View;

public class MyView extends View {
	Paint paint;
	public MyView(Context context){
		
		super(context);
		paint = new Paint();
		paint.setColor(Color.WHITE);
		paint.setTextSize(20);
		paint.setAntiAlias(true);
			
	}
	protected void onDraw(Canvas canvas){
		
		super.onDraw(canvas);
		canvas.drawColor(Color.GRAY);
		canvas.drawRect(10,10,110,110, paint);
		canvas.drawText("fuck you", 60, 170, paint);
		
		
	}
}
MyAndroidProject.java:
package qijia.si;

import android.app.Activity;
import android.os.Bundle;

public class MyAndroidProject extends Activity {
    /** Called when the activity is first created. */
	MyView myView;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        myView = new MyView(this);
        this.setContentView(myView);
    }
}
3. Service
Service是一个具有较长的生命周期但是并没有用户界面的程序。
Service一般由Activity启动,但不依赖于Activity,Service有两种启动方式:
1. startService
当Activity调用startService方法启动Service时,会依次调用onCreate和onStart方法来启动Service。当结束时,调用onDestroy方法结束Service。
2. bindService

BoardReceiver
BoardReceiver为用户接收广播通知的组件,当系统或某个应用程序发送广播时,可以使用BoardReceiver组件来接收广播信息并作出相应的处理。
使用过程:
1. 将需要广播的消息封装到Intent中。
2. Context.sendBroadcast(),sendOrderedBroadcast(),sendStickyBroadcast()中的一种将Intent发送
3. 通过IntentFilter对象过滤所发送的实体Intent
4. 重写onReceive方法的BoardReceiver。

4. ContentProvider
ContentProvider是用来实现应用程序之间数据共享的类。
5. Intent和IntentFilter
1) Intent类简介
Intent是一种运行时绑定机制,在应用程序运行时连接两个不同的组件。一般的应用是通过Intent向Android系统发出某种请求,然后Android系统会根据请求查询各个组件声明的IntentFilter,找到需要的组件并运行它。
前面所说的Activity,Service及BroadcastReceiver组件之间的通信全部使用的是Intent但是每个机制不同。
Activity组件:当需要激活一个Activity组件时,需要调用Context.startActivity或Context.startActivityForResult方法来传递Intent,此时的Intent参数成为Activity Action Intent
Service组件:一般通过Context.startService和Context.bindService
BroadcastReceiver组件:上面已经介绍

Intent是由组件名称,Action,Data,Category,Extra和Flag组成:

1. 组件名称:组件名称实际上就是一个ComponentName对象,用于标识唯一的应用程序组件。
2. Action:一个描述Intent所触发动作名称的字符串。如
ACTION_CALL,ACTION_EDIT,ACTION_VIEW,ACTION_MAIN等
3. Data:主要对Intent消息中数据的封装,主要描述Intent的动作所操作到的数据的URI及类型
4. Category:是对目标组件类型的描述
5. Extra:封装了一些额外的附加信息。
2) IntentFilter
IntentFilter实际上相当于Intent的过滤器。IntentFilter过滤Intent时,主要通过Action,Data及Category三方面进行监测:
1. 检查Action:一个Intent只能设置一种Action,但是一个IntentFilter却可以设置多个Action过滤。当IntentFilter设置了多个Action时,只需一个满足就可完成Action验证。
2. 检查Data:主要检查URI及数据类型
3. 检查Category:当Intent中的Category与IntentFilter中的一个Category完全匹配时,便会通过Category检查。
Intent案例:
判断输入的电话号码是否符合规范当符合规范时,调用系统自带的拨号程序进行拨号。

Java代码 复制代码
  1. package qijia.si;   
  2.   
  3. import android.app.Activity;   
  4. import android.content.Intent;   
  5. import android.net.Uri;   
  6. import android.os.Bundle;   
  7. import android.telephony.PhoneNumberUtils;   
  8. import android.view.View;   
  9. import android.widget.Button;   
  10. import android.widget.EditText;   
  11. import android.widget.Toast;   
  12.   
  13. public class MyAndroidProject extends Activity {   
  14.     /** Called when the activity is first created. */  
  15.     @Override  
  16.     public void onCreate(Bundle savedInstanceState) {   
  17.         super.onCreate(savedInstanceState);      
  18.         setContentView(R.layout.main);   
  19.         Button bCall = (Button)this.findViewById(R.id.Button01);   
  20.         bCall.setOnClickListener(   
  21.                 new View.OnClickListener() {           
  22.                     public void onClick(View v) {   
  23.                         // TODO Auto-generated method stub   
  24.                         EditText eTel = (EditText) findViewById(R.id.myEditText);   
  25.                         String strTel = eTel.getText().toString();   
  26.                         if(PhoneNumberUtils.isGlobalPhoneNumber(strTel)){   
  27.                             Intent i = new Intent(Intent.ACTION_DIAL,Uri.parse("tel://"+strTel));   
  28.                             MyAndroidProject.this.startActivity(i);   
  29.                                
  30.                                
  31.                         }else{   
  32.                             Toast.makeText(   
  33.                                     MyAndroidProject.this,   
  34.                                     "号码格式不正确",   
  35.                                     5000  
  36.                                
  37.                             ).show();   
  38.                     }   
  39.                 }   
  40.                 }   
  41.                 );   
  42.                            
  43.            
  44.     }   
  45. }  
  • 0
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值