android - 单击按钮时 setContentView 不起作用

标签 android layout android-activity

请帮助我编写代码。

当我单击任何按钮时,button1、button2 或 button3 打开新 Activity ,但布局是空的,没有任何文本和其他内容。

调用新 Activity 的 Activity 代码:

package com.novator.inweld;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class TentsCatalog extends Activity implements OnClickListener
{
    private Button button1;
    private Button button2;
    private Button button3;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.tents_catalog);

        button1 = (Button)findViewById(R.id.button1);
        button2 = (Button)findViewById(R.id.button2);
        button3 = (Button)findViewById(R.id.button3);

        button1.setOnClickListener(this);
        button2.setOnClickListener(this);
        button3.setOnClickListener(this);
    }

    @Override
    public void onClick(View view)
    {
        if(view == button1)
        {
            Intent intent = new Intent(this, TentPage.class);
            intent.putExtra("tentId", "1");
            startActivity(intent);
        }

        if(view == button2)
        {
            Intent intent = new Intent(this, TentPage.class);
            intent.putExtra("tentId", "2");
            startActivity(intent);
        }

        if(view == button3)
        {
            Intent intent = new Intent(this, TentPage.class);
            intent.putExtra("tentId", "3");
            startActivity(intent);
        }
    }
}

我的新 Activity 代码:

package com.novator.inweld;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;

public class TentPage extends Activity
{
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);

        Intent intent= getIntent();
        String tentId = intent.getStringExtra("tentId");

        if(tentId == "1")
        {
            setContentView(R.layout.tent1);
        }

        if(tentId == "2")
        {
            setContentView(R.layout.tent2);
        }

        if(tentId == "3")
        {
            setContentView(R.layout.tent3);
        }
    }

}

最佳答案

使用 equals(),而不是 ==

if(tentId.equals("1"))

关于android - 单击按钮时 setContentView 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21075143/

相关文章:

android - 半透明导航栏是纯色

java - 如何在android中操纵 Volley 响应?

Android:远程服务中的主线程是什么?服务中的网络操作

css - 仅当顶部栏粘在顶部时如何显示元素? - Zurb 基金会

java - 远程服务异常错误

java - 使用 AsyncTask 用多个项目填充 ExpandableListView

android - Admob 横幅布局错误,以编程方式设置大小

java - 无法在 java swing 应用程序中设置按钮的位置

java - 清理我的项目后,R.java 文件消失了

android - 是否需要覆盖 onSaveInstanceState 来保存私有(private)字段?