获取单击的项目

时间:2012-02-24 12:03:37

标签: java android

我几乎没有问题如何识别用OnClickEvent点击了哪个项目。我用图像+文本绘制gridview菜单。这是我的代码:

public class MyActivity extends Activity implements OnItemClickListener {

    GridView menu;
    private String[] menu_text = {
    "Menu1",
    "Menu2",
    "Menu3",
    "Menu4",
    "Menu5",
    "Menu6",
    "Menu7",
    "Menu8"};

    private Integer[] menu_icon = {
            R.drawable.icon,
            R.drawable.icon,
            R.drawable.icon,
            R.drawable.icon,
            R.drawable.icon,
            R.drawable.icon,
            R.drawable.icon,
            R.drawable.icon,};

    /** Called when the activity is first created. */

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);

        setContentView(R.layout.main);

        getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.window_title);    

        menu = (GridView)findViewById(R.id.Menu);
        menu.setOnItemClickListener(this);
        menu.setAdapter(new MenuItem(this, R.layout.menu_item, menu_text));

        }

    public class MenuItem extends ArrayAdapter {
        public MenuItem(Context context, int textViewResourceId, String[] objects) {
        super(context, textViewResourceId, objects);
        }

        public View getView(int position, View convertView, ViewGroup parent) {
            LayoutInflater inflater=getLayoutInflater();
            View row=inflater.inflate(R.layout.menu_item, parent, false);
            TextView tv=(TextView)row.findViewById(R.id.text);
            tv.setText(menu_text[position]);
            tv.setTextColor(Color.BLACK);
            tv.setCompoundDrawablesWithIntrinsicBounds(0, menu_icon[position], 0, 0);
            return row;
            }

    }

    public void onItemClick(AdapterView arg0, View arg1, int arg2, long arg3) {
    // TODO Action to perform


    }
    }

所以我的问题是如何识别在此网格菜单中单击了哪个项目。

3 个答案:

答案 0 :(得分:1)

arg2参数中的onItemClick int是数组中按下的项的位置。

所以

public void onItemClick(AdapterView arg0, View arg1, int arg2, long arg3) {
    // TODO Action to perform
    String selectedObject = objects[arg2]; //objects is the String array passed to the adapter.
}

答案 1 :(得分:0)

如果您阅读OnItemClickListener文档,您会发现在onItemClick方法中为您提供了一些参数:

  

parent发生点击的AdapterView   view已单击的AdapterView中的视图(这将是适配器提供的视图)
  position视图在适配器中的位置   id已单击的项的行ID。

位置将为您提供所点击项目的索引

答案 2 :(得分:-1)

您已在此次点击中覆盖了onItemClick方法,请查看arg1其正在点击的视图,第3参数arg2是gridview中项目的位置。