2011-11-10 57 views
2

我正在爲Android創建Phonegap插件。當我將findViewById方法添加到this.ctx.runOnUiThread(new Runnable()時,我收到標題中所述的錯誤。FindViewById(int)的方法未定義爲新類型Runnable(){}

這裏是我的代碼:

package com.company.msgbox; 


import java.io.File; 

import org.crossplatform.phonegap.trial.alternativeTo.R; 
import org.json.JSONArray; 
import org.json.JSONException; 

import android.app.AlertDialog; 
import android.graphics.Bitmap; 
import android.view.View; 

import com.phonegap.api.Plugin; 
import com.phonegap.api.PluginResult; 
import com.phonegap.api.PluginResult.Status; 

public class msgbox extends Plugin { 

    private static final String SHOW = "show"; 
    private static final int MSG_INDEX = 0; 
    private String msg; 

    @Override 
    public PluginResult execute(String arg0, final JSONArray arg1, String arg2) { 
     if (arg0.equals(SHOW)) { 
      this.ctx.runOnUiThread(new Runnable() { 
       public void run() { 
        // try/catch generated by editor 
        try { 
         msg = arg1.getString(MSG_INDEX); 
        } catch (JSONException e) { 
         // TODO Auto-generated catch block 
         e.printStackTrace(); 
        } 

        AlertDialog alertDialog = new AlertDialog.Builder(ctx).create(); 
        alertDialog.setTitle("Title"); 
        alertDialog.setMessage(msg); 
        alertDialog.show(); 

        View content = findViewById(R.id.layoutroot); 
        Bitmap bitmap = content.getDrawingCache(); 
        File file = new File("/sdcard/test.png"); 
       } 
      }); 
     } 

     return new PluginResult(Status.OK); 
    } 

} 
+0

請工作在你的縮進。現在代碼不可讀。 – Gray

+0

我編輯了縮進,等待驗證。這確實是不可讀 – Guillaume

+0

感謝Guillaume :) – jcrowson

回答

5

你需要從實際有方法的類調用findViewById。好的做法通常是傳遞你正在創建這個類的Activity。喜歡的東西:

public class msgbox extends Plugin { 
    private static final String SHOW = "show"; 
    private static final int MSG_INDEX = 0; 
    private String msg; 
    private final Activity parent; 

    // constructor 
    public msgbox(Activity parent) { 
     this.parent = parent; 
    } 

那麼你可以做:

parent.findViewById(R.id.layoutroot) 

您從一個活動內,以構建你的msgbox:

msgbox myMsgBox = new msgbox(this); 

當然,要做到這一點,在R.id.layoutroot組件必須處於您通過的活動中。

如果您在當你構建MSGBOX活動不是,你可以用一個setter替換構造函數注入:

public void setParent(Activity parent) { 
    this.parent = parent; 
} 

雖然,要能夠將您的Runnable中使用findViewById,家長需要是最終的,所以你必須把它複製到一個最終的變量(setter注入不能是最終的,顯然)

(注意:此外,您的類不使用標準的java命名約定,它很混亂:稱之爲MsgBox

+0

偉大的,它的工作原理,但我知道我有:'this.context \t = \t上下文; this.parent \t \t =(Activity)context;'在​​構造函數中。有沒有更好的辦法 ? –

+0

爲什麼你有this.context =上下文?你需要在你的課程中的其他地方使用this.context嗎?你只需要一個實例,如果你將this.parent轉換爲(Activity),它仍然表示我使用它的相同對象 – Guillaume

+0

,因爲我需要在活動之間發送數據。 A執行B(AsyncTask),然後B將數據返回給A. –

相關問題