Reset action on screen orientation change

I have a small application with some fragments, etc. Now, every time I change the orientation of my screen, the activity restarts, which means that the input is lost if you turn on your device. How can I prevent this? Also, I would like to leave the option to change my orientation and the application will change with it, I just want to keep the content.

The magic happens in MainActivity.java, the display is in SearchFragment.xml

MainActivity.java:

package mypackage;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Toast;
import android.view.View;
import android.view.inputmethod.InputMethodManager;


public class MainActivity extends Activity {


public final static String EXTRA_MESSAGE = "mypackage.MESSAGE";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    //addListenerOnSpinnerItemSelection();

 // lädt die ActionBar
        ActionBar actionbar = getActionBar();
        actionbar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
        actionbar.setDisplayShowHomeEnabled(true);
        actionbar.setDisplayShowTitleEnabled(true);
        actionbar.setDisplayShowCustomEnabled(false);

        // lädt die Tabs in die Actionbar
        String search = getString(R.string.search_fragment);
        String user = getString(R.string.user_fragment);
        String recent = getString(R.string.recent_fragment);

        ActionBar.Tab TabA = actionbar.newTab().setText(search);
        ActionBar.Tab TabB = actionbar.newTab().setText(user);
        ActionBar.Tab TabC = actionbar.newTab().setText(recent);

        // erstellt neue Fragmente
        Fragment fragmentA = new SearchFragment();
        Fragment fragmentB = new UserFragment();
        Fragment fragmentC = new UpdateFragment();

        // Listener werden angelegt
        TabA.setTabListener(new MyTabsListener(fragmentA));
        TabB.setTabListener(new MyTabsListener(fragmentB));
        TabC.setTabListener(new MyTabsListener(fragmentC));

        // Tabs werden in die actionbar geladen
        actionbar.addTab(TabA);
        actionbar.addTab(TabB);
        actionbar.addTab(TabC);

}


public void sendMessage(View view) 
{

    Spinner mySpinner = (Spinner) findViewById(R.id.criterion);
    String text = mySpinner.getSelectedItem().toString();

    //manual initialation of array - later to be created by XML-Parser
    String[][] array = {{"Opel", "Astra", "2010", "120 PS", "12 l/100km", "Blau, Rot, Grün, Braun", "File 1", "File 2"}, 
                        {"Opel", "Corsa", "2012", "80 PS", "8 l/100km", "Grün, Rot, Blau, Gelb, Magenta", "File 1", "File 2", "File 3"},
                        {"Opel","Vectra", "1980", "200 PS" ,"20 l/100km", "Braun", "file 1"},
                        {"Opel", "Astra", "2010", "120 PS", "12 l/100km", "Blau, Rot, Grün, Braun", "File 1", "File 2"}, 
                        {"Opel", "Corsa", "2012", "80 PS", "8 l/100km", "Grün, Rot, Blau, Gelb, Magenta", "File 1", "File 2", "File 3"},
                        {"Opel","Vectra", "1980", "200 PS" ,"20 l/100km", "Braun", "file 1"}    };



//        Intent intent = new Intent(this, DisplayMessageActivity.class);

    EditText editText = (EditText) findViewById(R.id.edit_message);

    String output = "";

    //add Elements of Array on output string
    for(int i = 0; i <array.length; i++)
    {
        int count = 0;

        //Standard values
        for(int j = 0; j<6; j++)
        {
            output = output + array[i][j];
            if(count<5)
            {
                output = output + " - ";
            }
            count++;
        }

        output = output + "\n";

        int count2 = 6;

        //User generated values with diferent length
        for(int k = 6; k <array[i].length; k++)
        {
            output = output + array[i][k];
            if(count2<array[i].length-1)
            {
                output = output + " - ";
            }
            count2++;
        }

        output = output + "\n\n";
    }


    String message = getText(R.string.search_text)+" "+text+": "+ editText.getText().toString() + "\n\n"+output;

   //display results 
   TextView viewText1 = (TextView) findViewById(R.id.showResults);
   viewText1.setText(message);

   //Clear EditText field
   editText.setText("");

   //Hides Softkeyboard on "Send" Button
   InputMethodManager imm = (InputMethodManager)getSystemService(
              Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(editText.getWindowToken(), 0);

//        intent.putExtra(EXTRA_MESSAGE, message);
//        startActivity(intent);

}


class MyTabsListener implements ActionBar.TabListener {
    public Fragment fragment;

    public MyTabsListener(Fragment fragment) {
        this.fragment = fragment;
    }

    @Override
    public void onTabReselected(Tab tab, FragmentTransaction ft) {
        // wenn das Tab erneut gewŠhlt wird.
    }

    @Override
    public void onTabSelected(Tab tab, FragmentTransaction ft) {
        ft.replace(R.id.fragment_container, fragment);
    }

    @Override
    public void onTabUnselected(Tab tab, FragmentTransaction ft) {
        ft.remove(fragment);
    }

}





@Override //creates the action bar menu using the text information from strings.xml and the method menu() from R.java
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.activity_main, menu);
    return true; //number of points in overflow menu or sth like this

}



public boolean onOptionsItemSelected(MenuItem item) {
    switch(item.getItemId()) {
    case R.id.menu_settings:
    {
        Intent intent = new Intent(this, Settings.class);
      startActivity(intent);
      break;
    }
    case R.id.about_section:
    {
        Intent intent = new Intent(this, About.class);
        startActivity(intent);
        break;
    }
    case R.id.faq_section:
    {
        Intent intent = new Intent(this, FAQ.class);
        startActivity(intent);
        break;
    }
    case R.id.search_section:
    {
        Intent intent = new Intent(this, MainActivity.class);
        startActivity(intent);
        break;
    }
    }

  return true;
}
}

      

SearchFragment.xml

    <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_gravity="center"
    android:orientation="vertical" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:layout_gravity="center"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="@string/welcome" />
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="70dp"
        android:orientation="horizontal" >

        <EditText
            android:id="@+id/edit_message"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="20dp"
            android:layout_marginRight="20dp"
            android:hint="@string/edit_message" />

    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="8dp" >

        <Spinner
            android:id="@+id/criterion"
            android:layout_width="117dp"
            android:layout_height="wrap_content"
            android:layout_marginRight="5dp"
            android:layout_marginLeft="5dp"
            android:layout_weight="1"
            android:entries="@array/array"
            android:prompt="@string/prompt" />

        <Button
            android:id="@+id/btnSubmit"
            android:layout_width="136dp"
            android:layout_marginRight="5dp"
            android:layout_marginLeft="5dp"
            android:layout_height="match_parent"
            android:layout_gravity="clip_vertical"
            android:onClick="sendMessage"
            android:text="@string/button_send"
            android:background="@drawable/android" />
    </LinearLayout>

    <TextView
        android:id="@+id/showResults"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium" />

</LinearLayout>

      

+3


source to share


3 answers


There is a listener for this orientation change as far as I know, so you can save some data before the orientation change, since when the orientation changes, the activity happens internally.

Check out http://developer.android.com/reference/android/view/OrientationListener.html



This is the class that is viewed there.

Hope it helped.

+2


source


Using this method: just call Activity.getLastNonConfigurationInstance

to get the same object you returned in onRetainNonConfigurationInstance

. Make sure to check for null and the producer in the class you want (you can return / get any class).Activity.getLastNonConfigurationInstance

An example of using whitespace in pseudo-code

would be:



onRetainNonConfigurationInstance:
    return "I need to remember this next time";

onCreate:
    ...
    String messageToShow = null;
    Object data = getLastNonConfigurationInstance();
    if(data != null)
        messageToShow = (String)data;
    else
        messageToShow = "Nothing to show";

      

So if you are targeting 2.xx you can use this method. Otherwise google recommends using Fragment.setRetainInstance. This is backward compatible with the compability package.

+3


source


If the layout is the same horizontally and verticall, add the following to your manifest:

<activity android:name="yourpackage.MainActivity" android:configChanges="orientation"/>

      

Now the activity will not be reset.

0


source







All Articles