【问题标题】:Using putExtra in intent to display specific layout in new activity使用 putExtra 意图在新活动中显示特定布局
【发布时间】:2012-10-05 22:27:55
【问题描述】:

我很好奇我是如何使用的

putExtra("something", something);

打算在我的应用程序中创建一个新活动,

Intent i = new Intent(getApplicationContext(), MainActivity.class);
i.putExtra("something", something)
startActivity(i);

我需要知道发送端和接收端的外观,根据意图中的 putExtra 发送的内容加载特定的布局文件。

因此,如果我在接收端发送 i.putExtra("a", a),它将使用 R.layout.a_layout.xml 创建一个内容视图

但如果我发送 i.putExtra("b", b) 它将加载 R.layout.b_layout.xml

有什么想法吗?

【问题讨论】:

    标签: java android layout android-intent


    【解决方案1】:

    这样做的一个好方法是说:

    Intent i = new Intent(getApplicationContext(), MainActivity.class);
    i.putExtra("layout", R.layout.a_layout.xml);
    

    将正确的布局发送到您的新班级。然后在新的类中,你可以使用:

    int layout = getIntent().getIntExtra("layout", R.layout.default_layout);
    setContentView(layout);
    

    【讨论】:

      【解决方案2】:

      发送代表您的布局的 int:

      i.putExtra("layout_id", R.layout.my_layout1);
      

      并加载它

      setContentView(getIntent().getIntExtra("layout_id", R.layout.default_layout);
      

      【讨论】:

        【解决方案3】:

        R.layout.a_layout 之类的值只是 int。所以,只需使用putExtra("Key", R.layout.a_layout);。

        然后,在您的接收活动中,只需将相同的 int 传递给 setContentView(),例如:

        public void onCreate(Bundle savedInstanceState)
        {
            int layout = getIntent().getIntExtra("Key", -1);
            if (layout != -1)
                setContentView(layout);
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-09-21
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多