这是我在这里发布的第一个问题,所以我希望我已经彻底和清楚地解释了我所遇到的问题。任何/所有帮助将不胜感激。
以下是我正在处理的java文件:
MainActivity.java
public class MainActivity extends AppCompatActivity {
ImageButton name1Button;
ImageButton name2Button;
ImageButton name3Button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); // Layout contains 3 ImageButtons "@+id/imageButton1", "@+id/imageButton2" and "@+id/imageButton3"
name1Button = (ImageButton) findViewById(R.id.imageButton1);
name2Button = (ImageButton) findViewById(R.id.imageButton2);
name3Button = (ImageButton) findViewById(R.id.imageButton3);
}
public void onChangeScreen(View view) {
Intent changeScreenIntent = new Intent(this, SecondActivity.class);
if(view == name1Button) {
changeScreenIntent.putExtra("Name", "name1");
} else if (view == name2Button) {
changeScreenIntent.putExtra("Name", "name2");
} else if (view == name3Button) {
changeScreenIntent.putExtra("Name", "name3");
} else {
changeScreenIntent.putExtra("Name", "Other");
}
startActivity(changeScreenIntent);
}
}
SecondActivity.java
public class SecondActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.my_layout); //Contains a TextView "@+id/textViewName"
Intent myIntent = getIntent();
String strName = myIntent.getExtras().getString("Name"); //Set strName to the parsed name ("name1", "name2" or "name3")
TextView myTextView = (TextView) findViewById(R.id.textViewName);
myTextView.setText(strName); //Sets the name parsed to a TextView //Setting the texts of the displayed TextView "@+id/textViewName" to the value of strName. This CORRECTLY shows the parsed name.
if(strName == "name1") { // Never true, even though the value of strName is "name1"
//Do thing if certain button clicked
Toast.makeText(this, "You selected name1", Toast.LENGTH_SHORT).show();
} else {
//Do other thing if non-specified button clicked
Toast.makeText(this, "Something went wrong", Toast.LENGTH_SHORT).show();
}
}
}
这意味着要做的事情如下:
onChangeScreen
。onChangeScreen
的3个按钮中的哪一个,将不同的值(字符串)传递给SecondActivity。changeScreenIntent.putExtra()
,调用第二个Activity。.putExtra()
传递的值。这是问题出现的地方。比较传递给SecondActivity的字符串的if语句显然是'不等于字符串的值(但显示的TextView
显示此字符串)。因此,永远不会使用if语句中的代码(替换为Toast)。
答案 0 :(得分:1)
始终用于比较字符串
if(strName.equals("name1"))
Toast.makeText(this, "You selected name1", Toast.LENGTH_SHORT).show();
} else {
//Do other thing if non-specified button clicked
Toast.makeText(this, "Something went wrong", Toast.LENGTH_SHORT).show();
}
equals()而不是== for string .....
享受编码.....
答案 1 :(得分:1)
使用"name1".equals(strName)
代替==
。如果strName
永远是null
。
答案 2 :(得分:0)
使用equals
代替==
使用
if(strName .equals("name1"))