Android基本控件示例GridView(05)

//主页面主要代码:
// 选择图片按钮事件
public void choose(View view) {
		Intent intent = new Intent(this, NextActivity.class);
		startActivityForResult(intent, REQUESTCODE);
		// 跳转下一页的请求码REQUESTCODE=100,用带回数据的跳转,重写onActivityResult()方法
	}

// 数据返回后将图片显示在imageView
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == REQUESTCODE && resultCode == 101) {
                                    // 判断请求码和结果码是否相同,便是否是对应的Intent
			Bundle bundle = data.getExtras();
			int headerid = bundle.getInt("headerId");
			// headerId注意这里获取的键要与传过来的键值对应,不然会出错
			imageView.setImageResource(headerid);
			setTitle(getResources().getText(headerid));// 在头部显示资源路径名
		}

	}

//第二个Activity的代码
public class NextActivity extends Activity {
	private GridView gridView;
	private SimpleAdapter adapter;
	// 图片数组
	private int[] image = { R.drawable.img01, R.drawable.img02,
			R.drawable.img03, R.drawable.img04, R.drawable.img05,
			R.drawable.img06, R.drawable.img07, R.drawable.img08,
			R.drawable.img09 };

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.girdview_activity);
		gridView = (GridView) this.findViewById(R.id.gridview);
		List<Map<String, Object>> data = new ArrayList<Map<String, Object>>();
		for (int i = 0; i < image.length; i++) {
			Map<String, Object> itemMap = new HashMap<String, Object>();
			itemMap.put("header", image[i]);
			data.add(itemMap);
		}
		adapter = new SimpleAdapter(this, data, R.layout.girdview_item,
				new String[] { "header" }, new int[] { R.id.item_imageview });
		gridView.setAdapter(adapter);
		// 点击选择图片监听
		gridView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				int headerId = image[position];
				// 获取intent,并返回给主页面数据
				Intent intent = getIntent();
				Bundle bundle = new Bundle();
				bundle.putInt("headerId", headerId);
				intent.putExtras(bundle);
				setResult(101, intent);
				finish();// 关闭该Activity

			}
		});
	}
}

//主页面布局:    
<ImageView
        android:id="@+id/imageview"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="" />
    <Button
        android:id="@+id/choose"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="选择头像" 
        android:onClick="choose"
        android:layout_below="@+id/imageview"
        />
//第二个页面布局
    <GridView
        android:id="@+id/gridview"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:numColumns="3"
       />

//SimpleAdapter适配器自定义布局
    <ImageView
        android:id="@+id/item_imageview"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
       />
相关文章
相关标签/搜索