Alex Mamo
Alex Mamo

Reputation: 138824

How to add a button programmatically to a LinearLayout in android

How can i use the linearLayout and the params variables from protected void onCreate, in the second protected void finishButton? I need to add finishButton to the linearLayout. Here is my code:

public class MainActivity extends AppCompatActivity {
    public static int score = 0;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ScrollView scrollView = (ScrollView) findViewById(R.id.scrollView);

        final LinearLayout linearLayout = new LinearLayout(this);
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        linearLayout.setLayoutParams(params);
        linearLayout.setOrientation(linearLayout.VERTICAL);
        linearLayout.setPadding(0, 110, 0, 0);
        scrollView.addView(linearLayout);

        TextView iq_Test_Title = new TextView(this);
        iq_Test_Title.setText("Text");
        iq_Test_Title.setTextSize(TypedValue.COMPLEX_UNIT_SP, 20);
        iq_Test_Title.setGravity(Gravity.CENTER);
        iq_Test_Title.setTextColor(Color.RED);
        linearLayout.addView(iq_Test_Title);

        finishButton();

        // other code
    }

    protected void finishButton() {
        final Button finishButton = new Button(this);
        finishButton.setText(R.string.finish_button);
        finishButton.setLayoutParams(params);
        linearLayout.addView(finishButton);

        finishButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finishButton.setEnabled(false);
            }
        });
    }
}

Thanks!

Upvotes: 1

Views: 647

Answers (2)

Brian Hibbert
Brian Hibbert

Reputation: 250

If I understand you correctly, you probably want to return the button to the caller from finishButton(). Then add it to the view in onCreate.

Change your declaration of finishButton to

protected Button finishButton()

After you've got it configured, add the line:

return finishButton;

at the end of that method. Then in onCreate:

linearLayout.addView(finishButton());

Upvotes: 0

AdamMc331
AdamMc331

Reputation: 16691

To access the view inside the finishButton method, just make it a class level variable:

public class MyActivity...
   private LinearLayout mLinearLayout;

   protected void onCreate(..){
      mLinearLayout = new LinearLayout(this);
      ...
   }

   private void finishButton(){
      ...
      mLinearLayout.addView(..);
   }
}

Upvotes: 1

Related Questions