你可以試試這個。
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);
}
使用''GridView''沒有''RelativeLayout'' – 2013-01-02 06:43:25
我怎樣才能插入網格內的按鈕? – newbie
您也可以使用Gridview或TableLayout來做到這一點。 – itsrajesh4uguys