【问题标题】:Using intent to pass spinner objects to a new activity via a button使用意图通过按钮将微调器对象传递给新活动
【发布时间】:2015-02-10 20:08:24
【问题描述】:

在第一个活动中,我有一个微调器和一个按钮。我想使其进行操作,以便选择旋转器选项,然后单击按钮时,打开新活动,并在TextView中显示旋转器选项(以及有关IT的其他信息)。简而言之,我正在尝试使用意图来发送和检索数据,然后添加其他信息,我认为我会使用 putExtra() 方法。

这里我有指向第二页的按钮,我试图通过意图存储微调器的对象。 MainActivity

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Button yourButton = (Button) findViewById(R.id.done);

    yourButton.setOnClickListener(new View.OnClickListener(){
        public void onClick(View v){

            Intent intent = new Intent(MainActivity.this, Selected.class);
            intent.putExtra("new_variable_name","value");
            startActivity(intent);
        }
    });

这里是 Selected.class(第二个活动) 我想检索微调器信息并将其放入文本视图中。

Bundle extras = getIntent().getExtras();
    if (extras != null) {
        String value = extras.getString("new_variable_name");
    }
}

另外,这里是名为“person_array”的微调器数组:

<string-array name="person_array">
    <item>Nick</item>
    <item>Isaac</item>
    <item>Sally</item>
    <item>Matt</item>
    <item>Tim</item>
</string-array>

【问题讨论】:

    标签: android button android-intent android-studio spinner


    【解决方案1】:

    您的代码中的问题是您正在创建两个不同的意图对象。前者用字符串填满:

      Intent i = new Intent(getApplicationContext(), Spinner.class);
      i.putExtra("new_variable_name","value");
    

    然后您使用后者为 Selected 活动加注星标。

      startActivity(new Intent(MainActivity.this, Selected.class));
    

    你应该只使用一个

     Intent intent = new Intent(MainActivity.this, Selected.class);
     intent.putExtra("new_variable_name","value");    
     startActivity(intent);
    

    【讨论】:

    • 啊,我明白了,当我应该放置目的地/Selected.class 时,我在第二个参数中有微调器。编辑了主帖~
    • 不喜欢重复评论但是,我该怎么做才能在这个新页面的文本视图中拉出从微调器中选择的对象?它正确加载了空白页面,但我希望该对象出现在 textview 中,然后使用 putExtra 方法添加其他信息。
    • 使用您的视图创建布局并将其传递给 setContentView 。检索TextViewfindViewById 并在实例上调用setText
    • 嗯,这是我绝对迷路的地方,哈哈。我在适当的布局文件 (activity_selected.xml) 中创建了一个 textview,但我不知道在 Selected.class 文件中如何处理它。我还没有使用 setContentView 或 findViewById。
    【解决方案2】:

    在您的第一个代码 sn-p 中,您创建了一个 Intent (i),指向不是 Android 应用程序组件 (Spinner) 的东西,在上面添加一个额外的东西,然后将其丢弃.这不会有用。

    相反,将您的额外内容放在您与startActivity() 一起使用的Intent 上:

    startActivity(new Intent(MainActivity.this, Selected.class)
                    .putExtra("new_variable_name","value"));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-05-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-07
      相关资源
      最近更新 更多