편집 : 사용자 QuickFix의 답이 저에게 효과적이었습니다. 이 질문의 맨 아래에 바로 코드를 작성하십시오.Cordova 3 Android Plugin - 주요 활동에서 함수를 호출하는 방법?
정상 및 맞춤 토스트를 만드는 Cordova 3 Android 플러그인을 작성하려고합니다. 그러나, 나는 단지 프론트 엔드 개발자이고 Cordova와 Android에 처음으로 익숙합니다. 나는 아직도 배우고 당신이 줄 수있는 어떤 도움에 감사 할 것입니다.
지금까지 내가 개인적으로 그리고 성공적으로이 작업을 수행 할 관리해야 :
- 정상 및 사용자 정의 토스트를 만드는 주요 활동에 함수를 작성 (사용자 정의 토스트는 단순히/입술/레이아웃에서 RelativeLayout의입니다 아이콘과 텍스트를 보여줍니다).
- Devgirl의 튜토리얼 : How to Write a PhoneGap 3.0 Plugin for Android에 따라 Cordova 플러그인을 작성하십시오.
내 문제는 다음과 같습니다. - 플러그인을 주 활동에서 showCustomToast()
함수로 호출하려면 어떻게해야합니까? 아래의 코드 블록 # 2에서 볼 수 있듯이, 심지어 이이라는 주된 활동을 수행하는 방법에 대한 문제가 발생하여 showCustomToast()
으로 전화 할 수 있습니다.
// Problem?
HelloCordova main = (HelloCordova) cordova.getActivity();
main.showCustomToast(toastTitle, toastText, duration);
내가 HelloCordova
에 cordova.getActivity()
캐스팅해야 그렇지 않으면이 이showCustomToast()
기능을 가지고 있음을 인식 할 수 없습니다 : 저는 여기에 현재이 일을 얼마나 추출물이다. 하지만 확실하게 이것은 이 아니며이 올바른 방법입니다. "작동"합니다. 즉, 앱에 표시 할 사용자 토스트를 얻을 수 있습니다. 나는 단지 도울 수는 없지만, 내가 완전히 잘못된 방향으로 갔다는 느낌. 현재로서는 정확히 재사용 가능한 플러그인이 아닙니다!
나는 누군가가 이것을 달성하는 방법의 올바른 길로 나를 설 수 있다면 매우 감사 할 것입니다. 예를 들어 플러그인을 완전히 포기해야합니까? do this 대신에?
이것은 첫 번째 Stackoverflow 질문이므로 변경하거나 명확하게해야하는지 알려주세요. 읽어 주셔서 감사합니다!! 새로운 코르도바 프로젝트를 시작할 때 1
이 HelloCordova
클래스가 자동으로 생성 된
코드 블록 번호 :
여기에 기존 코드입니다. 나는 showCustomToast()
함수를 추가했다.
package io.cordova.hellocordova;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import org.apache.cordova.*;
public class HelloCordova extends CordovaActivity
{
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
super.init();
// Set by <content src="index.html" /> in config.xml
super.loadUrl(Config.getStartUrl());
//super.loadUrl("file:///android_asset/www/index.html")
}
public void showCustomToast(String toastTitleText, String toastDescText, int toastDuration) {
Toast toast = new Toast(this);
toast.setDuration(toastDuration);
LayoutInflater inflater = getLayoutInflater();
View appearance = inflater.inflate(R.layout.toast_layout, (ViewGroup) findViewById(R.id.toastRoot));
toast.setView(appearance);
TextView toastTitle = (TextView) appearance.findViewById(R.id.toastTitle);
toastTitle.setText(toastTitleText);
TextView toastDesc = (TextView) appearance.findViewById(R.id.toastDescription);
toastDesc.setText(toastDescText);
toast.show();
}
}
코드 블록 # 2
코르도바 플러그인의 자바 부분입니다.
package com.example.plugins.toast;
//Problem?
import io.cordova.hellocordova.HelloCordova;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.Context;
import android.util.Log;
import android.widget.Toast;
public class ToastPlugin extends CordovaPlugin {
final String LOG_TAG = "ToastLog";
public static final String ACTION_NORMAL_TOAST = "normalToast";
public static final String ACTION_CUSTOM_TOAST = "customToast";
@Override
public boolean execute(String action, JSONArray args,
CallbackContext callbackContext) throws JSONException {
final JSONObject arg_object = args.getJSONObject(0);
final String toastTitle = arg_object.getString("toastTitle");
final String toastText = arg_object.getString("toastText");
final String toastDuration = arg_object.getString("toastDuration");
final CallbackContext ctx = callbackContext;
try {
if (ACTION_NORMAL_TOAST.equals(action)) {
Log.d(LOG_TAG, "Normal toast: " + toastText);
Runnable runnable = new Runnable() {
public void run() {
Context context = cordova.getActivity()
.getApplicationContext();
int duration = Toast.LENGTH_SHORT;
if (toastDuration.equals("LONG")) {
duration = Toast.LENGTH_LONG;
}
Toast.makeText(context, toastText, duration).show();
}
};
this.cordova.getActivity().runOnUiThread(runnable);
callbackContext.success();
return true;
} else if (ACTION_CUSTOM_TOAST.equals(action)) {
Log.d(LOG_TAG, "Custom toast: " + toastTitle + ": " + toastText);
Runnable runnable = new Runnable() {
public void run() {
int duration = Toast.LENGTH_SHORT;
if (toastDuration.equals("LONG")) {
duration = Toast.LENGTH_LONG;
}
//Problem?
HelloCordova main = (HelloCordova) cordova
.getActivity();
main.showCustomToast(toastTitle, toastText, duration);
ctx.success();
}
};
this.cordova.getActivity().runOnUiThread(runnable);
callbackContext.success();
return true;
}
callbackContext.error("Invalid action");
return false;
} catch (Exception e) {
System.err.println("Exception: " + e.getMessage());
callbackContext.error(e.getMessage());
return false;
}
}
}
편집 : 다음은 저에게 효과가있는 해결책입니다. 아래의 답변에서 QuickFix가 언급했듯이 이제 사용자 정의 토스트 코드가 플러그인에 포함됩니다.
package com.example.plugins.toast;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.Context;
import android.content.res.Resources;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
public class ToastPlugin extends CordovaPlugin {
final String LOG_TAG = "ToastLog";
public static final String ACTION_NORMAL_TOAST = "normalToast";
public static final String ACTION_CUSTOM_TOAST = "customToast";
@Override
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
final JSONObject arg_object = args.getJSONObject(0);
final String toastTitle = arg_object.getString("toastTitle");
final String toastText = arg_object.getString("toastText");
final String toastDuration = arg_object.getString("toastDuration");
try {
if (ACTION_NORMAL_TOAST.equals(action)) {
Log.i(LOG_TAG, "[Normal toast] toastText: " + toastText);
Runnable runnable = new Runnable() {
public void run() {
Context context = cordova.getActivity().getApplicationContext();
int duration = Toast.LENGTH_SHORT;
if (toastDuration.equals("LONG")) {
duration = Toast.LENGTH_LONG;
}
Toast.makeText(context, toastText, duration).show();
}
};
this.cordova.getActivity().runOnUiThread(runnable);
callbackContext.success();
return true;
} else if (ACTION_CUSTOM_TOAST.equals(action)) {
Log.i(LOG_TAG, "[Custom toast] toastTitle: " + toastTitle + "\n toastText: " + toastText);
Runnable runnable = new Runnable() {
public void run() {
int duration = Toast.LENGTH_SHORT;
if (toastDuration.equals("LONG")) {
duration = Toast.LENGTH_LONG;
}
Context context = cordova.getActivity().getApplicationContext();
Toast toast = new Toast(context);
toast.setDuration(duration);
LayoutInflater inflater = LayoutInflater.from(context);
Resources resources = context.getResources();
String packageName = context.getPackageName();
View appearance = inflater.inflate(resources.getIdentifier("toast_layout","layout",packageName),null);
toast.setView(appearance);
TextView toastTitleView = (TextView) appearance.findViewById(resources.getIdentifier("toastTitle","id",packageName));
toastTitleView.setText(toastTitle);
TextView toastDesc = (TextView) appearance.findViewById(resources.getIdentifier("toastDescription","id",packageName));
toastDesc.setText(toastText);
toast.show();
}
};
this.cordova.getActivity().runOnUiThread(runnable);
callbackContext.success();
return true;
}
callbackContext.error("Invalid action");
return false;
} catch (Exception e) {
System.err.println("Exception: " + e.getMessage());
callbackContext.error(e.getMessage());
return false;
}
}
}
감사 @QuickFix와 함수
R.layout.layoutname
및R.id.viewname
에 교체해야합니다, 당신이 할 수있는 몰랐다! 그 트릭을했습니다. 비슷한 일로 도움이 필요한 사람에게는 저에게 맞는 코드를 보여주기 위해 원래 질문을 업데이트했습니다. 다시 한 번 고마워, 고마워! – mank