Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: Button created in run-time to MATCH_PARENT in Java

Hey Everyone,

import android.widget.Button;

@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.webpage);

        but_action = new Button(getApplicationContext());
        but_action.setVisibility(Button.INVISIBLE);
        toolbar.addView(but_action);

Regarding the code above, this creates an invisible button that i make visible based on some conditions. This works, and so does the logic on the button.

Problem is that the height of the button is static, and this cant be the case. I need this button to simply match its parents height (as you can see its in the toolbar view, which is just a horizontal linearlayout), as the height of the toolbar is different on the tablet sized views as opposed to the phone sized views.

I heard that I need to use LayoutParams, but I will be totally honest: nothing i try validates, and when it does: does nothing. And using setHeight seems to only accept numerical values.

I'm sort of at a roadblock where I'm not sure what else to try.

(also is there something like a float: right; for real-time layout?)

like image 296
RedactedProfile Avatar asked Dec 13 '22 06:12

RedactedProfile


1 Answers

This should do it for you:

LayoutParams lp = new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT);
but_action.setLayoutParams(lp);

note that when you go to import LayoutParams you want to pick the one that matches your parent, so in this case you'll import the LinearLayout.LayoutParams

like image 64
FoamyGuy Avatar answered Mar 09 '23 00:03

FoamyGuy