簡體   English   中英

如何在另一個活動中調用方法

[英]how to call method in another activity

我應該從一個活動到另一個活動調用一個方法。 我的頭等艙是:

public class firstclass extends Activity {
    public String Kind(){
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
    boolean Key = preferences.getBoolean("Key", true);
    if(Key){
        name="you";
    }
    else{
        name="me";
    }
    return name;
    }
}

第二類是:

public class secondclass extends Activity {
    public void take(String token, int transactionId) {
        firstclass first = new firstclass(); //error in this class
        first.Kind();
   }
}

我的錯誤是:

03-25 19:05:39.082    5421-5487/com.example.com E/AndroidRuntime﹕ FATAL          EXCEPTION: pool-5-thread-1
java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
        at android.os.Handler.<init>(Handler.java:197)
        at android.os.Handler.<init>(Handler.java:111)
        at android.app.Activity.<init>(Activity.java:759)
        at com.example.com.firstclass<init>(firstclass.java:17)
        at com.example.com.secondclass(secondclass.java:157)

簡而言之:您不應該。 制作一個單獨的(單例)類,該類處理兩種活動都可以訪問的kind()邏輯。

如果您有需要在活動之間共享的代碼,則應將其導出到Helper類。

例:

public class KindUtils {
    public static String Kind(Context context){
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
    boolean Key = preferences.getBoolean("Key", true);
    if(Key){
        name="you";
    }
    else{
        name="me";
    }
    return name;
    }
}

現在,您可以在兩個活動中調用KindUtils.Kind(this)

那不是你做的方式。 讓我根據我的知識更正您的代碼。

  1. 始終確保類名應以大寫字母開頭,其java類命名約定
  2. 始終使用駱駝套作為方法名稱,從小寫字母開始。
  3. 您不能將關鍵字new用於擴展Activity的類。

現在如何從某個活動中訪問其他活動的方法

((Firstclass)getActivity()).kind;

這就是您從android中其他類訪問方法的方式。

public class Firstclass extends Activity {
    public String kind(){
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
    boolean Key = preferences.getBoolean("Key", true);
    if(Key){
        name="you";
    }
    else{
        name="me";
    }
    return name;
    }
}

在二等班,你會做

public class Secondclass extends Activity {
    public void take(String token, int transactionId) {
        String str= ((Firstclass)getActivity()).kind;
   }
}

希望對你有幫助

首先,當您從非UI線程調用UI(用戶界面)方法時,會發生彎針錯誤。 在這種情況下,因為第二個活動不是出於意圖而啟動的,所以您將其啟動是因為新的firstClass()會發生不好的事情。 活動具有生命周期回調。 onCreate可以將引用傳遞給應該繪制的項目,通常至少是對布局setContentView(R.layout.activity_main);的引用,onStart是開始繪制。 請記住,Android支持多種屏幕尺寸,並且必須詢問您要添加到活動中的內容,多少,Android度量和數字如何顯示,然后調用onstart來顯示它,等等。 最主要的是將Activity作為Intent啟動並閱讀鏈接。 在清單活動塊中,您具有啟動器,這意味着在圖標上放置一個圖標以在單擊該圖標時啟動一個活動。 一種啟動活動的特殊方式。

您只需不像在Java中那樣實例化Android中的Activities實例。 您應該創建Intents並調用startActivity() 為了使您的邏輯起作用,我建議您使用BroadcastReceivers

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM