【问题标题】:Start new activity with start values使用起始值开始新活动
【发布时间】:2012-03-29 14:34:34
【问题描述】:

我知道我们可以按照以下步骤开始新的活动:

  1. 设计包含布局详细信息的新 XML 文件(LinearLayout, RelativeLayout 等)并添加用户定义的小部件(Button、TextView、...)
  2. 将活动名称和标签详细信息添加到 AndroidManifest.xml,如下所示

    <activity android:name=".NewActivity" android:label="@string/new_activity_header" />
    
  3. 定义新的 Intent 并调用 startActivity 来启动新的活动。

但是,我想使用将在不同调用中更改的 start 参数启动新活动。

例如:

  • 主要活动XML布局文件:

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical" >
    
        <Button
            android:layout_width="wrap_content" 
            android:layout_height="wrap_content"
            android:id="@+id/button" />
    </LinearLayout>
    

我想这样做: 如果我们按下按钮,将启动新的活动并显示主活动中生成的随机数。

Button btn = (Button) findViewById(R.id.button);
btn.setOnClickListener(new View.OnClickListener() {

    @Override
    public void onClick(View v) {
        int rand = new Random().nextInt(10000);

        //Some code will be placed here !
    }
});

但是如何初始化新的活动类字段成员?

提前致谢:)

【问题讨论】:

    标签: android android-layout android-intent


    【解决方案1】:

    尝试:

    Button btn = (Button) findViewById(R.id.button);
    btn.setOnClickListener(new View.OnClickListener() 
    {
        @Override
        public void onClick(View v) 
        {
            int rand = new Random().nextInt(10000);
            Intent i = new Intent(getApplicationContext(), YourClass.class);       
            i.putExtra("random", rand);
            startActivity(i);
        }
    });
    

    在你的活动中:

    Bundle b = new Bundle();
    b = getIntent().getExtras();
    int value = b.getInt("random");
    

    【讨论】:

    • 非常感谢 :) 如我所见,所有答案都是正确的,但你马上就做,我也接受你的答案 :)
    【解决方案2】:

    像这样添加到您的活动中

     <application
          android:name="com.uncocoder.test.activity.G"
          ....>
     </application>
    

    然后像这样创建 G 类

    public class G extends Application {
        @Override
        public void onCreate() {
            //do your works here
        }
    }
    

    因此,在激活任何活动之前,您的代码将运行。

    【讨论】:

      【解决方案3】:

      您必须像这样将随机数添加到意图中:

      Intent intent = new Intent(this, <Your Activity>.class);
      intent.putExtra("rand", rand);
      startActivity(intent);
      

      然后在新活动的 onCreate 中获取值:

      rand = getIntent().getIntExtra("rand", 0);
      

      希望对你有帮助

      【讨论】:

        【解决方案4】:

        在您的主要活动中,在 onClick 方法中,创建一个 Intent。然后,您可以使用 intent.putExtra 将数据添加到 Intent。然后你可以调用 startActivity 并给它 Intent。

        在您开始的新 Activity 中,您可以调用 getIntent 并提取您之前放入的“附加”。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-03-31
          • 2015-06-14
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多