触发Onitemclick网格视图

时间:2012-02-26 22:26:37

标签: android

我有一个使用onitemclickListener设置的网格视图但是当我点击某个项目时它无法正常工作可以请任何人帮助我实现这一目标

主要活动

public class BahashActivity extends Activity implements OnItemClickListener{
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    GridView grid = (GridView) findViewById(R.id.grid);
    grid.setAdapter(new ImageAdapter(this));
}


    public void onItemClick(AdapterView<?> parent, View v, int position,
            long id) {

        if(position == 0){
            Intent i = new Intent(BahashActivity.this, Age.class);
            BahashActivity.this.startActivity(i);

        }


    }


}

ImageAdapter

package your.age.namespace;

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扩展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 };

}

2 个答案:

答案 0 :(得分:2)

你有电话吗?

gridView.setOnItemClickListener(this);

答案 1 :(得分:0)

这没用。我不知道为什么,但是当你实现接口,然后调用 “gridView.setOnItemClickListener(this);”,这不起作用。'

这样做的方法是:

gridView.setOnItemClickListener( new OnItemClickListener(){

            public void onItemClick(AdapterView<?> adapter, View view, int position, long arg3) {

                Toast.makeText(getBaseContext(), "Proving", Toast.LENGTH_SHORT).show();


        }

    });

我相信,这样可以正常使用。