方法findViewById(int)未定义类型new Runnable(){}

jcr*_*son 2 java android cordova

我正在为Android制作一个Phonegap插件.当我添加findViewById方法时,this.ctx.runOnUiThread(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);
    }

}
Run Code Online (Sandbox Code Playgroud)

Gui*_*ume 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;
    }
Run Code Online (Sandbox Code Playgroud)

然后你可以做一个:

parent.findViewById(R.id.layoutroot)
Run Code Online (Sandbox Code Playgroud)

您可以使用以下命令在活动中构建msgbox:

msgbox myMsgBox = new msgbox(this);
Run Code Online (Sandbox Code Playgroud)

当然,要做到这一点,R.id.layoutroot组件必须在您传递的活动中.

如果在构造msgbox时不在活动中,则可以使用setter替换构造函数注入:

public void setParent(Activity parent) {
    this.parent = parent;
}
Run Code Online (Sandbox Code Playgroud)

虽然,为了能够在你的内部使用findViewById Runnable,父级需要是最终的,所以你必须将它复制到最终变量(setter注入不能是最终的,显然)

(注意:此外,您的类不使用标准的Java命名约定,令人困惑:调用它MsgBox)