【问题标题】:not able to set visibilty of a button using shared preferences无法使用 sharedpreferences 设置按钮的可见性
【发布时间】:2018-01-06 15:19:17
【问题描述】:

我创建了一个图片库应用。

我的要求:当我在一个活动(PhotosActivity.java)中单击按钮时,按钮粘贴应该变得可见,并且当我返回另一个活动(ImageGallery.java)时它应该保持可见,以便我可以将它用于移动图片到另一个文件夹。此外,buttonpaste 只有在我单击 buttoncut 时才可见,并且在我第一次打开第一个活动 (Imagegallery.java) 时它应该是不可见的。

发生了什么:当我第一次打开第一个活动 (Imagegallery.java) 时,buttonpaste 已经可见。其他一切正常。

我尝试了一些代码,但它不起作用。我该如何解决?

PhotosActivity.java

    SharedPreferences preferences = getSharedPreferences("sample",Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = preferences.edit();
    editor.putBoolean("Name",true);
    editor.apply();
    Intent intent = new Intent(PhotosActivity.this,ImageGallery.class);
    startActivity(intent);

ImageGallery.java

 final ImageButton buttonpaste = (ImageButton) findViewById(R.id.buttonpaste);
        buttonpaste.setVisibility(View.GONE);

        SharedPreferences preferences = getSharedPreferences("sample",Context.MODE_PRIVATE);
        boolean Namestr=(preferences.getBoolean("Name",true));
        if(Namestr){
            buttonpaste.setVisibility(View.VISIBLE);
        }

【问题讨论】:

标签: java android android-intent sharedpreferences


【解决方案1】:

看看这一行:

boolean Namestr=(preferences.getBoolean("Name",true)); 

因此,如果您没有向SharedPreferences 写入任何带有“名称”键的内容,则默认值为true。这意味着buttonPaste 默认是可见的。要更改此设置,您必须将 false 设置为默认值:

boolean Namestr=(preferences.getBoolean("Name",false)); 

【讨论】:

    猜你喜欢
    • 2011-09-02
    • 2020-06-12
    • 2012-01-20
    • 1970-01-01
    • 2023-03-16
    • 1970-01-01
    • 1970-01-01
    • 2016-07-09
    • 2013-11-30
    相关资源
    最近更新 更多