package com.example.test3;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.Toast;
public class MainActivity extends Activity {
Integer[] img = { R.drawable.pic1, R.drawable.pic2, R.drawable.pic3,
R.drawable.pic4, R.drawable.pic5, R.drawable.pic6 };
private ImageView imgView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imgView = (ImageView) findViewById(R.id.img);
GridView gird = (GridView) findViewById(R.id.gridView1);
gird.setAdapter(new ImageAdapter(this));
gird.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
imgView.setBackgroundResource(img[arg2]);
}
});
}
public class ImageAdapter extends BaseAdapter {
public Context context;
public ImageAdapter(Context context) {
this.context = context;
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return img.length;
}
@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ImageView imageView;
if (convertView == null) {
imageView = new ImageView(context);
imageView.setLayoutParams(new GridView.LayoutParams(85, 85));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(8,8, 8, 8);
} else {
imageView = (ImageView) convertView;
}
imageView.setImageResource(img[position]);
return imageView;
}
}
@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;
}
}
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#000044"
android:orientation="vertical" >
<GridView
android:id="@+id/gridView1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="top"
android:horizontalSpacing="10dp"
android:numColumns="2"
android:stretchMode="columnWidth"
android:verticalSpacing="10dp" >
</GridView>
<ImageView
android:id="@+id/img"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
</LinearLayout>