如果语句给出条件始终为真 [英] If statement gives condition is always true

查看:191
本文介绍了如果语句给出条件始终为真的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我使用if语句时,它使我知道条件x始终为true,尽管我在另一个应用程序中使用了相同的代码并且它可以工作,但是在这种情况下,我在菜单的onOptionsItemSelected方法中使用了它,所以有人可以帮忙吗?

When I use if statement it gives me that the condition x is always true although I use the same code in another app and it works, but in this case I use it in onOptionsItemSelected method for my menu ,So can someone help ?

public class Wellcome extends AppCompatActivity
    implements NavigationView.OnNavigationItemSelectedListener {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_wellcome);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

        }

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.chang_language, menu);
    return true;
}
 Boolean x=true;
@Override
public boolean onOptionsItemSelected(MenuItem item) {
   int id = item.getItemId();
   if (id == R.id.arabic) {
       if (x =true) {
           setLocale("en");
           x = false;
       } else  if (x =false) {
           setLocale("ar");
           x = true;
       }
     return true;
   }
    return super.onOptionsItemSelected(item);
}
public void setLocale(String lang) {
    java.util.Locale myLocale = new Locale(lang);
    DisplayMetrics dm = getResources().getDisplayMetrics();
    Configuration conf = getResources().getConfiguration();
    conf.locale = myLocale;
    getResources().updateConfiguration(conf, dm);
    Intent refresh = new Intent(this, Wellcome.class);
    startActivity(refresh);
       }
     }

推荐答案

绕过比较运算符错误=而不是==(==是正确的,请更新您的代码),该问题已从另一个地方解决答案是,程序的流程永远不会到达(至少是用户体验部分)在if语句中将x变量设置为false的部分.

Bypassing the comparison operator error = instead of == (== is the correct, please update your code), which is addressed from the other answers, the flow of your program leads to never reach (at least the user experience part) the part where you set the x variable to false in the if statement.

setLocale("en");
x = false; // -> this part is not reached because you start a new activity of the same class in the setLocale above

更具体地说,在onOptionsItemSelected方法中调用的setLocale方法通过以下代码重新开始活动:

More specifically, the setLocale method which is called in the onOptionsItemSelected method, restarts your activity via the following code:

Intent refresh = new Intent(this, Wellcome.class);
startActivity(refresh);

由于Wellcome活动是从refresh意图开始的,因此新的Wellcome活动会显示在旧活动的顶部,当然,新活动的字段变量x将被实例化为true

Since the Wellcome activity is started from the refresh intent, a new Wellcome activity appears on top of the old one, and of course this new activity's field variable x will be instantiated to true,

Boolean x=true;

这篇关于如果语句给出条件始终为真的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆