0

可能重复:
在 Android 的 GridView 中创建可点击的图像

我已经设置了一个网格布局,但想让图像打开单独的活动,我的代码如下所示:

package android.grid.layout;

导入android.content.Context;导入android.view.View;导入android.view.ViewGroup;导入 android.widget.BaseAdapter;导入android.widget.GridView;导入android.widget.ImageView;

公共类 ImageAdapter 扩展 BaseAdapter { 私有上下文 mContext;

// Keep all Images in array
public Integer[] mThumbIds = {
        R.drawable.group_off, R.drawable.indoor_off, R.drawable.outdoors_off,
        R.drawable.attractions_off, R.drawable.playcentre_off, R.drawable.animals_nature_off,
        R.drawable.entertainment_off, R.drawable.arts_off, R.drawable.educational_off, 
        R.drawable.museum_off, R.drawable.historical_off, R.drawable.exercise_off,
        R.drawable.swimming_off, R.drawable.restaurant_off, R.drawable.partyhat_off
};

// Constructor
public ImageAdapter(Context c){
    mContext = c;
}

@Override
public int getCount() {
    return mThumbIds.length;
}

@Override
public Object getItem(int position) {
    return mThumbIds[position];
}

@Override
public long getItemId(int position) {
    return 0;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    ImageView imageView = new ImageView(mContext);
    imageView.setImageResource(mThumbIds[position]);
    imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
    imageView.setLayoutParams(new GridView.LayoutParams(70, 70));
    return imageView;
}

}

读取它的类看起来像这样

package android.grid.layout;

导入android.app.Activity;导入android.content.Intent;导入android.os.Bundle;导入android.view.View;导入 android.widget.AdapterView;导入 android.widget.AdapterView.OnItemClickListener;导入android.widget.GridView;

公共类 HomeActivity 扩展 Activity {

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.grid_layout);

    GridView gridView = (GridView) findViewById(R.id.grid_view);

    // Instance of ImageAdapter Class
    gridView.setAdapter(new ImageAdapter(this));

}   

}

我如何让每个人都可以点击打开一个新的单独活动以在其中包含自定义列表?

4

1 回答 1

0

在 Adpater 的 GetView 中添加一个点击监听器,

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    ImageView imageView = new ImageView(mContext);
    imageView.setImageResource(mThumbIds[position]);
    imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
    imageView.setLayoutParams(new GridView.LayoutParams(70, 70));
   imageView.setOnClickListener(new View.OnClickListener() {

  @Override
  public void onClick(View view) {
   Intent i=new Intent(context,activity.class);
     startActivity(i);
  }

});

    return imageView;
}
于 2012-05-23T09:13:50.097 回答