网格视图在图像上启动新活动单击

时间:2012-02-26 00:26:24

标签: android gridview

我是一名新程序员,我需要一种方法来在网格视图中单击图像时启动新活动。我尝试过的一切都行不通。你有什么想法?我需要每个图像加载不同的活动。我有网格工作但只是需要它来改变活动。

Java文件:

package your.pacage.names;

import android.content.Context;
import android.content.Intent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.Toast;


public class ImageAdapter extends BaseAdapter {
private Context mContext;

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

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

public Object getItem(int position) {
    return null;
}

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

// create a new ImageView for each item referenced by the Adapter
public View getView(int position, View convertView, ViewGroup parent) {
    ImageView imageView;
    if (convertView == null) { // if it's not recycled, initialize some
                                // attributes
        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;
}

// references to our images
private Integer[] mThumbIds = { R.drawable.ic_launcher,
        R.drawable.ic_launcher, R.drawable.ic_launcher,
        R.drawable.ic_launcher, R.drawable.ic_launcher,
        R.drawable.ic_launcher };
}

1 个答案:

答案 0 :(得分:6)

在给定的代码中,您没有在单个imageViews上设置任何类型的onItemClickListener(在网格上)或View.OnClickListener ...当您按下其中一个时,您需要执行其中一个操作网格视图项。

从活动开始新活动:startActivity(new Intent(YourActivity.this,TargetActivity.class))

在onCreate中共同执行以下操作:

GridView yourGridView = (GridView) findViewById(R.id.your_grid_view_id);
yourGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int position, long l){
        Class targetActivity = getTargetActivityForPosition(position);
        YourActivity.this.startActivity(new Intent(YourActivity.this, TargetActivity.class));
    }
}