Search code examples
androidonconfigurationchanged

Change layout if orientation change, error with buttons


I used onConfigurationChanged method to know when the orientation change. But, when I call other layout the buttons not working.

here is my code:

IntroPage.java

package com.example.mysqltest;

import android.app.Activity;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.Toast;

public class IntroPage extends Activity implements OnClickListener {

    private Button btnlogin;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.intropage);


        btnlogin = (Button)findViewById(R.id.btnlogin); 

        btnlogin.setOnClickListener(this);

    }
    // Check screen orientation or screen rotate event here
    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        setContentView(R.layout.intropage);

        // Checks the orientation of the screen for landscape and portrait
        if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
            setContentView(R.layout.intropage_landscape);
            Toast.makeText(this, "landscape", Toast.LENGTH_SHORT).show();

        } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){
            Toast.makeText(this, "portrait", Toast.LENGTH_SHORT).show();

        }
    }   




    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        Intent i = new Intent(IntroPage.this, Login.class);
        startActivity(i);


    }



    }

and i write android:configChanges="orientation|screenSize" in my manifest xml. Please someone help me...What I can do with buttons not working?


Solution

  • Even though this is not the recommended way to handle this, a quick suggestion would be to add these two lines again after you do setContentView(R.layout.intropage_landscape);

    btnlogin = (Button)findViewById(R.id.btnlogin); 
    btnlogin.setOnClickListener(this);
    

    Recommended way is:

    1. Not to call setContentView for each orientation. Call setContentView once in onCreate and initialize all the UI elements.
    2. Then re-use the common UI elements for both orientation
    3. If there are some non common UI elements, then use fragments to add and remove as necessary.

    Hope this helps.