2020年10月21日 星期三

如何在啟動 Activity 時帶入參數

使用 putExtra 帶入 Intent
以 getIntent().getExtras().取出

啟動時帶入參數
Intent intent = new Intent(caller, ActFolder.class);
intent.putExtra([參數名稱], [參數值]);
caller.startActivity(intent);

取用參數
Bundle bundle = getIntent().getExtras();
[val]= (String) bundle.get([參數名稱]);


範例:啟動一個顯示目錄的 Activity

啟動Activity 並帶入參數
Intent intent = new Intent(caller, ActFolder.class);
//建立一個 Intent , 指定 class

intent.putExtra("PATH", path);
//將路徑參數帶入 intent

caller.startActivity(intent);

取出傳入的路徑
Bundle bundle = this.getIntent().getExtras();
//取出 Activity 的參數Bundle

_path = (String) bundle.get("PATH");
//從 Bundle 中取出 PATH 的值

2020年10月15日 星期四

如何啟動一個 Activity

如何在程式中啟動一個 Activity 

啟動一個 Activity

android.content.Intent intent = new android.content.Intent();
//建立一個intent

intent.setClass(caller, [class]);
//指定要啟動的 Activity class

startActivity(intent);
//用startActivity 啟動之


startActivity 是content(android.content) 的一個 method
繼承者都會有
像是 activity,service,application
想進一步了解的, 可以參考 startActivity官方文件

下面是個人的使用例子

啟動一個名為 ActWks 的 Activity

Intent intent = new Intent(caller, ActWks.class);
startActivity(intent);


寫成函式

public static void openClass(Class targetClass, Context caller)
{
    android.content.Intent intent = new android.content.Intent();
    intent.setClass(caller, targetClass);
    caller.startActivity(intent);
}