Bài 24: Intent Trong Android(P2)

Leave a Comment
Intent myIntent=new Intent(thisChildActivity.class);
Đối số 1 là context hiện tại, nếu bạn muốn chắc ăn ở đâu nó cũng hiểu thì bạn gán tên class Activity như thế này:
Intent myIntent=new Intent(MainActivity.thisChildActivity.class);
Với MainActivity là một Activity tùy ý (trong Context hiện tại), viết như trên thì bạn sẽ luôn luôn đúng trong mọi trường hợp.
Đối số 2 là :  ChildActivity.class, Tức là bạn muốn mở Activity nào thì lấy tên Activity đó .class; trong trường hợp này Tôi muốn mở ChildActivity nên Tôi ghi là ChildActivity.class
- Quan sát dòng lệnh 26
startActivity(myIntent); Hàm này có tác dụng mở Activity được truyền vào đối số thứ 2 ở trên.
- Tiến hành khám phá ChildActivity:
24_intent_3
-Đầy là source XML của ChildActivity:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:id="@+id/LinearLayout1"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:orientation="vertical"
 tools:context=".ChildActivity" >
 
<TextView
 android:id="@+id/textView1"
 android:layout_width="match_parent"
 android:layout_height="100dp"
 android:background="#FFFF00"
 android:gravity="center"
 android:text="This is Child Activity"
 android:textColor="#008040"
 android:textSize="20sp"
 android:textStyle="bold" />
 
<Button
 android:id="@+id/btnBacktoMainActivity"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:layout_gravity="center"
 android:text="Back to Main Activity" />
 
</LinearLayout>
-Giao diện của ChildActivity chỉ có một Button cho phép quay lại MainActivity.
- Bạn xem coding của ChildActivity:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
package tranduythanh.com;
 
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
 
public class ChildActivity extends Activity {
 protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_child);
 Button btnBack= (Button)
 findViewById(R.id.btnBacktoMainActivity);
 btnBack.setOnClickListener(new
 View.OnClickListener() {
 public void onClick(View v) {
 finish();
 }
 });
 }
 public boolean onCreateOptionsMenu(Menu menu) {
 // Inflate the menu; this adds items to the action bar if it is present.
 getMenuInflater().inflate(R.menu.activity_child, menu);
 return true;
 }
}
-Dòng lệnh 18:  finish() có nhiệm vụ đóng Activity hiện tại.
- Bạn vừa đi qua 1 ví dụ vô cùng đơn giản.

0 nhận xét:

Đăng nhận xét