3

我有一个带有一些片段等的小应用程序。现在每次我改变屏幕的方向时,动作都会重新启动,这意味着如果你转动设备,输入就会丢失。我怎样才能防止这种情况?此外,我想保留更改方向的可能性,并且应用程序随之更改,我只想保留内容。

魔法发生在 MainActivity.java 中,显示在 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;
}
}

搜索片段.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>
4

3 回答 3

3

使用此方法:只需调用Activity.getLastNonConfigurationInstance以检索您在onRetainNonConfigurationInstance. 请务必检查 null 并转换为正确的类(您可以返回/获取任何类)。Activity.getLastNonConfigurationInstance

示例用法pseudo-code如下:

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";

因此,如果您的目标是 2.xx,您可以使用该方法。否则,google 建议您使用 Fragment.setRetainInstance。这是通过兼容性包向后兼容的。

于 2013-02-08T09:23:50.747 回答
2

据我所知,此方向更改有一个侦听器,以便您可以在方向更改之前保存一些数据,因为当方向更改活动在内部重新启动时。

查看http://developer.android.com/reference/android/view/OrientationListener.html

那是类看看那里。

希望有帮助。

于 2013-02-08T08:38:43.287 回答
0

如果水平和垂直的布局相同,请将以下内容添加到清单中的活动中:

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

现在活动不会重置。

于 2013-02-08T08:38:16.440 回答