layout中activity_main.xml中包含ImageButton和EditText,picgallery.xml中包含gallery组件
其中将ImageButton设置android:onClick="picChooseFF"
ImageAdapter.java中:
public class ImageAdapter extends BaseAdapter {
private Context context;
//存储可供选择的图片
public static Integer[] images = { R.drawable.a,
R.drawable.b, R.drawable.c, R.drawable.d,R.drawable.e};
int mGalleryItemBackground;
public ImageAdapter(Context context) {
this.context=context;
}
@Override
public int getCount() {
return images.length;
}
@Override
public Object getItem(int position) {
return images[position];
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView=new ImageView(context);//利用ImageView来显示图片
imageView.setImageResource(images[position]);
imageView.setBackgroundResource(mGalleryItemBackground);
imageView.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
imageView.setAdjustViewBounds(true);
return imageView;
}
}
MainActivity.java中:
public class MainActivity extends Activity {
Gallery gallery;
static int num;
private ImageButton imageButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void picChooseFF(View view)
{
imageButton = (ImageButton)this.findViewById(R.id.picChoose);
AlertDialog.Builder alertDialog=new AlertDialog.Builder(this);//使用AlertDialog.Builder创建对话框
alertDialog.setTitle("请选择头像:");//标题
//在Activity里面就使用了LayoutInflater来载入界面, 通过inflate方法载入xml
LayoutInflater layoutInflater=getLayoutInflater();
View view1=layoutInflater.inflate(R.layout.picgallery, null);
alertDialog.setView(view1);
//显示gallery
gallery=(Gallery) view1.findViewById(R.id.gallery1);
ImageAdapter imageAdapter=new ImageAdapter(this);
gallery.setAdapter(imageAdapter);
gallery.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adpterView, View view, int position,
long id) {
num=position;
}
});
alertDialog.setPositiveButton("确定", new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
imageButton.setImageResource(ImageAdapter.images[num]);
removeDialog(0);
}
});
alertDialog.setNegativeButton("取消",new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
removeDialog(0);
}
});
alertDialog.create().show();
}
}