【发布时间】:2015-07-04 21:16:26
【问题描述】:
这是我的代码,当我的应用再次打开时,我需要在屏幕上显示最后一个字符串和字符串编号。感谢您的帮助。
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
String [] tabela;
TextView textView;
TextView textView2;
TextView textView3;
Button next, prev;
int index;
SharedPreferences sPref;
SharedPreferences.Editor editor;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sPref = getSharedPreferences("daniel.myapplication", Context.MODE_PRIVATE);
editor = sPref.edit();
// Importing the string array from Valuses folder
tabela = getResources().getStringArray(R.array.array);
// initialization of textview
textView =(TextView)findViewById(R.id.textView);
textView2 =(TextView)findViewById(R.id.textView2);
textView3 =(TextView)findViewById(R.id.textView3);
//Initialization of buttons
next =(Button)findViewById(R.id.button);
prev =(Button)findViewById(R.id.button2);
//OnClickListener for buttons
next.setOnClickListener(this);
prev.setOnClickListener(this);
// Setting values for our variable and textviews
index = 0;
textView.setText(tabela[index]);
textView2.setText(String.valueOf(index+1));
textView3.setText("/"+String.valueOf(tabela.length));
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.button2:
index++;
if (index==tabela.length){
index=0;
textView.setText(tabela[index]);
textView2.setText(String.valueOf(index+1));
}else {
textView.setText(tabela[index]);
textView2.setText(String.valueOf(index + 1));
}
break;
case R.id.button:
index--;
if (index ==-1){
index = tabela.length -1;
textView.setText(tabela[index]);
textView2.setText(String.valueOf(index+1));
}else {
textView.setText(tabela[index]);
textView2.setText(String.valueOf(index + 1));
}
break;
}
}
}
【问题讨论】:
-
在请其他人编写代码之前,自己尝试问题或多阅读一些内容。尝试使用MCVE 重新表述问题以结构化
-
您创建了一个 sharedPreference 但没有使用它。我建议将值保存在 onPause 中,然后在 onCreate 中再次加载
-
对不起,我没有提到我正在尝试使用 sharedPreferences 并删除了不起作用的代码,因为我说我是编程新手,如果有人可以告诉我如何在这种情况下使用共享首选项,它会很棒
-
您可以使用 BranMoney 答案作为参考,然后可以检查我在答案中所做的更改,我也应该建议在 developer.android.com/reference/android/content/… 正确阅读