Gaurav
Gaurav

Reputation: 535

Best way to create buttons dynamically

I want to create button dynamically in my application. The buttons need to be created based on items fetched from database. What is the best way to achieve this. Should I go for grid layout or Linear layout. My layout is simple with max 3 buttons per row. Once the first row is complete the buttons should be placed in second row.

I scanned lot of similar questions(some had grid layout other were using Linear layout) but unable to decide what is the optimum way to implement this.

I am complete newbie in android application, so any code snippets would be really helpful. Apologies if someone feels this is a duplicate question (I searched a lot before posting but didn't find appropriate answer to layout to be used.)

Thanks.

Upvotes: 0

Views: 135

Answers (1)

nilesh patel
nilesh patel

Reputation: 832

Please try to use gridView same as bellow code.

// in xml write this code 

    <GridView  

       android:id="@+id/calendar"
       android:layout_width="fill_parent"
       android:layout_height="wrap_content"
       android:numColumns="3" />


// grid adapter

public class GridAdapter extends BaseAdapter {
    private final Context _context;

    private final List<String> list;

    public GridAdapter(Context context, ArrayList<String> list) {
        super();
        this._context = context;
        this.list = list;
    }

    public String getItem(int position) {
        return list.get(position);
    }

    @Override
    public int getCount() {
        return list.size();
    }

    public View getView(int position, View convertView, ViewGroup parent) {
        Button button = new Button(_context);
        button.setText("button" + list.get(position));
        return button;
    }

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


/// in oncreate 

gridView.setAdapter(new GridAdapter(getApplicationContext(),list);

Upvotes: 1

Related Questions