GridView网格视图
1、在main.xml 建立进入另一个Activity的grid_view_button
<Button android:id="@+id/grid_view_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="GridView"/>
2、在MainActivity.java里
Button grid_view_button=(Button)findViewById(R.id.grid_view_button);
grid_view_button.setOnClickListener(grid_view_button_listener);
相应的监听事件:
private Button.OnClickListener grid_view_button_listener = new OnClickListener(){
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent();
intent.setClass(MainActivity.this, GridViewActivity.class);
startActivity(intent);
}
};
3、在res的layout里新建一个grid_view.xml
<GridView android:id="@+id/grid_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="GridView"/>
4、新建一个GridViewActivity.java的类
package zeng.Demo;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import zeng.Demo.ImageAdapter;
public class GridViewActivity extends Activity{
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.grid_view);
setTitle("GridViewActivity");
GridView gridview =(GridView)findViewById(R.id.grid_view);
gridview.setAdapter(new ImageAdapter(this));
}
}
5、需要新建一个上面对应的ImageAdapter的类
package zeng.Demo;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
public class ImageAdapter extends BaseAdapter{
private Context mContext;
public ImageAdapter(Context c){
mContext = c;
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return mThumbIds.length;
}
@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 imageView;
if(convertView == null){
imageView = new ImageView(mContext);
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(mThumbIds[position]);
return imageView;
}
private Integer[] mThumbIds = {
R.drawable.grid_view_01,R.drawable.grid_view_02,
R.drawable.grid_view_03,R.drawable.grid_view_04,
R.drawable.grid_view_05,R.drawable.grid_view_06,
R.drawable.grid_view_07,R.drawable.grid_view_08,
R.drawable.grid_view_09,R.drawable.grid_view_10
};
}
鉴于上面需要图片,因此在Res里新建了一个drawable的文件夹,同时贴入了许多图片