Cách chuyển đổi qua lại giữa các Activity trong Android
Trong các ứng dụng Android, giao diện đều được thể hiện qua một activity. Trong quá trình phát triển một ứng dụng Android, bạn phải biết cách chuyển đổi qua lại giữa các screen (màn hình) hoặc view. Trong bài viết đầu tiên của Blog Lập trình Android này, chúng ta bàn về cách chuyển qua lại giữa Activity này sang một Activity khác, và chuyển dữ liệu qua lại giữa các Activities.Sau khi tạo mới 1 Project, ta tạo thêm 1 file Activity class trong src/com.devandroid.demoswitchactivity: SecondActivity.java.
Để mở một Activity mới, ta dùng phương thức startActivity() hoặc startActivityResult()
Intent i = new Intent(getApplicationContext(), SecondActivity.class); StartActivity(i);
Gửi dữ liệu sang một Activity mới
Để gửi dữ liệu sang một Activity mới, ta dùng phương thức putExtra()
i.putExtra("key", "value");
// example
i.putExtra("email", "myemail@gmail.com");
Nhận dữ liệu ở một Activity mới
Để nhận dữ liệu ta sử dụng phương thức getStringExtra()
Intent i = getIntent()
i.getStringExtra("key");
String myemail = i.getStringExtra("email");
Nếu bạn muốn nhận giá trị trả về từ một Activity mới, ta dùng phương thức startActivityForResult(). Nếu Activity mới đã đóng, ta dùng phương thức onActivityResult() để đọc giá trị trả về
Intent i = new Intent(getApplicationContext(), SecondScreen.class);
startActivityForResult(i, 101); // 101 là một mã dùng để xác thực giá trị trả về
// Function dùng để đọc kết quả trả về từ một Activity mới được tạo
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent Data)
{
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == 101)
{
String mywebsite = data.getExtras().get("result");
}
}
Gửi dữ liệu trả về Activity cũ khi StartActivityForResult() được dùng
Intent i = new Intent();
i.putExtra("website", "http://laptrinhandroidaz.blogspot.com");
setResult(101, in);
Để đóng Activity ta dùng phương thức finish()
finish();
Chỉnh sửa AndroidManifest.xml
Để có thể chạy được ứng dụng, bạn phải khai báo activity mới vào file AndroidManifest.xml. Thêm activity mới vào giữa tag <application>
<activity android:name=".NewActivity"></activity>
Bây giờ chúng ta sẽ làm 1 demo nhỏ cho bài ngày hôm nay.
Trước hết, ta tạo thêm 1 file Activity nữa tên: SecondActivity.java và 1 file xml secondscreen.xml. Bạn có thể xem hình bân dưới để biết vị trí tạo 2 file trên ở đâu.
Nào trước hết ta tạo 1 project:
- Vào File -> New -> Android Application Project. Đặt tên project là Demo Switch Activity.
- Chọn Minimum Required SDK, Target SDK và Compile With -> Next -> Next and Finish.
- Vào phần src/com.devandroid.demoswitchactivity, tạo 1 file java có tên SecondActivity.java.
- Vào phần res/layout tạo 1 file secondscreen.xml
- Mở file activity_main.xml trong res/layout và code như sau:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Họ Tên"/> <EditText android:id="@+id/editName" android:layout_width="fill_parent" android:layout_height="wrap_content" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Email" /> <EditText android:id="@+id/editMail" android:layout_width="fill_parent" android:layout_height="wrap_content" /> <Button android:id="@+id/btnSend" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Gửi dữ liệu" /> <LinearLayout/>
- Chạy thử giao diện xem thế nào nhé.
- Mở file Main_Activity.java và code như sau. Trong đoạn code, ta tạo một Intent và gán dữ liệu khi nhấn nút.
package com.devandroid.demoswitchactivity; import android.os.Bundle; import android.app.Activity; import android.view.Menu; import android.content.Intent; import android.widget.EditText; import android.widget.Button; import android.widget.Toast; import android.view.View; public class MainActivity extends Activity { EditText editName, editMail; Button btnSend; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); editName=(EditText)findViewById(R.id.editName); editMail=(EditText)findViewById(R.id.editMail); btnSend=(Button)findViewById(R.id.btnSend); btnSend.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub String name = editName.getText().toString(); String email = editMail.getText().toString(); Intent nextScreen = new Intent(getApplicationContext(), SecondActivity.class); nextScreen.putExtra("name", name); nextScreen.putExtra("email", email); startActivity(nextScreen); //Toast.makeText(getApplicationContext(), "Đúng rồi", Toast.LENGTH_LONG).show(); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } }
- Mở file secondscreen.xml và code như sau
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="25dip" android:gravity="center" android:layout_margin="15dip" android:text="Dữ liệu bạn đã nhập" /> <TextView android:id="@+id/txtName" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_margin="15dip" android:textSize="18dip" /> <TextView android:id="@+id/txteMail" android:layout_height="wrap_content" android:layout_width="wrap_content" android:layout_margin="15dip" android:textSize="18dip" /> <Button android:id="@+id/btnClose" android:layout_height="wrap_content" android:layout_width="fill_parent" android:layout_marginTop="15dip" android:text="Đóng" /> </LinearLayout>
- Mở file SecondActivity.java và code như sau.
package com.devandroid.demoswitchactivity; import android.app.Activity; import android.os.Bundle; import android.content.Intent; import android.view.View; import android.widget.TextView; import android.widget.Button; public class SecondActivity extends Activity { TextView txtName, txtMail; Button btnClose; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.secondscreen); txtName=(TextView)findViewById(R.id.txtName); txtMail=(TextView)findViewById(R.id.txteMail); btnClose=(Button)findViewById(R.id.btnClose); Intent i = getIntent(); String name = i.getStringExtra("name"); String mail = i.getStringExtra("email"); txtName.setText(name); txtMail.setText(mail); btnClose.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub finish(); } }); } }
- Mọi thứ có vẻ ổn rồi đấy, nhưng đừng quên vào file AndroidManifest.xml để thêm activity mới tạo nhé
<application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name="com.devandroid.demoswitchactivity.MainActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name=".SecondActivity" > </activity> </application>
- Cuối cùng ta chạy thử chương trình nào
No comments
Posted at 6:59 AM |  by
James Are



