How to add view to gridview programmatically, android?

android, dynamic, gridview

Solution

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:)

Problem

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; } } ```

Original source