This question already has answers here:
How do I compare strings in Java?
                                
                                    (23个答案)
                                
                        
                                4年前关闭。
            
                    
我使用Extra通过意图传递了对列表视图的选择,但没有选择它。

以下代码底部的日志表明,它正在将正确的名称传递给此类文件,例如cous cous,意大利面,蛋糕等-但它不会在if语句中显示日志,也不会加载内容视图。

有任何想法吗?

public class RecipePage extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        String recipeName = (String) getIntent().getStringExtra("RecipeName");
        if(recipeName == "Cous Cous"){
            setContentView(R.layout.activity_couscous);
            Log.d("Joe", "1");
        }
        if(recipeName == "Rice"){
            setContentView(R.layout.activity_rice);
            Log.d("Joe", "2");
        }
        if(recipeName == "Burgers"){
            setContentView(R.layout.activity_burgers);
            Log.d("Joe", "3");
        }
        if(recipeName == "Pasta"){
            setContentView(R.layout.activity_pasta);
            Log.d("Joe", "4");
        }
        if(recipeName == "Chicken"){
            setContentView(R.layout.activity_chicken);
            Log.d("Joe", "5");
        }
        if(recipeName == "Cake"){
            setContentView(R.layout.activity_cake);
            Log.d("Joe", "6");
        }
        if(recipeName == "Roast"){
            setContentView(R.layout.activity_roast);
            Log.d("Joe", "7");
        }
        if(recipeName == "Lasagne"){
            setContentView(R.layout.activity_lasagne);
            Log.d("Joe", "8");
        }

        Log.d("Joe", "Recipe =" + recipeName);

    }
}

最佳答案

为了比较字符串,您应该使用equals()方法。

10-05 18:55