How to add view to gridview programmatically, android?

风格不统一 提交于 2019-12-10 16:15:24

问题


I have created a gridview of 2 coloumns. I need to have a button and a textview which are created dynamically at runtime in each column. I am unable write its baseadapter class. How should i inflate my view in the gridview.

This is my adapter class

    public class Adapter extends BaseAdapter {
    Context con;
    Integer[] m;

    public Adapter(Context c) {
        con = c;
    }

    public Adapter(Integer[] x) {
        m = x;
    }

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

    @Override
    public Object getItem(int position) {
        // TODO Auto-generated method stub
        return m[position];
    }

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

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // TODO Auto-generated method stub
        Button btn = new Button(con);
        TextView textview =new TextView(con);


        return null;
    }

}

回答1:


You can do something like:

public class Adapter extends BaseAdapter {
Context con;
Integer[] m;

public Adapter(Context c, Integer[] x) {
    con = c;
    m = x;
}



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

@Override
public Object getItem(int position) {
    // TODO Auto-generated method stub
    return m[position];
}

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

@Override
public View getView(int position, View convertView, ViewGroup parent) {
   LinearLayout layout = new LinearLayout(mContext);
    layout.setLayoutParams(new GridView.LayoutParams(
            android.view.ViewGroup.LayoutParams.FILL_PARENT,
            android.view.ViewGroup.LayoutParams.FILL_PARENT));
    layout.setOrientation(LinearLayout.HORIZONTAL);

    Button btn = new Button(mContext);
    btn.setLayoutParams(new LinearLayout.LayoutParams(
            android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
            android.view.ViewGroup.LayoutParams.WRAP_CONTENT));
    btn.setText("Btn " + position);

    TextView textview = new TextView(mContext);
    textview.setLayoutParams(new LinearLayout.LayoutParams(
            android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
            android.view.ViewGroup.LayoutParams.WRAP_CONTENT));
    textview.setText("TV " + position);
    textview.setTextColor(Color.RED);

    layout.addView(textview);
    layout.addView(btn);

    return layout;
}

}

It will work:)



来源:https://stackoverflow.com/questions/21107064/how-to-add-view-to-gridview-programmatically-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!