Make one button width to fill the parent program

How to make a single button width to programmatically fill the parent element? I did this, but it doesn't seem to work, it is still in the upper left corner, just wrapping the contents ... here are some of the code when creating the button ...

public class TEST_GIFDisplay extends Activity implements View.OnClickListener {

    SurfaceView sview;
    GifRun gr = new GifRun();
    Button btnBack;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        sview = new SurfaceView(this);
        sview.setZOrderOnTop(true);

        gr.LoadGiff(sview, this, R.drawable.smiley);

        LinearLayout linearLayout1 = new LinearLayout(this);
        linearLayout1.setOrientation(LinearLayout.VERTICAL);
        linearLayout1.setBackgroundColor(Color.parseColor("#27ae60"));
        linearLayout1.setLayoutParams(new ViewGroup.LayoutParams(
                ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT));

        LinearLayout linearLayout2 = new LinearLayout(this);
        linearLayout2.setOrientation(LinearLayout.VERTICAL);
        linearLayout2.setBackgroundColor(Color.parseColor("#27ae60"));
        linearLayout2.setLayoutParams(new ViewGroup.LayoutParams(
                ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT));

        LinearLayout.LayoutParams p = new   
        LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT,   
        LinearLayout.LayoutParams.WRAP_CONTENT);
        p.weight = 1.0f;

        btnBack = new Button (this);
        btnBack.setText("Back");
        btnBack.setBackgroundColor(Color.parseColor("#f1c40f"));
        btnBack.setGravity(Gravity.CENTER_HORIZONTAL);
        btnBack.setLayoutParams(p);
        btnBack.setOnClickListener(this);

        linearLayout2.addView(btnBack);
        linearLayout1.addView(linearLayout2);
        linearLayout1.addView(sview);

        setContentView(linearLayout1);
    }

    @Override
    public void onClick(View view) {
        btnBack = (Button) view;
        btnBack.setBackgroundColor(Color.parseColor("#2980b9")); //color change
        new CountDownTimer(100, 50) {

            @Override
            public void onTick(long arg0) {
                // TODO Auto-generated method stub
            }

            @Override
            public void onFinish() {
                btnBack.setBackgroundColor(Color.parseColor("#f1c40f")); // original color
            }
        }.start();//end color changed

        finish();
    }
}
+4
source share
1 answer

You add Buttonin linearLayout2. You must change the width linearLayout2'stoMATCH_PARENT

linearLayout2.setLayoutParams(new ViewGroup.LayoutParams(
        ViewGroup.LayoutParams.MATCH_PARENT,
        ViewGroup.LayoutParams.WRAP_CONTENT));

Hope this helps.

P.S: Button's , . , : Android

+3

Source: https://habr.com/ru/post/1535248/


All Articles