我创建了一个图片库应用程序。
我的要求:当我在 Activity (PhotosActivity.java)中单击buttoncut时,buttonpaste应该变得可见,并且当我返回到另一个 Activity (ImageGallery.java)时它应该保持可见,以便我可以使用它将图片移动到另一个文件夹。
发生了什么:当我点击 buttoncut(PhotosActivity.java) 时,buttonpaste 变得可见,但当我返回到任何其他 Activity (ImageGallery.java) 时,它就会消失。
我尝试了一些代码,但它不起作用。我该如何解决它?
PhotosActivity.java
Intent intent = new Intent(PhotosActivity.this, ImageGallery.class);
intent.putExtra(EXTRA_IS_CORRECT, true);
startActivity(intent);
ImageGallery.java
Intent startingIntent = getIntent();
boolean isCorrect = startingIntent.getBooleanExtra(PhotosActivity.EXTRA_IS_CORRECT, false);
if(isCorrect) {
final ImageButton buttonpaste = (ImageButton) findViewById(R.id.buttonpaste);
buttonpaste.setVisibility(View.VISIBLE);
}
最佳答案
but when I go back to any other activity(ImageGallery.java), it disappears
因为当你“回去”时你有不同的Intent。如果您想保持可见性,您可能应该使用 SharedPreferences
。
例如
ImageButton buttonpaste = (ImageButton) findViewById(R.id.buttonpaste);
SharedPreferences prefs = getSharedPreferences("prefs" Context.MODE_PRIVATE);
boolean isCorrect = getIntent().getBooleanExtra(PhotosActivity.EXTRA_IS_CORRECT, false);
SharedPreferences.Editor e = prefs.edit();
if(isCorrect || prefs.getBoolean(PhotosActivity.EXTRA_IS_CORRECT,false)) {
buttonpaste.setVisibility(View.VISIBLE);
e.putBoolean(PhotosActivity.EXTRA_IS_CORRECT, true);
e.apply();
}
关于java - 无法使按钮从另一个 Activity 中可见,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48107561/