我需要在微调器中保存所选项目。目前我有3个部分,topnews / mynews和breakingviews。每个部分都有一个动态列表,包括项目,例如topnews有欧洲/亚洲/德国/ frontnews等。在侧面我有一个菜单按钮,我可以在这里添加或删除要在这3个类别中显示的项目。现在,每次我在锭床工人中选择一个项目时都会说"德国"然后我点击菜单按钮,添加或删除德国上方或下方的任何项目,位置也会在微调器上移动到以前选择的项目或下一个项目。如何通过菜单按钮使旋转器记住最后一个选择,而不管菜单列表中添加或删除的项目。
我在sharedpreferencesmanager.java中添加了以下代码:
private static final String PROPERTY_NEWS_INDEX = "newsindex";
public void savenewsselectedindex(int selectedindex) {
mSharedPreferences.edit().putInt(PROPERTY_NEWS_INDEX, selectedindex).apply();
Log.d("newsdash", "");
}
public int getnewsselectedindex(){
return mSharedPreferences.getInt(PROPERTY_NEWS_INDEX, 0);
}
以下是我的片段类:(我仍然没有将共享偏好应用于它,不知道在哪里添加它以及如何添加它,无论是位置参数还是显示的字符串:
public class NewsCategoriesFragment extends AbsLoaderFragment implements OnItemSelectedListener, OnClickListener, OnMenuItemClickedListener,Dialog.OnDismissListener {
public static final String TAG_NEWS_CATEGORIES_FRAGMENT = "NewsCategoriesFragment";
private static int mSelectedCategoryCodePosition;
private NewsCategorySpinnerAdapter mCategoryAdapter;
private List<AdapterRow> mTopNewsRows;
private List<AdapterRow> mMyNewsRows;
private List<AdapterRow> mBreakingViewsRows;
private List<AdapterRow> mMostReadNewsRows;
private boolean mHasNonMyNewsCategoriesLoaded;
private boolean mHasMyNewsCategoriesLoaded;
private String mSelectedCategory;
private boolean mFirstTimeLoadingMyNews;
private boolean mFirstTimeLoadingNonMyNews;
private MenuHelper mMenuHelper;
private final ArrayList<String> mMenuItems = new ArrayList<String>();
private HeaderView headerView;
private static class MenuItems{
final static String MANAGE_NEWS_CATEGORIES = Application.getAppResources().getString(R.string.news_menu_manage);
final static String NEWS_PREFERENCES = Application.getAppResources().getString(R.string.news_menu_preferences);
static final int MANAGE_NEWS_CATEGORIES_POSITION = 0;
static final int NEWS_PREFERENCES_POSITION = 1;
}
public static NewsCategoriesFragment newInstance(final FragmentManager manager, final int categoryCodePosition) {
final NewsCategoriesFragment fragment = new NewsCategoriesFragment();
mSelectedCategoryCodePosition = categoryCodePosition;
final FragmentInfo fragmentInfo = new FragmentInfo(TransactionMethods.ADD, R.id.header_container);
fragmentInfo.setFragmentTag(TAG_NEWS_CATEGORIES_FRAGMENT);
fragmentInfo.doNotAddToBackStack();
fragmentInfo.setAnimation(R.anim.no_animation, R.anim.no_animation);
fragmentInfo.setPopAnimation(R.anim.no_animation, R.anim.no_animation);
FragmentStackManager.getInstance().transitionFragment(manager, fragment, fragmentInfo);
return fragment;
}
@Override
public View onCreateView(final LayoutInflater inflater, final ViewGroup container, final Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.fragment_news_categories, container, false);
headerView = (HeaderView) view.findViewById(R.id.news_categories_container);
headerView.setContextMenuOnClickListener(this);
mMyNewsLoader.onCreate(getActivity());
createMenu();
return view;
}
private void createMenu() {
mMenuItems.add(MenuItems.MANAGE_NEWS_CATEGORIES);
mMenuItems.add(MenuItems.NEWS_PREFERENCES);
mMenuHelper = new MenuHelper(getActivity(), mMenuItems,this,this);
}
@Override
public void onViewCreated(final View view, final Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mFirstTimeLoadingNonMyNews = true;
mFirstTimeLoadingMyNews = true;
mMyNewsLoader.initLoader();
}
@Override
public void onDestroyView() {
super.onDestroyView();
mMyNewsLoader.onDestroy();
}
@Override
public Uri onCreateContentUri() {
final Uri baseUri = NewsContentProvider.USER_CATEGORIES_URI;
final Builder builder = baseUri.buildUpon().appendQueryParameter(UserCategory.QueryParams.SHORT_LIST, String.valueOf(true));
return builder.build();
}
@Override
public void onCursorLoaded(final Uri uri, final Cursor cursor) {
Log.d("CategoryIssue", "News - CursorLoaded");
if (!mFirstTimeLoadingNonMyNews || cursor.getCount() > 0 || !isOperationExecuting()) {
Log.d("CategoryIssue", "News - CursorLoaded with count " + cursor.getCount());
PrecacheManager.getInstance().saveNonMyNewsCategoriesForCaching(cursor, mSelectedCategory);
populateCategoryRows(cursor);
mHasNonMyNewsCategoriesLoaded = true;
if (mHasMyNewsCategoriesLoaded) {
Log.d("CategoryIssue", "News - CursorLoaded showing results");
showResults(uri);
}
}
if (mFirstTimeLoadingNonMyNews) {
mFirstTimeLoadingNonMyNews = false;
}
}
@Override
public void onOperationError(Uri uri, RestError error) {
super.onOperationError(uri, error);
mHasNonMyNewsCategoriesLoaded = true;
if (mHasMyNewsCategoriesLoaded) {
showResults(uri);
}
}
private void updateCategorySpinner() {
mCategoryAdapter.updateTopNewsRows(mTopNewsRows);
mCategoryAdapter.updateBreakinViewsRows(mBreakingViewsRows);
if (mMyNewsRows == null || mMyNewsRows.size() <= 1) {
mCategoryAdapter.removeMyNews();
} else {
mCategoryAdapter.updateMyNewsRows(mMyNewsRows);
}
}
private void initCategorySpinner() {
mCategoryAdapter = new NewsCategorySpinnerAdapter(getActivity(), mTopNewsRows, mBreakingViewsRows, mMyNewsRows,mMostReadNewsRows);
headerView.setSpinnerAdapter(mCategoryAdapter);
headerView.setSpinnerOnItemSelectedListener(this);
headerView.setSpinnerSelectedItemPosition(mSelectedCategoryCodePosition);
}
@Override
public void showResults(final Uri uri) {
LayoutUtils.showResults(getView(), headerView.getSpinnerId());
if (mCategoryAdapter == null) {
Log.d("CategoryIssue", "init spinner");
initCategorySpinner();
} else {
Log.d("CategoryIssue", "update spinner");
updateCategorySpinner();
}
}
@Override
public void showNoResults(final Uri uri) {
LayoutUtils.showNoResult(getView(), headerView.getSpinnerId());
}
@Override
public void onClick(final View view) {
switch (view.getId()) {
case R.id.context_menu_button:
final int actionBarHeight = getActivity().findViewById(R.id.title_main_container).getHeight();
mMenuHelper.showMenu(getView().getBottom() + actionBarHeight, Gravity.RIGHT);
BangoHelper.eventSettings();
if (headerView.isSelected()) {
headerView.setSelected(false);
Log.i("ImageButtonCheck", "Button is not selected anymore");
} else {
headerView.setSelected(true);
Log.i("ImageButtonCheck", "Button is in selected state");
}
break;
default:
break;
}
}
private void populateCategoryRows(final Cursor cursor) {
final Resources resources = getView().getResources();
mTopNewsRows = new ArrayList<AdapterRow>();
String categoryTitle = resources.getString(R.string.title_top_news);
mTopNewsRows.add(new CategoryHeader(categoryTitle));
mBreakingViewsRows = new ArrayList<AdapterRow>();
categoryTitle = resources.getString(R.string.title_breakingviews);
if(SharedPreferencesManager.getInstance().isLiteUser()){
}else{
mBreakingViewsRows.add(new CategoryHeader(categoryTitle));
}
cursor.moveToPosition(-1);
if(Locale.getDefault().toString().equals("ja_JP")){
final String categoryName = Application.getAppResources().getString(R.string.news_category_constant_japanese);
final String categoryCode = "urn:newsml:reuters.com:20090527:SPDOC_1323242720091";
mTopNewsRows.add(new SpinnerCategoryRow(categoryName, categoryCode, Type.TOP_NEWS));
} else if(Locale.getDefault().toString().equals("zh_CN")){
final String categoryName = Application.getAppResources().getString(R.string.news_category_constant_chinese);
final String categoryCode = "urn:newsml:reuters.com:20100623:SPDOC_1331612320101";
mTopNewsRows.add(new SpinnerCategoryRow(categoryName, categoryCode, Type.TOP_NEWS));
}
while (cursor.moveToNext()) {
final String navGroup = cursor.getString(cursor.getColumnIndex(NewsCategory.Columns.NAVIGATION_GROUP));
final String categoryName = cursor.getString(cursor.getColumnIndex(NewsCategory.Columns.NAME));
final String categoryCode = cursor.getString(cursor.getColumnIndex(NewsCategory.Columns.CODE));
if (NewsCategory.Constants.BREAKINGVIEWS.equals(navGroup)) {
mBreakingViewsRows.add(new SpinnerCategoryRow(categoryName, categoryCode, Type.BREAKINGVIEWS));
} else {
mTopNewsRows.add(new SpinnerCategoryRow(categoryName, categoryCode, Type.TOP_NEWS));
}
}
}
private final ContentLoader mMyNewsLoader = new ContentLoader() {
@Override
public Uri onCreateContentUri() {
final Builder builder = PreferencesContentProvider.MY_NEWS_CATEGORIES_CONTENT_URI.buildUpon();
builder.appendQueryParameter(MyNewsCategory.QueryParams.SELECTED_ONLY, String.valueOf(true));
return builder.build();
};
@Override
public void onOperationError(final Uri uri, final RestError error) {
super.onOperationError(uri, error);
mHasMyNewsCategoriesLoaded = true;
if (mHasNonMyNewsCategoriesLoaded) {
showResults(uri);
}
};
@Override
public void onCursorLoaded(final Uri uri, final Cursor cursor) {
if (!mFirstTimeLoadingMyNews || cursor.getCount() > 0 || !isOperationExecuting()) {
PrecacheManager.getInstance().saveMyNewsCategoriesForCaching(cursor, mSelectedCategory);
populateMyNewsCateogryRows(cursor);
mHasMyNewsCategoriesLoaded = true;
if (mHasNonMyNewsCategoriesLoaded) {
showResults(uri);
}
if (cursor.getCount() == 0) {
if (mCategoryAdapter != null) {
mCategoryAdapter.removeMyNews();
}
}
}
if (mFirstTimeLoadingMyNews) {
mFirstTimeLoadingMyNews = false;
}
}
private void populateMyNewsCateogryRows(final Cursor cursor) {
mMyNewsRows = new ArrayList<AdapterRow>();
mMyNewsRows.add(new CategoryHeader(getView().getResources().getString(R.string.title_my_news)));
cursor.moveToPosition(-1);
while (cursor.moveToNext()) {
final String categoryCode = cursor.getString(cursor.getColumnIndex(MyNewsCategory.Columns.FILE_NAME));
final String categoryName = cursor.getString(cursor.getColumnIndex(MyNewsCategory.Columns.NAME));
mMyNewsRows.add(new SpinnerCategoryRow(categoryName, categoryCode, Type.MY_NEWS));
}
};
};
@Override
public void onMenuItemClicked(final int position) {
switch (position) {
case MenuItems.MANAGE_NEWS_CATEGORIES_POSITION:
ManageNewsCategoriesActivity.newInstance(getActivity());
break;
case MenuItems.NEWS_PREFERENCES_POSITION:
NewsPreferencesActivity.newInstance(getActivity());
break;
default:
break;
}
headerView.setSelected(false);
mMenuHelper.hideMenu();
}
@Override
public void onItemSelected(IcsAdapterView<?> parent, View view, int position, long id) {
final SpinnerCategoryRow item = (SpinnerCategoryRow) parent.getItemAtPosition(position);
final NewsFragment parentFragment = (NewsFragment) getParentFragment();
mSelectedCategory = item.getCategoryCode();
if (item.getCategoryType() == Type.MY_NEWS) {
parentFragment.onMyNewsSelected(mSelectedCategory);
parentFragment.onCategoryPositionSelected(position);
} else {
parentFragment.onCategorySelected(mSelectedCategory);
parentFragment.onCategoryPositionSelected(position);
}
parentFragment.dismissPullToRefresh();
}
@Override
public void onDismiss(DialogInterface dialog) {
headerView.setSelected(false);
}
@Override
public void onNothingSelected(IcsAdapterView<?> parent) {
}
}
另外,请告诉我是否应该添加适配器和活动的代码以进一步解释它,但我认为只有片段应该足够了,但我可能是错的
添加spinneradapter:
public class NewsCategorySpinnerAdapter extends CustomRowAdapter<AdapterRow> {
private List<AdapterRow> mTopNewsRows;
private List<AdapterRow> mBreakingViewsRows;
private List<AdapterRow> mMyNewsRows;
private List<AdapterRow> mRenderList;
public NewsCategorySpinnerAdapter(final Context context, final List<AdapterRow> topNewsRows, final List<AdapterRow> breakingViewsRows, final List<AdapterRow> myNewsRows) {
super(context);
mTopNewsRows = topNewsRows;
mBreakingViewsRows = breakingViewsRows;
mMyNewsRows = myNewsRows;
mRenderList = new ArrayList<AdapterRow>();
mRenderList.addAll(topNewsRows);
mRenderList.addAll(breakingViewsRows);
//mRenderList.addAll(myNewsRows);
if (myNewsRows != null && myNewsRows.size() > 0) {
mRenderList.addAll(myNewsRows);
}
if (mostReadNewsRows != null && mostReadNewsRows.size() > 0) {
mRenderList.addAll(mostReadNewsRows);
}
}
@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);
}
public void updateTopNewsRows(final List<AdapterRow> topNewsRows) {
if (mTopNewsRows != null) {
mTopNewsRows = topNewsRows;
recontructRenderList();
} else {
getEntries().addAll(topNewsRows);
}
notifyDataSetChanged();
}
public void updateBreakinViewsRows(final List<AdapterRow> breakingViewsRows) {
if (mBreakingViewsRows != null) {
mBreakingViewsRows = breakingViewsRows;
recontructRenderList();
} else {
getEntries().addAll(breakingViewsRows);
}
notifyDataSetChanged();
}
public void updateMyNewsRows(final List<AdapterRow> myNewsRows) {
if (mMyNewsRows != null) {
mMyNewsRows = myNewsRows;
recontructRenderList();
} else {
getEntries().addAll(myNewsRows);
}
notifyDataSetChanged();
}
private void recontructRenderList() {
getEntries().clear();
addSection(mTopNewsRows);
addSection(mBreakingViewsRows);
addSection(mMyNewsRows);
}
private void addSection(final List<AdapterRow> section) {
if (section != null && !section.isEmpty()) {
getEntries().addAll(section);
}
}
public void removeMyNews() {
if (ArrayUtils.isNotEmpty(mMyNewsRows)) {
mRenderList.removeAll(mMyNewsRows);
mMyNewsRows = null;
notifyDataSetChanged();
}
}
}
}
答案 0 :(得分:1)
在onItemSelected()方法中使用此代码并保存所选值的微调器的位置:
int Choice = spinner.getSelectedItemPosition();
SharedPreferences sharedPref = getSharedPreferences("FileName",0);
SharedPreferences.Editor prefEditor = sharedPref.edit();
prefEditor.putInt("spinnerChoice",Choice);
prefEditor.commit();
从sharedPreferences设置选项:
SharedPreferences sharedPref = getSharedPreferences("FileName",MODE_PRIVATE);
int spinnerValue = sharedPref.getInt("spinnerChoice",-1);
if(spinnerValue != -1)
spinner.setSelection(spinnerValue);
答案 1 :(得分:0)
使用此选项获取所选字符串:
String text = spinner.getSelectedItem().toString();
这是在项目被删除后再次设置微调器:
ArrayAdapter myAdap = (ArrayAdapter) spinner.getAdapter();
int spinnerPosition = myAdap.getPosition(text);
spinner.setSelection(spinnerPosition);
答案 2 :(得分:0)
你可以在共享偏好上保存选定的项目文本(你知道怎么做,所以我不再说了)。然后单击“添加”按钮并将新的String添加到数组中调用:
spinner.setSelection(yourArrayList.indexOf("yourPreviusNameThatRetriveFromSharedPreference"));
答案 3 :(得分:0)
您可以在SharedPreference中保存最后选择的位置,并在用户单击微调器时保存,而不是设置spinner.setSelection(position)。它保存在您的SharedPreference中。这是解决此问题的唯一解决方案。