你可以试试这个。
private void populateButtons() {
ArrayAdapter<String> chars = new ArrayAdapter<String>(context, android.R.layout.simple_list_item_1);
GridView layout = (GridView) findViewById(R.id.gridView);
for (char buttonChar = 'A'; buttonChar <= 'Z'; buttonChar++) {
String buttonText = String.valueOf(buttonChar);
chars.add(buttonText);
}
layout.setAdapter(chars);
}
如果您真的想插入按钮,请创建一个扩展类Adapter
,
ArrayAdapter
足够。
public class AlphabetButtonAdapter extends ArrayAdapter<String>
{
private List<String> objects;
public AlphabetButtonAdapter(Context context,
int textViewResourceId,
List<String> objects)
{
super(context, textViewResourceId, objects);
this.objects = objects;
}
@Override
public View getView(int position, View convertView, ViewGroup parent)
{
Button b = new Button(getContext());
b.setText(objects.get(position));
return b;
}
public void setOnClickListener(OnClickListener listener)
{
this.listener = listener;
}
}
使用自定义适配器填充
private void populateButtons() {
ArrayList<String> list = new ArrayList<String>();
GridView layout = (GridView) findViewById(R.id.gridView);
for (char buttonChar = 'A'; buttonChar <= 'Z'; buttonChar++) {
String buttonText = String.valueOf(buttonChar);
list.add(buttonText);
}
AlphabetButtonAdapter chars = new AlphabetButtonAdapter(context, 0, list);
layout.setAdapter(chars);
}
更新1:绑定onClick()
按钮
您可以传入OnClickListener
只需AlphabetButtonAdapter
添加一个 setter 方法
public class MyActivity OnClickListener
{
@Override
public void onClick(View v)
{
Button b = (Button) v;
// Your definition...
}
}
private void populateButtons() {
ArrayList<String> list = new ArrayList<String>();
GridView layout = (GridView) findViewById(R.id.gridView);
for (char buttonChar = 'A'; buttonChar <= 'Z'; buttonChar++) {
String buttonText = String.valueOf(buttonChar);
list.add(buttonText);
}
AlphabetButtonAdapter chars = new AlphabetButtonAdapter(context, 0, list);
chars.setOnClickListener(listener);
layout.setAdapter(chars);
}