Mike
Mike

Reputation: 51

How to create another button in android dynamically

As the title states, I am looking to find out how to create a button dynamically when another button in another activity is pressed. This is being done with the Android SDK.

Basically, I have two activities, MainActivity and SecondaryActivity, within the SecondaryActivity you enter some information, title, text, id, so on and so forth. When you click the "Save" button it sends some, information to MainActivity(not the issue). As well as sending the information, I need to create an entirely new button within the MainActivity.

Any suggestions on how this should be accomplished?

Thanks.

Edit 1

public void CreateNewButton(View view)
{

    LinearLayout lineLayout = (LinearLayout)findViewById(R.id.linear_layout);
    TextView newTextView = new TextView(this);
    int id = rand.nextInt(100);
    int newId;

    newTextView.setVisibility(View.VISIBLE);
    newTextView.setId( R.id.new_button + id );
    newTextView.setText("New Item");
    newTextView.setTextSize(35);
    newTextView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            intent = new Intent(getBaseContext(), SecondActivity.class);

            startActivity(intent);

        }
    });

    lineLayout.addView(newTextView);
}

This code generates the new TextView( Decided to change it up ) but now the issue I have, is newTextView.setText(); needs to get the text from the other activity

newTextView.setText(i.getData().toString());

putting this in the CreateNewButton(View view) methods causes an error since technically there is no data in the field that it is trying to grab from.

The problem at hand is I need to create the new TextView field WITH the name of the new account that has yet to be created. If that makes any sense.

Upvotes: 1

Views: 1255

Answers (1)

invertigo
invertigo

Reputation: 6438

I'm going to assume you want to add this button to a LinearLayout:

LinearLayout linearLayout = (LinearLayout) findViewById(R.id.linearLayout1);
Button button = new Button(this);
button.setText("I'm a button!");
// add whatever other attributes you want to the button
linearLayout.addView(button);

Upvotes: 2

Related Questions