Java 使用变量定义setContentView

Java 使用变量定义setContentView,java,android,Java,Android,我是android的新手,我试图通过Intent函数接收一个变量,并根据和变量的值显示contentview Bundle parametros = getIntent().getExtras(); String type = parametros.getString("tipo"); int accao = parametros.getInt("accao"); protected void onCreate(Bundle savedInstanceState) { super.on

我是android的新手,我试图通过Intent函数接收一个变量,并根据和变量的值显示contentview

Bundle parametros = getIntent().getExtras();
String type = parametros.getString("tipo");
int accao = parametros.getInt("accao");

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    if (type=="medicamentos") {
        Button voltar = (Button) findViewById(R.id.button1);
        voltar.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                Intent medIntent = new Intent(view.getContext(), Listar.class);
                startActivityForResult(medIntent, 0);
            }
        });
        if (accao==1)
            setContentView(R.layout.adicionar_medicamentos);

        if (accao==2)
            setContentView(R.layout.editar_medicamentos);
    }
}
我做错了什么?谢谢

使用
equals()
比较字符串

=
比较对象引用而不是其内容

if(type.equals("medicamentos")) {
  ....
}

}
type==“medicamentos”
应该是
“medicamentos”。equals(type)
getIntent调用应该在onCreate.or
type.equals(“medicamentos”)
@Abu中,但是如果
type
null
,则会抛出一个NPE。这样做时应该非常小心。做你正在做的事情可能有一个合理的理由,但在大多数情况下,这是一个设计错误,会给你带来很大的麻烦。如果布局不包含相同的视图,则每次执行findViewById()之前都必须检查该值。
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

String type = getIntent().getString("tipo");
int accao = getIntent().getInt("accao");

if (type != null && type.equals("medicamentos")) {
    Button voltar = (Button) findViewById(R.id.button1);
    voltar.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {
            Intent medIntent = new Intent(view.getContext(), Listar.class);
            startActivityForResult(medIntent, 0);
        }
    });
    if (accao==1)
        setContentView(R.layout.adicionar_medicamentos);

    if (accao==2)
        setContentView(R.layout.editar_medicamentos);
}