10

我在我的代碼中使用了一個微調器下拉菜單,其中我有4到5個動態填充值,如果我將「蘋果」設置爲默認值,並從下拉列表中選擇「桔子」,並將我的屏幕從畫像,它會回到默認的「蘋果」以及與它相關的視圖。如何保存狀態,使得當我選擇「桔子」並旋轉到橫向時,它會填充選定的值/保持在相同的選定狀態並保持該視圖保持不變/填充在與所選值對應的肖像模式中選擇的視圖。下面是我用相同的適配器代碼:如何在方向更改時保留選定的微調器/下拉項目的狀態?

public class MarketsSpinnerAdapter extends CustomRowAdapter<AdapterRow> { 


    private List<AdapterRow> mRenderList; 

    public MarketsSpinnerAdapter(final Context context, final List<AdapterRow> renderList) { 
     super(context); 


     mRenderList = new ArrayList<AdapterRow>(); 
     mRenderList.addAll(renderList); 
    } 

    @Override 
    protected void setEntries(final List<AdapterRow> renderList) { 
     mRenderList = renderList; 
    } 

    @Override 
    protected List<AdapterRow> getEntries() { 
     return mRenderList; 
    } 

    @Override 
    public View getDropDownView(final int position, final View convertView, final ViewGroup parent) { 
     return getEntries().get(position).getDropDownView(mContext, convertView); 
    } 

} 

相應的使用在各自的片段:

private void populateCategoryRows(final Cursor cursor) { 
      mCategories.clear(); 
      mAllCategories.clear(); 
      cursor.moveToPosition(-1); 
      Map<String, String> categoryParentNames = new HashMap<String, String>(); 

      int selectedPosition = 0; 
      String previousHeader = ""; 
      String previousAllHeader = ""; 

      while (cursor.moveToNext()) { 
       final int categoryLevel = cursor.getInt(cursor.getColumnIndex(MarketsCategory.Columns.LEVEL)); 
       final String categoryName = cursor.getString(cursor.getColumnIndex(MarketsCategory.Columns.NAME)); 
       final String categoryDisplayName = cursor.getString(cursor.getColumnIndex(MarketsCategory.Columns.DISPLAY_NAME)); 

       if (categoryLevel == 1) { 
        categoryParentNames.put(categoryName, categoryDisplayName); 
       } 
      } 

      cursor.moveToPosition(-1); 
      while (cursor.moveToNext()) { 
       final int categoryLevel = cursor.getInt(cursor.getColumnIndex(MarketsCategory.Columns.LEVEL)); 
       final boolean categoryIsDefault = cursor.getInt(cursor.getColumnIndex(MarketsCategory.Columns.IS_DEFAULT)) == 1; 
       final boolean categoryIsSelected = cursor.getInt(cursor.getColumnIndex(MarketsCategory.Columns.IS_SELECTED)) == 1; 
       final String categoryParent = cursor.getString(cursor.getColumnIndex(MarketsCategory.Columns.PARENT)); 
       final String categoryName = cursor.getString(cursor.getColumnIndex(MarketsCategory.Columns.NAME)); 
       final String categoryDisplayName = cursor.getString(cursor.getColumnIndex(MarketsCategory.Columns.DISPLAY_NAME)); 


       if (categoryLevel == 2) { 
        String categoryParentDisplayName = categoryParentNames.get(categoryParent); 
         if (!categoryParent.equals(previousHeader)) { 
          if (categoryIsSelected) { 

           mCategories.add(new CategoryHeader(categoryParentDisplayName)); 
           previousHeader = categoryParent; 
          } 
         } 

         if (!categoryParent.equals(previousAllHeader)) { 
          mAllCategories.add(new CategoryHeader(categoryParentDisplayName)); 
          previousAllHeader = categoryParent; 
         } 

         if (categoryIsSelected) { 
          mCategories.add(new SpinnerMarketCategoryRow(categoryName, categoryDisplayName, categoryParent)); 
         } 
         mAllCategories.add(new MarketsCategoryCheckableRow(categoryName, categoryDisplayName, categoryIsSelected, categoryIsDefault)); 

         if(categoryIsDefault){ 
          selectedPosition = mCategories.size()-1; 
         } 
       } 
      } 

      mSpinnerAdapter = new MarketsSpinnerAdapter(Application.getAppContext(), mCategories); 
      headerView.setSpinnerAdapter(mSpinnerAdapter); 
      headerView.setSpinnerSelectedItemPosition(selectedPosition); 
     } 
     if (selectedItem instanceof SpinnerMarketCategoryRow) { 
      selectedCategory = (SpinnerMarketCategoryRow) mSpinnerAdapter.getItem(position); 
     } else { 
      if (mSpinnerAdapter.getCount() - 1 >= position + 1) { 
       selectedCategory = (SpinnerMarketCategoryRow) mSpinnerAdapter.getItem(position + 1); 
      } else { 
       selectedCategory = (SpinnerMarketCategoryRow) mSpinnerAdapter.getItem(position - 1); 
      } 
     } 

     final MarketsFragment parentFragment = (MarketsFragment) getParentFragment(); 
     parentFragment.onCategorySelected(selectedCategory.getCategoryName(), selectedCategory.getCategoryParentName()); 
    } 
@Override 
    public void showResults(final Uri uri) { 
     LayoutUtils.showResults(getView(), headerView.getSpinnerId()); 
     headerView.setVisibility(View.VISIBLE); 
    } 

    @Override 
    public void showNoResults(final Uri uri) { 
     final MarketsFragment parentFragment = (MarketsFragment) getParentFragment(); 
     parentFragment.hideSpinner(); 
     //LayoutUtils.showNoResult(getView(), headerView.getSpinnerId()); 
    } 

    @Override 
    public void onDismiss(DialogInterface dialog) { 
     headerView.setSelected(false); 
    } 
    @Override 
    public void onNothingSelected(IcsAdapterView<?> parent) { 
    } 

任何想法?

謝謝!

回答

17

你可以做到這一點像...

@Override 
protected void onSaveInstanceState(Bundle outState) { 
    super.onSaveInstanceState(outState); 
    outState.putInt("yourSpinner", yourSpinner.getSelectedItemPosition()); 
    // do this for each or your Spinner 
    // You might consider using Bundle.putStringArray() instead 
} 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    // initialize all your visual fields   
    if (savedInstanceState != null) { 
     yourSpinner.setSelection(savedInstanceState.getInt("yourSpinner", 0)); 
     // do this for each of your text views 
    } 
} 

希望這有助於

+1

我的微調是在onCreateOptionsMenu中定義的。我該如何解決這個問題? – TeodorKolev

+1

此解決方案可能會使微調控制器多次調用OnItemSelected()。 –

+0

@SamRamezanli解釋說爲什麼可以多次調用該方法將會有所幫助。 – Elyasin

0

如果設備的配置變化(由Resources.Configuration類中定義),那麼任何顯示用戶界面將需要更新以匹配該配置,因此您的Activity除非另有說明,否則配置更改(例如屏幕方向,語言,輸入設備等的更改)將導致當前活動被破壞,通過的正常Activity lifecycle process的onPause() ,onStop()和onDestroy()

如果該活動已經在前臺或對用戶可見,一旦的onDestroy()被稱爲該實例,則活動的新實例將被創建,與任何savedInstanceState以前的實例已經產生從onSaveInstanceState(Bundle)

這樣做是因爲任何應用程序資源(包括佈局文件)都可以根據任何配置值進行更改。在一些特殊情況下(就像你的,如果我正確的話,如果你只有微調/下拉在當前用戶界面&你不需要經歷完整的活動生命週期),你可能想繞過重新開始你的活動或更多類型的配置更改。這是通過其清單中的屬性完成的和/或也可以使用onSaveInstanceState(Bundle)當活動被破壞並且從該再生時重新創建時這是調用者。

您只需解決此problem_

1_

    1. 添加安卓雙向:configChanges = 「方向」在活動標記的清單文件。
<?xml version="1.0" encoding="utf-8"?> 
<manifest ... 
> 
<application ... 
    >  
    <activity 
     android:name="SpinnerActivity" 
     android:configChanges="orientation" > 
     <intent-filter> 
      <action android:name="android.intent.action.MAIN" /> 
      <category android:name="android.intent.category.LAUNCHER" /> 
     </intent-filter> 
    </activity> 
</application> 

</manifest> 
  • 2,覆蓋onConfigurationChanged,其由系統中的設備配置的改變您的活動運行時當調用。
@Override 
public void onConfigurationChanged(Configuration newConfig) { 
    super.onConfigurationChanged(newConfig); 
    int orientation = newConfig.orientation; 

    switch (orientation) { 
    case Configuration.ORIENTATION_LANDSCAPE: 
     // do what you want when user is in LANDSCAPE 
     break; 

    case Configuration.ORIENTATION_PORTRAIT: 
     // do what you want when user is in PORTRAIT 
     break; 
    } 

} 

2_

使用put方法來存儲值的onSaveInstanceState():

protected void onSaveInstanceState(Bundle savedInstanceState) { 
    super.onSaveInstanceState(savedInstanceState); 
    //Put your spinner values to restore later... 
    savedInstanceState.putLong("yourSpinnerValKey", yourSpinner.getSelectedItemPosition()); 
} 

,恢復值的onCreate():

public void onCreate(Bundle savedInstanceState) { 
    if (savedInstanceState!= null) { 
    //get your values to restore... 
     value = savedInstanceState.getLong("param"); 
    } 
} 

這一定會解決您的問題,並且屏幕方向更改時不會刷新您的微調器。我希望這會幫助你和所有人! :)

+0

微調控制器的狀態保存在哪裏? –

+0

@justice,請通過更新的ans。 –

相關問題