【问题标题】:Setting up the visibility of an Image View depending on Shared Preferences根据共享首选项设置图像视图的可见性
【发布时间】:2017-12-28 09:05:08
【问题描述】:

我编写了一个测验应用程序。我已经设置了,如果高分超过 10,ImageView 将永久显示。这在应用程序重新启动时也能正常工作,唯一的问题是,如果用户达到例如 11 的高分,然后在测验开始时直接回答正确然后错误,ImageView 就会消失。共享首选项位于 Main Activity(测验活动)中,将在 Menu2(第二个 Activity)中调用。

测验活动java:

       @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_quiz);


    //Randromizes the row of the questions
    QuestionLibrary q = new QuestionLibrary();
    System.out.printf("Question:0 Choice:(%s, %s, %s) Answer:%s%n",
            q.getChoice1(0), q.getChoice2(0), q.getChoice3(0), q.getCorrectAnswer(0));
    q.shuffle();
    System.out.printf("Question:0 Choice:(%s, %s, %s) Answer:%s%n",
            q.getChoice1(0), q.getChoice2(0), q.getChoice3(0), q.getCorrectAnswer(0));
    mQuestionLibrary.shuffle();
    //End randomizer

    //We need this for the NAVIGATION DRAWER
    mToolbar = (Toolbar) findViewById(R.id.nav_action);

    setSupportActionBar(mToolbar);

    mDrawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);

    mToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.open, R.string.close);
    mDrawerLayout.addDrawerListener(mToggle);
    mToggle.syncState();
    getSupportActionBar().setDisplayHomeAsUpEnabled(true); //Able to see the Navigation Burger "Button"


    NavigationView mNavigationView = (NavigationView) findViewById(R.id.nv1);
    mNavigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener(){
        @Override
        public boolean onNavigationItemSelected(MenuItem menuItem){
            switch (menuItem.getItemId()){
                case(R.id.nav_stats): //If nav stats selected Activity 2 will show up
                    Intent accountActivity = new Intent(getApplicationContext(),Menu2.class);
                    startActivity(accountActivity);
            }
            return true;
        }
    });

        //Initialise

        mScoreView = (TextView) findViewById(R.id.score_score);
        mQuestionView = (TextView) findViewById(R.id.question);
        mButtonChoice1 = (Button) findViewById(R.id.choice1);
        mButtonChoice2 = (Button) findViewById(R.id.choice2);
        mButtonChoice3 = (Button) findViewById(R.id.choice3);


        updateQuestion(); //New question appears

        //Start of Button Listener1 -> if true, next question appears +score +1[] Else menu 2 will show
        mButtonChoice1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //My logic for Button goes in here

                if (mButtonChoice1.getText() == mAnswer) {
                    mScore = mScore + 1;
                    updateScore(mScore);
                    updateQuestion();



                    //This line of code is optional...
                    Toast.makeText(QuizActivity.this, "Correct", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(QuizActivity.this, "Wrong... Try again!", Toast.LENGTH_SHORT).show();


                    Intent intent = new Intent(QuizActivity.this, Menu2.class);
                    intent.putExtra("score",mScore); //pass score to Menu2
                    startActivity(intent);




                }
            }


        });
        //End of Button Listener1

        //Start of Button Listener2
        mButtonChoice2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //My logic for Button goes in here

                if (mButtonChoice2.getText() == mAnswer) {
                    mScore = mScore + 1;
                    updateScore(mScore);
                    updateQuestion();




                    //This line of code is optional...
                    Toast.makeText(QuizActivity.this, "Correct", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(QuizActivity.this, "Oh... wrong your score is 0", Toast.LENGTH_SHORT).show();

                    Intent intent = new Intent(QuizActivity.this, Menu2.class);
                    intent.putExtra("score",mScore); //pass score to Menu2
                    startActivity(intent);




                }
            }


        });
        //End of Button Listener2

        //Start of Button Listener3
        mButtonChoice3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //My logic for Button goes in here

                if (mButtonChoice3.getText() == mAnswer) {
                    mScore = mScore + 1;
                    updateScore(mScore);
                    updateQuestion();




                    //This line of code is optional...
                    Toast.makeText(QuizActivity.this, "Correct", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(QuizActivity.this, "Come on, that was not so hard...", Toast.LENGTH_SHORT).show();

                    Intent intent = new Intent(QuizActivity.this, Menu2.class);
                    intent.putExtra("score",mScore); //pass score to Menu2
                    startActivity(intent);




                }
            }


        });
        //End of Button Listener3

    }


    private void updateQuestion() {
    //If the max. number of questions is reached, menu2 will be open if not  
    //a  new quiz selection appears
    if (mQuestionNumber < mQuestionLibrary.getLength()) {

    mQuestionView.setText(mQuestionLibrary.getQuestion(mQuestionNumber));

    mButtonChoice1.setText(mQuestionLibrary.getChoice1(mQuestionNumber));

    mButtonChoice2.setText(mQuestionLibrary.getChoice2(mQuestionNumber));

    mButtonChoice3.setText(mQuestionLibrary.getChoice3(mQuestionNumber));

        mAnswer = mQuestionLibrary.getCorrectAnswer(mQuestionNumber);
        mQuestionNumber++;
    }
    else {
        Toast.makeText(QuizActivity.this, "Last Question! You are very intelligent!", Toast.LENGTH_SHORT).show();
        Intent intent = new Intent(QuizActivity.this, Menu2.class);
        intent.putExtra("score",mScore); //pass score to Menu2
        startActivity(intent);


    }

}

private void updateScore ( int point){
    mScoreView.setText("" + mScore);
    //Shared preferences = a variabe (mScore) gets saved and call up in another activity
    SharedPreferences sharedpreferences = getSharedPreferences("mypref", Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = sharedpreferences.edit();
    editor.putInt("currentscore", mScore);
    editor.apply();
}

    @Override //Makes that the "Burger" Item, shows the Drawer if someone clicks on the simbol
    public boolean onOptionsItemSelected (MenuItem item){
        if (mToggle.onOptionsItemSelected(item)) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

}

菜单 2:

      public class Menu2 extends AppCompatActivity {




private DrawerLayout mDrawerLayout2;
private ActionBarDrawerToggle mToggle;
private Toolbar mToolbar;
private Button popup;
private PopupWindow popupWindow;private LayoutInflater layoutInflater; //Alows to add a new layout in our window



@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_menu2);

    SharedPreferences sharedpreferences = getSharedPreferences("mypref", Context.MODE_PRIVATE);
    int applyView =sharedpreferences.getInt("currentscore",0);
     TextView txtScore = (TextView) findViewById(R.id.textScore2);
     TextView txtHighScore = (TextView)findViewById(R.id.textHighScore);
     ImageView imgTrophyView1 = (ImageView)findViewById(R.id.trophy1);
     ImageView imgTrophyView2 = (ImageView) findViewById(R.id.trophy2);
     Button bttPOPUP =(Button)findViewById(R.id.enablePOPUP);

    Intent intent = getIntent();
    int mScore = intent.getIntExtra ("score",0);
    txtScore.setText("Your score is: " + mScore);




    SharedPreferences mypref =getPreferences(MODE_PRIVATE);
    int highScore = mypref.getInt("highScore", 0);
    if (highScore>= mScore)
        txtHighScore.setText("High score: " + highScore);


    else{
        txtHighScore.setText("New highscore: " + mScore);

        SharedPreferences.Editor editor = mypref.edit();
        editor.putInt("highScore",mScore);
        editor.apply();

    }

    if (applyView >=10) {
        imgTrophyView1.setVisibility(View.VISIBLE);
        bttPOPUP.setVisibility(View.VISIBLE);
    }
        if (applyView >= 20){
            imgTrophyView2.setVisibility(View.VISIBLE);

    }


    popup = (Button)findViewById(R.id.enablePOPUP);
    popup.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            layoutInflater =(LayoutInflater) getApplicationContext().getSystemService(LAYOUT_INFLATER_SERVICE);
            ViewGroup container = (ViewGroup)layoutInflater.inflate(R.layout.popup_menu2_1,null);
            popupWindow = new PopupWindow(container,1000,980,true); //400,400=popUp size, true = makes that we can close the pop up by simply click out of the window
            popupWindow.showAtLocation(mDrawerLayout2, Gravity.CENTER, 0, 0);
            mDrawerLayout2.setAlpha((float) 0.1);

            container.setOnTouchListener(new View.OnTouchListener(){

                @Override

                        public boolean onTouch(View view, MotionEvent motionEvent  ){
                        mDrawerLayout2.setAlpha((float) 1);
                              popupWindow.dismiss();

                        return true;

                }

            });


            popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {

                @Override
                public void onDismiss() {
                    mDrawerLayout2.setAlpha((float) 1);
                    popupWindow.dismiss();

                }
            });
        }
    });





    mToolbar = (Toolbar)findViewById(R.id.nav_action);
    setSupportActionBar(mToolbar);
    mDrawerLayout2 = (DrawerLayout) findViewById(R.id.drawerLayout2);

    mToggle = new ActionBarDrawerToggle(this, mDrawerLayout2, R.string.open, R.string.close);
    mDrawerLayout2.addDrawerListener(mToggle);
    mToggle.syncState();
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    NavigationView mNavigationView = (NavigationView) findViewById(nv2);
    mNavigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {

        @Override
        public boolean onNavigationItemSelected(MenuItem menuItem){
            switch (menuItem.getItemId()){
                case(R.id.nav_home2):
                    Intent accountActivity2 = new Intent(getApplicationContext(),QuizActivity.class);
                    startActivity(accountActivity2);

            }
            return true;
        }
    });}

            public void onClick(View view) {

                Intent intent = new Intent(Menu2.this, QuizActivity.class);
                startActivity(intent);

}




@Override //Makes that the "Burger" Item, shows the Drawer if someone clicks on the simbol
public boolean onOptionsItemSelected(MenuItem item) {
    if (mToggle.onOptionsItemSelected(item)) {
        return true;
    }
    return super.onOptionsItemSelected(item);


}

}

【问题讨论】:

    标签: java android uiimageview sharedpreferences visibility


    【解决方案1】:

    在您的updateScore 中,无论分数是多少,您都在保存数据,因此您删除旧值并用新值更改它,因此您需要读取旧分数并将其与 mScore 进行比较,如下所示:

    SharedPreferences mypref =getPreferences(MODE_PRIVATE);
    int highScore = mypref.getInt("highScore", 0);
    if(mScore> highScore){
        SharedPreferences.Editor editor = mypref.edit();
        editor.putInt("currentscore", mScore);
        editor.apply();
    }
    

    【讨论】:

    • 您好!我必须在哪里插入这个?
    • 我把它插入到updateScore下但是现在连图片都没有出现...
    • 你好,他的作品只有在我达到例如分数 10 并且直接在我达到 fx 分数之后。 1 然后它永久休息..我希望它在“达到”高分时已经出现
    【解决方案2】:

    发生这种情况是因为您有以下代码

    if (applyView >=10) {
        imgTrophyView1.setVisibility(View.VISIBLE);
        bttPOPUP.setVisibility(View.VISIBLE);
    }
        if (applyView >= 20){
            imgTrophyView2.setVisibility(View.VISIBLE);
    
    }
    

    这会检查“currentScore”,因此如果用户在第二次播放时只找到 1 个答案,那么它将是 1,因此图像不会显示。 我注意到你有一个当前分数的 sharedPref 并且你也有意通过它。您还有另一个 sharedPref 吗?我的建议是只通过意图,然后检查它是否是高分,然后将其保存到 sharedPref。并且只有一个 sharedPref。

    编辑

    从 updateScore 中删除下面的代码

    SharedPreferences sharedpreferences = getSharedPreferences("mypref", Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = sharedpreferences.edit();
    editor.putInt("currentscore", mScore);
    editor.apply();
    

    然后删除/编辑您在菜单 2 中的所有共享首选项代码,如下所示

    SharedPreferences sharedpreferences = getSharedPreferences("mypref", Context.MODE_PRIVATE);
    
    //first time high score
    if (sharedPreferences.getInt("highScore", 0) == 0)
    {
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putInt("highScore", mScore );
        editor.apply();
    }
    else
    {
        int oldScore = sharedPreferences.getInt("highScore", 0);
    
        //new high score
        if (mScore  > oldScore)
        {
            SharedPreferences.Editor editor = sharedPreferences.edit();
            editor.putInt("highScore", mScore );
            editor.apply();
        }
    }
    

    【讨论】:

    • 您好!先生,我必须在哪里插入此代码?在菜单 2 中?我必须删除一些东西吗?
    • 是的,您必须从 QuizActivity 中删除 updateScore,因为您通过意图传递分数,然后在其他活动中编辑 sharedPref 代码。或者将 Menu2 中的 apllyView 更改为 highScore
    • 所以我必须在测验活动和 Menu2 中删除更新分数,我必须插入哪些代码?先生,我不知道在哪里输入此代码
    • 当我删除更新分数时,在部分更新分数上的按钮侦听器上是错误无法解决 simbol..
    • 您好,我发现了一个解决方案,只是它不能完美地工作。你也能帮帮我吗?答案就在你的 Oussema 上
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-05
    • 2021-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多