如果语句给出条件总是为真 [英] If statement gives condition is always true
问题描述
当我使用 if
语句时,它告诉我条件 x 始终为真,尽管我在另一个应用程序中使用相同的代码并且它有效,但在这种情况下我在 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);
}
}
推荐答案
绕过比较运算符错误 =
而不是 ==
(==
> 是正确的,请更新您的代码),这是从其他答案中解决的,您的程序流程导致永远不会到达(至少是用户体验部分)您设置 x
的部分if
语句中的 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屋!