2

我不确定标题是否可以,但我会尝试更好地解释它。

我想在我的布局中显示一个网格。为此,我正在使用自定义 ArrayAdapter。我不知道如何将 onClickListener 设置为每个项目......

布局包含一个用于显示名称的标签和一个网格视图。

这是我的活动:

public class Sala extends Activity{
GridView gridView;
TextView label_name;

ArrayList<String> lista_opciones = new ArrayList<String>();  

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.layout_sala);
    //Refresh the name in the label
    Bundle bundle=getIntent().getExtras();
    String name= bundle.getString("name");
    label_name= (TextView) findViewById(R.id.label_name);
    label_name.setText(name);

    //Loading array
    lista_op.add("Op 1");  
    lista_op.add("Op 2");  
    lista_op.add("Op 3");  
    lista_op.add("Op 4"); 

    //AdaptadorOpciones
    ArrayAdapterOpciones mAdapter = new ArrayAdapterOptions(this,lista_op);  

    //Set the customAdapter to the grid
    gridView = (GridView) findViewById(R.id.grid); 
    gridView.setAdapter(mAdapter);  
}

}

我应该重写女巫方法以在每个项目中实现 onClickListener 吗?

4

2 回答 2

4

为 gridview 项目点击实现 setOnItemClickListener:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.layout_sala);
    //Refresh the name in the label
    Bundle bundle=getIntent().getExtras();
    String name= bundle.getString("name");
    label_name= (TextView) findViewById(R.id.label_name);
    label_name.setText(name);

    //Loading array
    lista_op.add("Op 1");  
    lista_op.add("Op 2");  
    lista_op.add("Op 3");  
    lista_op.add("Op 4"); 

    //AdaptadorOpciones
    ArrayAdapterOpciones mAdapter = new ArrayAdapterOptions(this,lista_op);  

    //Set the customAdapter to the grid
    gridView = (GridView) findViewById(R.id.grid); 
    gridView.setAdapter(mAdapter);  
    gridView.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View v, int position, long id) {

                //Do stuff here
            }
        });
}
于 2012-04-25T01:25:13.350 回答
0

您可以在 Adapter.getView 实现中添加侦听器:

    @Override       
    public View getView(int position, View convertView, ViewGroup parent) {
        ImageView button = (ImageView) convertView;
        if (button == null) {
            button = new ImageButton(); // or whatever
            button.setOnClickListener(this);
        }
        button.setId(ids_present.get(position));
        return button;
    }
于 2012-04-25T01:25:48.153 回答