使用起始值启动新活动

时间:2012-03-29 14:34:35

标签: android android-layout android-intent

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

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

    <activity android:name=".NewActivity" android:label="@string/new_activity_header" />
    
  3. 定义新的Intent并调用startActivity以启动新活动。
  4. 但是,我想用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 !
        }
    });
    

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

    提前致谢:)

4 个答案:

答案 0 :(得分: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");

答案 1 :(得分:1)

将此类似添加到您的活动中

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

然后像这样创建G类

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

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

答案 2 :(得分:1)

您必须将随机数添加到意图中,如下所示:

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

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

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

希望这有帮助

答案 3 :(得分:1)

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

在您开始的新活动中,您可以调用getIntent并提取之前放入的'extras'。

相关问题