在动态网格视图中添加一个动态按钮?

时间:2014-01-20 07:29:26

标签: android button gridview

我最初的做法 - 我正在创建一些按钮,让我们在运行时说5个按钮。 我将它们存储在矢量中。

我需要在动态网格中添加这些按钮。我在xml中添加了动态按钮。 我将向量按钮传递给适配器类。 但我无法弄清楚如何将该按钮添加到gridview。

这是我的适配器类

   public class GridAdapter extends BaseAdapter {
    Vector<LinkButton> gridButton;

    public GridAdapter() {
        gridButton = null;
    }

    public GridAdapter(Vector<LinkButton> gg) {
        Log.e("view   ", "grid");
        gridButton = gg;
    }

    @Override
    public int getCount() {
        // TODO Auto-generated method stub
        return gridButton.size();
    }

    @Override
    public Object getItem(int position) {
        // TODO Auto-generated method stub
        return return gridButton.get(position);
    }

    @Override
    public long getItemId(int position) {
        // TODO Auto-generated method stub
        return;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // TODO Auto-generated method stub

        LayoutInflater inflater = getLayoutInflater();
        View row;
        row = inflater.inflate(R.layout.grid_element, parent, false);
        LinkButton lb = gridButton.get(position);

        Log.e("viewGrid   ", ""+gridButton.get(position));
        ((ViewGroup) row).addView(lb);

        return row;
    }

}

这就是我调用构造函数的方式

  GridView g = new GridView(this);
        g.setLayoutParams(new LinearLayout.LayoutParams(
                android.widget.LinearLayout.LayoutParams.WRAP_CONTENT,
                android.widget.LinearLayout.LayoutParams.WRAP_CONTENT));
        g.setNumColumns(2);
        g.setAdapter(new GridAdapter(homeButtons));

1 个答案:

答案 0 :(得分:0)

使用以下代码:

 @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // TODO Auto-generated method stub
        LayoutInflater inflater = getLayoutInflater();
        View row;
        row = inflater.inflate(R.layout.grid_element, parent, false);  //xml layout which contains the dynamic button element
        LinkButton lb   = gridButton.get(position);
        LayoutParams lp = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
        ((ViewGroup) row).addView(lb , lp);            

        return row;
    }