Glave
Glave

Reputation: 137

How do i set the attributes of programmatically created buttons?

How do i set the attributes of programmatically created buttons? For instance: In my example below I want to create a "android:layout_weight="1"" and an "on_click="startsearch"" attribute for my "Place" Button.

    List<DB_Verlauf_Contact> placeList = db.getAllDBPlaces();
    LinearLayout layout = (LinearLayout) findViewById(R.id.verlauf_liste);

    for (DB_Verlauf_Contact cn : placeList) {
        String log = "Id: "+cn.getID()+" ,Place ID: " + cn.getPlace_id() + " ,Name: " + cn.getName()+ " ,Longitude: " + cn.getLongitude()+ " ,Latitude: " + cn.getLatitude();
        LinearLayout row = new LinearLayout(this);
        row.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));

        Button Place = new Button(this);
        Place.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
        Place.setText(cn.getName());
        Place.setId(cn.getID());
        row.addView(Place);

        Button Delete = new Button(this);
        Delete.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
        Delete.setText("Löschen");
        Delete.setId(cn.getID());
        row.addView(Delete);

        layout.addView(row);
        Log.d("Name: ", log);
    }

Upvotes: 1

Views: 50

Answers (1)

Ognian Gloushkov
Ognian Gloushkov

Reputation: 2659

Go with:

Button place = new Button(this);
LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) place.getLayoutParams();
params.weight = 1.0f;
place.setLayoutParams(params);


place.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View v) {
        //handle the click
    }
});

Instance names should begin with a lowercase letter.

Upvotes: 2

Related Questions