Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add view to gridview programmatically, android?

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

}
like image 333
WISHY Avatar asked Feb 15 '23 02:02

WISHY


1 Answers

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

like image 77
Sonali8890 Avatar answered Feb 23 '23 15:02

Sonali8890