简体   繁体   中英

Saving dynamically created button android

I am trying to save a button that I make dynamically on a separate activity, but I cant seem to get it to work. Here is what I have tried in my CreateButton.java:

    private static final AtomicInteger sNextGeneratedId = new AtomicInteger(1);

public static int generateViewId() {
    for (;;) {
        final int result = sNextGeneratedId.get();
        // aapt-generated IDs have the high byte nonzero; clamp to the range under that.
        int newValue = result + 1;
        if (newValue > 0x00FFFFFF) newValue = 1; // Roll over to 1, not 0.
        if (sNextGeneratedId.compareAndSet(result, newValue)) {
            return result;
        }
    }
}

public void Submit (View view) {
        Intent myIntent = new Intent(CreateNewClass.this, MainActivity.class);
        EditText mEdit   = (EditText)findViewById(R.id.class_name);
        String name = mEdit.getText().toString();

        mEdit   = (EditText)findViewById(R.id.class_semester);
        String semester = mEdit.getText().toString();

        mEdit   = (EditText)findViewById(R.id.class_year);
        String year = mEdit.getText().toString();

        Button myButton = new Button(this);

        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) {
            myButton.setId(generateViewId());
        }
        else {
            myButton.setId(Button.generateViewId());
        }

        myButton.setText(name + " " + semester + " " + year);

        setContentView(R.layout.activity_main);
        LinearLayout ll = (LinearLayout)findViewById(R.id.main_screen);
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams
                (LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        ll.addView(myButton, layoutParams);

        startActivity(myIntent);
    }

And here is my .xml for the activity_main:

    <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/main_screen"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/select" />

    <Button
        android:layout_height="wrap_content"
        android:clickable="true"
        android:autoLink="web"
        android:layout_width="match_parent"
        android:id="@+id/button_so"
        android:text="@string/Google"
        android:linksClickable="true"
        android:onClick="goToGoogle"/>


    <Button
        android:layout_height="wrap_content"
        android:layout_width="match_parent"
        android:text="@string/newClass"
        android:autoLink="web"
        android:clickable="true"
        android:id="@+id/button_su"
        android:onClick="goToCreate"/>
</LinearLayout>

It creates the button dynamically on the mainActivity and navigates to it, but I cannot get it to save the button, it immediately goes back to just the two original buttons.

Any help is really appreciated, I am a newbie and am just trying to learn some of this stuff on the side. Thank you!

That's because you're first setting the View using setContentView , which basically just displays the Layout you have inflated inside your current Activity. And after that you're starting a new Activity, which launches a completely independent View on its own and therefore does still display the default buttons.

If you want to set the text and add the Button inside the actual Activity, it is a good practice to pass the String as an Intent Extra.

So your submit method should look like this:

//by the way you shouldn't start method names with upper case
public void submit (View view) {
        Intent myIntent = new Intent(CreateNewClass.this, MainActivity.class);
        EditText mEdit   = (EditText)findViewById(R.id.class_name);
        String name = mEdit.getText().toString();

        mEdit   = (EditText)findViewById(R.id.class_semester);
        String semester = mEdit.getText().toString();

        mEdit   = (EditText)findViewById(R.id.class_year);
        String year = mEdit.getText().toString();

        String buttonText = name + " " + semester + " " + year;

        myIntent.putExtra("button_text", buttonText);

        startActivity(myIntent);
    }

And in your MainActivity you can then place the button by pasting the following code into the onCreate method.

Intent intent = getIntent();
String buttonText = intent.getStringExtra("button_text");

//activity could also be started without providing the extra
if(buttonText != null){
    Button button = new Button(this);
    button.setText(buttonText);
    LinearLayout ll = (LinearLayout)findViewById(R.id.main_screen);
    LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams
      (LinearLayout.LayoutParams.WRAP_CONTENT, 
      LinearLayout.LayoutParams.WRAP_CONTENT);
    ll.addView(button, layoutParams);
}

EDIT:

Okay, since you're trying to achieve something a bit different, than I thought, you should try an other approach.

You are trying to get a Result from the second Activity and therefore it would be perfect to use the startActivityForResult() (see documentation ) method here. I assume that your application is using the MainActivity as the first Activity that gets shown.

Instead of launching the second Activity by issuing startActivity() you use startActivityForResult() providing any constant as request code. In your submit method you can then remove the startActivity(myIntent) line and instead place the following code there:

setResult(Activity.RESULT_OK, myIntent);
finish();

In your MainActivity again you can now override the onActivityResult method with the following implementation:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    //you specified the request code before, when launching the second activity
    if(requestCode == ADD_USER_REQUEST){
        if(resultCode == Activity.RESULT_OK){
            String buttonText = data.getStringExtra("button_text");
            if(buttonText != null){
                Button button = new Button(this);
                button.setText(buttonText);
                LinearLayout ll = (LinearLayout)findViewById(R.id.main_screen);
                LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams
                  (LinearLayout.LayoutParams.WRAP_CONTENT, 
                  LinearLayout.LayoutParams.WRAP_CONTENT);
                ll.addView(button, layoutParams);

                //here comes the part that saves the button strings persistently
                SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
                Set<String> buttonSet = prefs.getStringSet("saved_buttons",null);
                if(buttonSet == null){
                    buttonSet = new HashSet<String>();
                }
                buttonSet.add(buttonText);
                prefs.edit.putStringSet("saved_buttons", buttonSet).commit();
            }

        }
    }

And finally you need to rebuild the old layout when the activity gets relaunched. Place the following code inside the MainActivity.onCreate , delete the Intent Extra stuff.

SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
Set<String> buttonSet = prefs.getStringSet("saved_buttons", null);
if(buttonSet != null){
    LinearLayout ll = (LinearLayout)findViewById(R.id.main_screen);
    for(String buttonText : buttonSet){
        Button button = new Button(this);
        button.setText(buttonText);    
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams
          (LinearLayout.LayoutParams.WRAP_CONTENT, 
          LinearLayout.LayoutParams.WRAP_CONTENT);
        ll.addView(button, layoutParams);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM