読者です 読者をやめる 読者になる 読者になる

liguofeng29’s blog

個人勉強用ブログだっす。

AndroidのActivity - Activityへのデータ渡し (Bundle)

  

MainActivity.java
 
package com.example.liguofeng.requestdatatoactivity;

import android.app.Activity;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends Activity {

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

Button login = (Button) findViewById(R.id.login);
login.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String account = ((EditText) findViewById(R.id.account)).getText().toString();
String password = ((EditText) findViewById(R.id.password)).getText().toString();

// Bundle
Bundle data = new Bundle();
data.putString("account", account);
data.putString("password", password);
// Intent&Activity起動
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
intent.putExtras(data);
startActivity(intent);
}
});
}
}

 

SecondActivity.java
 
package com.example.liguofeng.requestdatatoactivity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;

import org.w3c.dom.Text;

public class SecondActivity extends Activity {

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

TextView account = (TextView) findViewById(R.id.rls_account);
TextView password = (TextView) findViewById(R.id.rls_password);

// 起動時のIntent取得
Intent intent = getIntent();
// Intent内のデータ取得
account.setText(intent.getStringExtra("account"));
password.setText(intent.getStringExtra("password"));
}
}