2011-11-10 6 views
2

私はAndroid用のPhonegapプラグインの作成に取り組んでいます。 findViewByIdメソッドをthis.ctx.runOnUiThread(new Runnable()に追加すると、タイトルに記載されているエラーが発生します。あなたが実際にメソッドを持つクラスからfindViewByIdを呼び出す必要findViewById(int)メソッドがnew型のために未定義です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

おかげでギョーム:) – jcrowson

答えて

5

は、ここに私のコードです。通常は、このクラスを作成しているアクティビティを渡すことをお勧めします。ような何か:あなたが使用しての活動の中からあなたのMsgBoxを構築

parent.findViewById(R.id.layoutroot) 

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; 
    } 

次に、あなたが行うことができます。もちろん、

msgbox myMsgBox = new msgbox(this); 

を、それを行うには、R.id.layoutrootコンポーネントは、渡されたアクティビティに含まれている必要があります。

あなたがメッセージボックスを作成するときに活動していないなら、あなたはセッターとコンストラクタ・インジェクションを置き換えることができます。

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

親がする必要がある、あなたのRunnable内findViewByIdを使用することができるようにする、が、

(注:あなたのクラスは標準的なJava命名規則を使用していないので、それは曖昧です:MsgBoxと呼んでください)

+0

偉大な、それは動作しますが、右が私が好きだ知っている: 'this.context \t = \tコンテキスト; this.parent \t \t =(アクティビティ)コンテキスト; 'コンストラクタ内。より良い方法がありますか? –

+0

なぜthis.context = contextを持っていますか?あなたはあなたのクラスのどこにでもthis.contextが必要ですか? this.parentを(Activity)にキャストしても同じオブジェクトを表す場合は、ただ1つのインスタンスしか必要ありません – Guillaume

+0

私はアクティビティ間でデータを送信する必要があるため使用します。 AはB(AsyncTask)を実行し、BはAにデータを返します。 –

関連する問題