Android 减少按钮单击事件的代码

Android 减少按钮单击事件的代码,android,Android,我的问题有三个部分 我的布局由26个按钮组成:ButtonA、ButtonB、ButtonC…ButtonZ 按钮在屏幕上按顺序排列。单击按钮时,我希望捕获单击事件,并根据单击的第一个字母过滤SQLiteDB中的单词 如何编写捕获点击的最小代码量,识别按钮的对应字母,并从SQLite数据库返回以所选字母开头的字母 下面是我的代码,它还没有为代码简洁而优化 //Create your buttons and set their onClickListener to "this" Butto

我的问题有三个部分

我的布局由26个按钮组成:ButtonA、ButtonB、ButtonC…ButtonZ

按钮在屏幕上按顺序排列。单击按钮时,我希望捕获单击事件,并根据单击的第一个字母过滤SQLiteDB中的单词

如何编写捕获点击的最小代码量,识别按钮的对应字母,并从SQLite数据库返回以所选字母开头的字母

下面是我的代码,它还没有为代码简洁而优化

//Create your buttons and set their onClickListener to "this"
    Button b1 = (Button) findViewById(R.id.Button04);   
    b1.setOnClickListener(this);

    Button b2 = (Button) findViewById(R.id.Button03);   
    b2.setOnClickListener(this);


     //implement the onClick method here
public void onClick(View v) {
   // Perform action on click
  switch(v.getId()) {
    case R.id.Button04:
        //Toast.makeText(this,"test a",Toast.LENGTH_LONG).show();

     // Do the SqlSelect and Listview statement for words that begin with "A" or "a" here.

       break;
    case R.id.Button03:
        //Toast.makeText(this,"test b",Toast.LENGTH_LONG).show();

 // Do the SqlSelect and Listview statement for words that begin with "A" or "a" here.
      break;
  }

}

如果您的布局是用XML定义的,您可能希望对按钮使用
android:onClick
参数。通过这种方式,您可以保存
findViewById()
setOnClickListener()
调用。

如果您有很多字符和每个字符的按钮,我可能会扩展“BaseAdapter”类并制作一个按钮适配器,将字母表作为字符数组保存,而不是实际制作28:ish按钮。。。如果我正确理解了这个问题

getView的外观可能如下所示:

  public View getView(int position, View convertView, ViewGroup parent) {
    Button button;

    if (convertView == null) {
        button = new Button(mContext);
        button.setTag(alphabet[position]);
        button.setOnClickListener(clickListener);
    } else {
        button = (Button) convertView;
    }

    button.setText(alphabet[position]);
    return button;
  }

正如alextsc所说,如果希望减少活动中的代码,可以从XML绑定click侦听器。然而,考虑到按钮的性质,我认为最好在循环中的代码中定义按钮。只需在布局中制作一个简单的容器(例如线性布局)并添加按钮即可。我们可以利用这样一个事实,即您可以循环使用字符(将其视为整数):


感谢Anton、Alex和Marko,我使用了“onClick”作为xml的一部分,并使用了“public void onClick(View v)”代码。这真的使一项活动大为改观。再次感谢你的指点,穆乔很感激
for (char letter = 'a'; letter <= 'z'; letter++) {
    Button button = new Button(this);
    button.setText(String.valueOf(letter));
    button.setOnClickListener(this);
    container.addView(button);
}
public void onClick(View v) {
        Button button = (Button) v;
        String letter = button.getText().toString();
        // filter using letter
}