Search code examples
androidtextviewlayoutparams

How to restore programmatically changed LayoutParams after configuration changes


Say the textsize of a textview defined in the layout file is 12sp, I dynamically changed it to 24sp .but When I rotate the screen, the textsize will change back to 12sp. Is there anyway to retain the LayoutParams that is set at run time when configuration changes?


Solution

  • Hi user3591494 you can save and restore your text size with android. Add below code to your activity.

    private final String TEXT_SIZE_KEY = "text_size";
    
    @Override
    public void onSaveInstanceState(Bundle savedInstanceState) {
        // save text view size
        savedInstanceState.putFloat(TEXT_SIZE_KEY, yourTextView.getTextSize());
        super.onSaveInstanceState(savedInstanceState);
    }
    

    Then restore your textSize after your activity restores like this

    @Override
    public void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
    
        // restore your text size and set to your text view
        float textSize = savedInstanceState.getFloat(TEXT_SIZE_KEY);
        yourTextView.setTextSize(textSize);
    }
    

    Hi again, sorry answer to your comment is too big to be posted. The approach will be same. So when u call linearLayout.LayoutParams(0,MATCH_PARENT, 1f)) if you hover on the function you'll see what your calling is linearLayout.LayoutParams(int, int, float) the parameters being width, height and weight. So using the same approach store the 3 values in bundle using savedInstanceState.putInt(FRAME_A_WIDTH, yourLayout.getLayoutParams().width) and restore it using the same approach in onRestoreInstanceState() function. Instead of calling yourTextView.setTextSize(textSize) on your text view just call setLayoutParams on your view with restored values. Let me know if you need code snippet for this question, post your xml & i'll add it above.