通讯录开发学习5

主要是实现对用户列表添加后,返回到主界面

 主要是实现对用户列表添加后,返回到主界面

先在MainActivity类里重写下面的方法

protected void onActivityResult(int requestCode,int resultCode, Intent data) {}以及修改了AddNewActivity.java的onCreate 的click方法里增添下面方法

因此在这里依然覆盖前面写的关于MainActivity.java和AddNewActivity.java两个类

一些注释在程序里有说明

1、MainActivity.java

package test.contact;

import java.util.ArrayList;
import java.util.HashMap;

import test.contact.db.DBHelper;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.ListView;
import android.widget.SimpleAdapter;

public class MainActivity extends Activity {
	
	GridView gv_button_menu;
	
	ListView lv_userList;//用户列表
	SimpleAdapter adapter;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		this.setContentView(R.layout.main);
		loadUserList();
	}
	
	private void loadUserList(){
		lv_userList = (ListView)this.findViewById(R.id.lv_userlist);
		
		ArrayList data = DBHelper.getInstance(this).getUserList();//这个方法在DBHelper里
            adapter = new SimpleAdapter(this, 
										data, R.layout.list_item, 
										new String[]{"imageId","name","mobilePhone"}, 
										new int[]{R.id.user_image,R.id.tv_showname,R.id.tv_showmobilephone});
		lv_userList.setAdapter(adapter);
	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if(keyCode==KeyEvent.KEYCODE_MENU){
			//
			if(gv_button_menu==null){
				loadButtonMenu();
			}
			if(gv_button_menu.getVisibility()==View.GONE){
				gv_button_menu.setVisibility(View.VISIBLE);
			} else {
				gv_button_menu.setVisibility(View.GONE);
			}
		}
		return super.onKeyDown(keyCode, event);
	}
	
	//加载底部的菜单(gridView)
	@SuppressWarnings("unchecked")
	private void loadButtonMenu(){
		gv_button_menu =(GridView) this.findViewById(R.id.gv_button_menu);
		gv_button_menu.setBackgroundResource(R.drawable.menu_background);
		gv_button_menu.setNumColumns(5);//设置有多少列
		gv_button_menu.setGravity(Gravity.CENTER);//设置位置 居中
		gv_button_menu.setVerticalSpacing(100);//设置水平间隔
		gv_button_menu.setHorizontalSpacing(10);//设置垂直间隔
		
		ArrayList data = new ArrayList();
		
		//是gridview里的图片和底部的字 ,这些是构造data
		HashMap map = new HashMap();
		map.put("itemImage", R.drawable.menu_new);
		map.put("itemText", "增加");
		data.add(map);
		
		map = new HashMap();
		map.put("itemImage", R.drawable.menu_search);
		map.put("itemText", "查找");
		data.add(map);

		map = new HashMap();
		map.put("itemImage", R.drawable.menu_delete);
		map.put("itemText", "删除");
		data.add(map);
		
		map = new HashMap();
		map.put("itemImage", R.drawable.controlbar_showtype_list);
		map.put("itemText", "菜单");
		data.add(map);
		
		map = new HashMap();
		map.put("itemImage", R.drawable.menu_exit);
		map.put("itemText", "退出");
		data.add(map);
		
		//创建Adapter
	SimpleAdapter adapter = 
new SimpleAdapter(this,data, R.layout.item_menu,new String[]{"itemImage","itemText"},new int[]{R.id.item_image,R.id.item_text});
			//SimpleAdapter的参数有(context,listmapdata,resource,from,to),其中resource是布局,即item_menu.xml
	//data中的map都将布局(resources)通过后面对应的两个联系起来 
		
		gv_button_menu.setAdapter(adapter);
		//gridview只能展示,是个视图,而适配器就是将数据和展现方式联系起来的方式
		
		gv_button_menu.setOnItemClickListener(new OnItemClickListener(){

			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position,
					long id) {
				//第一个参数代笔所有数据
				//HashMap map = (HashMap)parent.getItemAtPosition(1);
				//postition是指弹出的那个ItemMenu里的项(如增加,查找,删除,菜单,退出等5个)
				switch(position){
				case 0:{
					Intent intent = new Intent(MainActivity.this,AddNewActivity.class);
					//0代表请求跳转到添加界面(AddNewActivity)
					startActivityForResult(intent,0);
					break;
				}
				case 1:{
					break;
				}
				case 2:{
					break;
				}
				case 3:{
					break;
				}
				case 4:{
					break;
				}
				}
			}
			
		});
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		//resultCode表示跳转码
		if(resultCode==0){
			if(resultCode==1){
				//增加用户成功 进行刷新
				ArrayList userData = DBHelper.getInstance(this).getUserList();//这个方法在DBHelper里
	            adapter = new SimpleAdapter(this, 
											userData, R.layout.list_item, 
											new String[]{"imageId","name","mobilePhone"}, 
											new int[]{R.id.user_image,R.id.tv_showname,R.id.tv_showmobilephone});
	            	lv_userList.setAdapter(adapter);
				
			} else  if(resultCode==2){
				//增加用户失败, 不进行刷新
			}
		}
		super.onActivityResult(requestCode, resultCode, data);
	}
	
	
}


2、AddNewActivity.java

package test.contact;
import test.contact.db.DBHelper;
import test.contact.entity.User;//引入user的包

import test.contact.entity.User;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Gallery;
import android.widget.ImageButton;
import android.widget.ImageSwitcher;
import android.widget.ImageView;
import android.widget.Toast;
import android.widget.ViewSwitcher.ViewFactory;


public class AddNewActivity extends Activity {
	ImageButton btn_img;
	AlertDialog imageChooseDialog;
	Gallery gallery;
	ImageSwitcher is;
	int imagePosition;//在图片选择中确定按钮是提交的图片的id,如果默认的话,值为0
	
	//增加联系人信息的这个界面里的那些编辑框
	EditText et_name;
	EditText et_mobliePhone;
	EditText et_familyPhone;
	EditText et_officePhone;
	EditText et_position;
	EditText et_company;
	EditText et_address;
	EditText et_zipCode;
	EditText et_email;
	EditText et_otherContact;
	EditText et_remark;
	
	Button btn_save;
	Button btn_return;
	
	private int[] images={
						  R.drawable.icon,
						  R.drawable.image1,R.drawable.image2,
						  R.drawable.image3,R.drawable.image4,
			              R.drawable.image5,R.drawable.image6,
			              R.drawable.image7,R.drawable.image8,
			              R.drawable.image9,R.drawable.image10};
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.addnew);
        
        initWidget();//初始化这个界面里的EditText和两个Button
           
        //响应"保存"按钮事件
        btn_save = (Button)this.findViewById(R.id.btn_save);
        btn_save.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				String name = et_name.getText().toString();
				if(name.equals("")){
					Toast.makeText(AddNewActivity.this, "姓名不能为空", Toast.LENGTH_LONG).show();
					return;
					}
				String mobilePhone = et_mobliePhone.getText().toString();
				String officePhone = et_officePhone.getText().toString();
				String familyPhone = et_familyPhone.getText().toString();
				String position = et_position.getText().toString();
				String company = et_company.getText().toString();
				String address = et_address.getText().toString();
				String email = et_email.getText().toString();
				String zipCode = et_zipCode.getText().toString();
				String otherContact = et_otherContact.getText().toString();
				String remark = et_remark.getText().toString();
				//如果没有给Image赋图像,那么imageId默认为0,
				//所以在上面的Image里的第一个是icon,作为默认的那个图片
				int imageId = images[imagePosition];
				
				//联系人
				User user = new User();
				user.address = address;
				user.company = company;
				user.email = email;
				user.familyPhone = familyPhone;
				user.imageId = imageId;
				user.mobilePhone = mobilePhone;
				user.otherContact = otherContact;
				user.name = name;
				user.officePhone = officePhone;
				user.position = position;
				user.remark = remark;
				user.zipCode = zipCode;
				
				//保存用户信息到数据库,执行后就到了DBHelper里的save方法了
				//如果保存成功就发出提示信息
				long success = DBHelper.getInstance(AddNewActivity.this).save(user);
				if(success!=-1){
					Toast.makeText(AddNewActivity.this, "添加成功!", Toast.LENGTH_LONG);
					//resultCode为1时表示增加用户成功,返回到主界面
					setResult(1);
					finish();
				} else {
					Toast.makeText(AddNewActivity.this, "添加失败,请重新操作!", Toast.LENGTH_SHORT);
					//resultCode为1时表示增加用户失败
					setResult(2);
					finish();
				}
				
			}
        	
        });
        
        //实现的主要是修改Image按钮里的东西
    	btn_img=(ImageButton)this.findViewById(R.id.btn_img);
		btn_img.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				initImageChooseDialog(); //当点击选择图片(即名字旁边的图片按钮时的方法)
				imageChooseDialog.show();
			}
			
		});
    }
    
    //写个方法将这个界面的编辑框和保存取消等控件都初始化
    public void initWidget(){
    	et_name=(EditText)this.findViewById(R.id.et_name);
    	et_mobliePhone=(EditText)this.findViewById(R.id.et_mobilephone);
    	et_familyPhone=(EditText)this.findViewById(R.id.et_familyphone);
    	et_officePhone=(EditText)this.findViewById(R.id.et_officephone);
    	et_position=(EditText)this.findViewById(R.id.et_position);
    	et_company=(EditText)this.findViewById(R.id.et_company);
    	et_address=(EditText)this.findViewById(R.id.et_address);
    	et_zipCode=(EditText)this.findViewById(R.id.et_zipcode);
    	et_email=(EditText)this.findViewById(R.id.et_email);
    	et_otherContact=(EditText)this.findViewById(R.id.et_other);
    	et_remark=(EditText)this.findViewById(R.id.et_remark);
    }
    
    private void initImageChooseDialog(){
    	AlertDialog.Builder builder = new AlertDialog.Builder(this);
    	builder.setTitle("请选择图像");
    	
    	//添加选择和取消图片的按钮
    	builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				btn_img.setImageResource(images[imagePosition]);//在选中一张图片后,获得这个图片的id,才能选中它了
				
			}
		});
    	
    	builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				
			}
		});
    	LayoutInflater inflater = LayoutInflater.from(this);
    	View view = inflater.inflate(R.layout.imageswitch, null);
    	//1、Gallery的东西需要显示出来,
    	 gallery = (Gallery) view.findViewById(R.id.img_gallery); 
    	gallery.setAdapter(new ImageAdapter(this));
    	gallery.setSelection(images.length/2);//定位中中间的图片
    	
    	
    	//2、Switcher方面,选中图片 
    	 is=(ImageSwitcher) view.findViewById(R.id.image_switcher);
       	is.setFactory(new MyViewFactory(this));
       	
      //1.1 Gallery的响应事件 
       	gallery.setOnItemSelectedListener(new OnItemSelectedListener(){

			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int position, long arg3) {
				// TODO Auto-generated method stub
				imagePosition = position;
				is.setImageResource(images[position%images.length]);//取余
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub
				
			}
    		
    	});  
    	builder.setView(view);
    	imageChooseDialog = builder.create();
    }
    //Gallery的Adapter,实现BaseAdapter内部类
    class ImageAdapter extends BaseAdapter{
    	private Context context;
    	public ImageAdapter(Context context){
    		this.context=context;
    	}
		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			//return images.length;
			//实现在imageswitch.xml即那个弹出来要早增加图片的界面,其中的图片让其循环出现
			return Integer.MAX_VALUE;//使得它返回一个比较大的值
		}

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

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

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			ImageView iv = new ImageView(context);
			iv.setImageResource(images[position%images.length]);
			iv.setAdjustViewBounds(true);//设置适应视图的大小
			iv.setLayoutParams(new Gallery.LayoutParams(80,80));//设置其大小
			//设置图片之间的间隔
			iv.setPadding(15, 10, 15, 10);
			return iv;
		}
    	
    }
    
    //Switcher的Factory,实现ViewFactory的内部类
    class MyViewFactory implements ViewFactory{
    	private Context context;//需要的上下文
    	public MyViewFactory(Context context){
    		this.context=context;
    	}
		@Override
		public View makeView() {
			// TODO Auto-generated method stub
			ImageView iv = new ImageView(context);
			iv.setLayoutParams(new ImageSwitcher.LayoutParams(90,90));
			
			return iv;
		}
    	
    }
}


这样在增加联系人信息后可以跳转到主页面

3、关于要实现imageswitcer.xml里的界面,即更换图片处可以循环显示图片,只要修改两处(小技巧)

一个是将AddNewActivity.java里的getCount()方法 return MAX_VALUE;

此外,在images[position],处,把postition修改为:position%images.length;即可

在本项目中是,

public View getView(int position, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			ImageView iv = new ImageView(context);
			iv.setImageResource(images[position%images.length]);
			iv.setAdjustViewBounds(true);//设置适应视图的大小
			iv.setLayoutParams(new Gallery.LayoutParams(80,80));//设置其大小
			//设置图片之间的间隔
			iv.setPadding(15, 10, 15, 10);
			return iv;
		}


 

//1.1 Gallery的响应事件 
       	gallery.setOnItemSelectedListener(new OnItemSelectedListener(){

			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int position, long arg3) {
				// TODO Auto-generated method stub
				imagePosition = position;
				is.setImageResource(images[position%images.length]);//取余
			}


     
没修改之前的效果是:

 

修改后的效果是:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值