我有一个微调器,其元素保存在sharedPrefrences中。当我从微调器中选择任何元素并单击“保存”按钮时,它将将该元素保存在sharedPref中,并且每当我回到此活动时,就会选择与我选择并保存的元素相同的微调器。当我关闭我的应用程序并将其从手机中当前正在运行的应用程序中删除时,就会出现问题。在这种情况下,当我打开我的应用程序并转到该活动时,将使用第0个元素选择微调器。我从sharedPref获取保存的元素,但未调用getPosition()。为什么会这样呢?
这是我的方法:
public boolean setBranchIds(ArrayList<String> tdBrlist) {
try {
branchList = tdBrlist;
runOnUiThread(new Runnable() {
@Override
public void run() {
branchSpinner = new Spinner(Activity_Settings.this);
TableRow.LayoutParams tdpid_spinner_params = new TableRow.LayoutParams(
0, LayoutParams.WRAP_CONTENT, 3f);
branchSpinner.setLayoutParams(tdpid_spinner_params);
branchRow.addView(branchSpinner);
branchSpinner.setPrompt("Select Branch");
if (branchList.size() > 0) {
ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<String>(
Activity_Settings.this,
android.R.layout.simple_spinner_item,
branchList);
branchSpinner.setAdapter(spinnerAdapter);
String branch = mActivity.getSharedPreferences(
Utility.PREFERENCE_NAME, Context.MODE_PRIVATE)
.getString(Utility.BRANCH, "");
System.out.println("====branch===: "+branch);
if (!branch.equals("")) {
branchIndex = getIndex(branch);
System.out.println("=====positionbranch:
"+branchIndex);
branchSpinner.setSelection(branchIndex);
}
}
}
});
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
private int getIndex(String branch) {
for (int i = 0; i < branchList.size(); i++) {
if (branchList.get(i).equalsIgnoreCase(branch)) {
System.out.println("======i: "+i);
return i;
}
}
return -1;
}
LogCat值:
12-17 13:50:51.502: I/System.out(13229): ====branch===: B1
12-17 13:50:51.502: I/System.out(13229): ====branchlist===: [Select, B1, B2,
B3,B4]
12-17 13:50:51.502: I/System.out(13229): ======i: 1
12-17 13:50:51.502: I/System.out(13229): =====positionbranch: 1
我返回时的LogCat值:
12-17 13:53:10.932: I/System.out(14895): ====branch===: B1
12-17 13:53:10.932: I/System.out(14895): ====branchlist===: [Select, B1, B2
, B3, B4]
12-17 13:53:10.932: I/System.out(14895): =====positionbranch: -1
最佳答案
可能您需要替换:
int branchIndex = pinnerAdapter.getPosition(branch);
branchSpinner.setSelection(branchIndex);
有了这个:
branchSpinner.setSelection(list.indexOf(branch));