将网格布局图像制作成按钮,以便各自打开单独的活动

时间:2012-05-23 08:58:11

标签: android android-layout gridview

  

可能重复:
  Create a clickable image in a GridView in Android

我已经设置了一个网格布局,但是想让图像打开单独的活动,我的代码看起来像这样:

package android.grid.layout;

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扩展BaseAdapter {     private Context 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;

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

public class 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));

}   

}

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

1 个答案:

答案 0 :(得分: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;
}