Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8136177
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 6, 20262026-06-06T10:40:42+00:00 2026-06-06T10:40:42+00:00

I have a CustomButton class (extends LinearLayout ) where I inflate a layout which

  • 0

I have a CustomButton class (extends LinearLayout) where I inflate a layout which contains a ToggleButton (in reality this is more complex, but I simplified here the problem).

public class CustomButton extends LinearLayout {

    private ToggleButton toggleOnOffButton;

    public CustomButton(Context context, AttributeSet attrs) {
        super(context, attrs);
        LayoutInflater.from(context).inflate(R.layout.custom_button_layout, this);
    }

    @Override
    protected void onFinishInflate() {
        toggleOnOffButton = (ToggleButton) findViewById(R.id.toggle_on_off_button);
        super.onFinishInflate();
    }

    public ToggleButton getToggleOnOffButton() {
        return toggleOnOffButton;
    }
}

custom_button_layout.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content">

    <ToggleButton android:id="@+id/toggle_on_off_button"
                  android:layout_width="wrap_content"
                  android:layout_height="wrap_content"
                  android:textOff="Off"
                  android:textOn="On"
                  android:layout_alignParentRight="true"
            />
</RelativeLayout>

I have an activity where I inflate an layout with 2 CustomButton-s.
The on/off state of the first toggleButton is saved in shared preferences and I load the value from there in onCreate method.

public class FirstActivity extends Activity
{
    private CustomButton customButton;
    private ToggleButton toggleBut;

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

        customButton = (CustomButton)findViewById(R.id.toggleButton);
        toggleBut = customButton.getToggleOnOffButton();

        boolean saved = loadPreferences("toggleBut");
        toggleBut.setChecked(saved);
        toggleBut.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                boolean checked = toggleBut.isChecked();
                savePreferences("toggleBut", checked);
            }
        });
    }

    private void savePreferences(String key, boolean value){
        SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putBoolean(key, value);
        editor.commit();
    }

    private boolean loadPreferences(String key){
        SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
        return sharedPreferences.getBoolean(key, true);
    }
}

main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical"
              android:layout_width="fill_parent"
              android:layout_height="fill_parent"> 
    <com.example.example.cs.ssd.custom.CustomButton
            android:id="@+id/toggleButton"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            />

    <com.example.example.cs.ssd.custom.CustomButton
            android:id="@+id/toggleButton2"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            />
</LinearLayout>

When I start the application the first toggleButton is ON. When I change the orientation of the screen, automatically the first toggleButton become Off, even saved has value true and is called toggleBut.setChecked(saved); and I think this has to do with the CutomButton I’ve created because if the main.xml layout contains only 1 CustomButton this problem does not reproduce.
I’m not sure what I’m doing wrong…
Here is the archive with the above code (as a project): archive

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-06T10:40:43+00:00Added an answer on June 6, 2026 at 10:40 am

    If you want your CustomButton to retain its current state after an orientation change simply override onSaveInstanceState() and onRestoreInstanceState().

    A Solution

    I ran through your code and noticed that toggleBut‘s state was being changed after onActivityCreated() but before onStart(). To avoid having any of these methods override your toggle settings, I simply moved these lines from onViewCreated():

    boolean saved = loadPreferences("toggleBut");
    toggleBut.setChecked(saved);
    

    and put them in onResume(). Hope that helps!

    Better Solution

    Your ToggleButton setting are being overwritten when the system tries to restore the default saveInstanceState, probably in Fragment.onActivityCreated().

    In CustomButton, override these functions like so:

    @Override
    protected Parcelable onSaveInstanceState() {
        Bundle state = new Bundle();
        state.putParcelable("default", super.onSaveInstanceState());
        state.putParcelable("toggle", toggleOnOffButton.onSaveInstanceState());
        return state;
    }
    
    @Override
    protected void onRestoreInstanceState(Parcelable state) {
        Bundle bundle = (Bundle) state;
        super.onRestoreInstanceState(bundle.getParcelable("default"));
        toggleOnOffButton.onRestoreInstanceState(bundle.getParcelable("toggle"));
    };
    

    Understand that the system will still change the ToggleButton states, without the one more thing. But let me try to explain what;s happening:

    • onActivityCreated(Bundle savedInstanceState) passes it’s savedInstanceState to every layout element by calling ‘onRestoreInstanceState(Bundle savedInstanceState)`.
    • onRestoreInstanceState() begins with the layout’s root element first and traverses up the layout’s hierarchy (in this case it sets the checked state of each ToggleButton last).
    • Since the default methods are clearly not working, we need to define our own save / restore method for the ToggleButtons. Otherwise any changes we make before the system calls onRestoreInstanceState() will be changed again by the system…

    So, lastly we will exclude the ToggleButtons from this default behavior by adding the following line to CustomButton.onFinishInflate():

    toggleOnOffButton.setSaveEnabled(false);
    

    Voila, your CustomButtons automatically retain their state.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

have written this little class, which generates a UUID every time an object of
I have been trying to develop a CustomButton class that extends MovieClip, however I
I have a custom button class called ImageButton that extends JButton. In it i
I've seen this with other platforms (especially iPhone/iPad) but have not been able to
I've seen this with other platforms (especially iPhone/iPad) but have not been able to
so I have this code: <toolbox id=navigator-toolbox> <toolbar id=abar accesskey=T class=chromeclass-toolbar context=toolbar-context-menu hidden=false persist=hidden>
I have a background MovieClip in a custom button class, which moves the play
I have a custom button Submit Order which simple change Opportunity Stage. But i
Check out this jsbin . I have a form with a custom button that
Have a procedure which looks like Procedure TestProc(TVar1, TVar2 : variant); Begin TVar1 :=

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.