Re-implement Editbox on Android platform.

This PR also fixed issue:

https://github.com/cocos2d/cocos2d-x/issues/9572

For the new EditBox:

1. Added a ResizeLayout for updating layout when soft keyboard is shown.
This is because some Android devices won't refresh the view and when
the view is panned, the native EditText will turn black. This is really
a hack, but it works for many Android devices from 2.3 to 5.0.

When keyboard is beginning to show, the ResizeLayout's doLayout
method will be called 24 frames per second. Once the keyboard is closed,
or the user begins to input, the doLayout method will be disabled.

2. EditText is working in a different UI thread, so all the data
are passed to GL thread via callbacks in UI thead.

3. It also overrides onKeyDown method in Cocos2dxEditBox.
When the EditText got the focus, users could press back key to exit
the game. This behavior is not allowed. We give developer the choice to
handle back key event manually.
This commit is contained in:
andyque 2015-08-07 17:27:15 +08:00
parent 22812cbc23
commit a35e89225e
39 changed files with 1436 additions and 745 deletions

View File

@ -29,11 +29,9 @@ import android.hardware.Sensor;
import android.hardware.SensorEvent; import android.hardware.SensorEvent;
import android.hardware.SensorEventListener; import android.hardware.SensorEventListener;
import android.hardware.SensorManager; import android.hardware.SensorManager;
import android.util.Log;
import android.view.Display; import android.view.Display;
import android.view.Surface; import android.view.Surface;
import android.view.WindowManager; import android.view.WindowManager;
import android.os.Build.*;
public class Cocos2dxAccelerometer implements SensorEventListener { public class Cocos2dxAccelerometer implements SensorEventListener {
// =========================================================== // ===========================================================

View File

@ -23,13 +23,6 @@ THE SOFTWARE.
****************************************************************************/ ****************************************************************************/
package org.cocos2dx.lib; package org.cocos2dx.lib;
import javax.microedition.khronos.egl.EGL10;
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.egl.EGLDisplay;
import org.cocos2dx.lib.Cocos2dxHelper.Cocos2dxHelperListener;
import com.chukong.cocosplay.client.CocosPlayClient;
import android.app.Activity; import android.app.Activity;
import android.content.Context; import android.content.Context;
import android.content.Intent; import android.content.Intent;
@ -39,14 +32,63 @@ import android.graphics.PixelFormat;
import android.opengl.GLSurfaceView; import android.opengl.GLSurfaceView;
import android.os.Build; import android.os.Build;
import android.os.Bundle; import android.os.Bundle;
import android.os.Handler;
import android.os.Message; import android.os.Message;
import android.preference.PreferenceManager.OnActivityResultListener; import android.preference.PreferenceManager.OnActivityResultListener;
import android.util.AttributeSet;
import android.util.Log; import android.util.Log;
import android.view.ViewGroup; import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.FrameLayout; import android.widget.FrameLayout;
import java.util.Arrays; import com.chukong.cocosplay.client.CocosPlayClient;
import java.util.Comparator;
import org.cocos2dx.lib.Cocos2dxHelper.Cocos2dxHelperListener;
import javax.microedition.khronos.egl.EGL10;
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.egl.EGLDisplay;
class ResizeLayout extends FrameLayout{
private boolean mEnableForceDoLayout = false;
public ResizeLayout(Context context){
super(context);
}
public ResizeLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}
public void setEnableForceDoLayout(boolean flag){
mEnableForceDoLayout = flag;
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
super.onLayout(changed, l, t, r, b);
if(mEnableForceDoLayout){
/*This is a hot-fix for some android devices which don't do layout when the main window
* is paned. We refersh the layout in 24 frames per seconds.
* When the editBox is lose focus or when user begin to type, the do layout is disabled.
*/
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
//Do something after 100ms
requestLayout();
invalidate();
}
}, 1000 / 24);
}
}
}
public abstract class Cocos2dxActivity extends Activity implements Cocos2dxHelperListener { public abstract class Cocos2dxActivity extends Activity implements Cocos2dxHelperListener {
// =========================================================== // ===========================================================
@ -65,6 +107,11 @@ public abstract class Cocos2dxActivity extends Activity implements Cocos2dxHelpe
private static Cocos2dxActivity sContext = null; private static Cocos2dxActivity sContext = null;
private Cocos2dxVideoHelper mVideoHelper = null; private Cocos2dxVideoHelper mVideoHelper = null;
private Cocos2dxWebViewHelper mWebViewHelper = null; private Cocos2dxWebViewHelper mWebViewHelper = null;
private Cocos2dxEditBoxHelper mEditBoxHelper = null;
public Cocos2dxGLSurfaceView getGLSurfaceView(){
return mGLSurfaceView;
}
public class Cocos2dxEGLConfigChooser implements GLSurfaceView.EGLConfigChooser public class Cocos2dxEGLConfigChooser implements GLSurfaceView.EGLConfigChooser
{ {
@ -268,6 +315,13 @@ public abstract class Cocos2dxActivity extends Activity implements Cocos2dxHelpe
if(mWebViewHelper == null){ if(mWebViewHelper == null){
mWebViewHelper = new Cocos2dxWebViewHelper(mFrameLayout); mWebViewHelper = new Cocos2dxWebViewHelper(mFrameLayout);
} }
if(mEditBoxHelper == null){
mEditBoxHelper = new Cocos2dxEditBoxHelper(mFrameLayout);
}
Window window = this.getWindow();
window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
} }
//native method,call GLViewImpl::getGLContextAttrs() to get the OpenGL ES context attributions //native method,call GLViewImpl::getGLContextAttrs() to get the OpenGL ES context attributions
@ -293,6 +347,7 @@ public abstract class Cocos2dxActivity extends Activity implements Cocos2dxHelpe
if (hasFocus) { if (hasFocus) {
Cocos2dxHelper.onResume(); Cocos2dxHelper.onResume();
mGLSurfaceView.onResume(); mGLSurfaceView.onResume();
mGLSurfaceView.requestFocus();
} }
} }
@ -301,6 +356,7 @@ public abstract class Cocos2dxActivity extends Activity implements Cocos2dxHelpe
super.onPause(); super.onPause();
Cocos2dxHelper.onPause(); Cocos2dxHelper.onPause();
mGLSurfaceView.onPause(); mGLSurfaceView.onPause();
mGLSurfaceView.setSoftKeyboardShown(false);
} }
@Override @Override
@ -315,14 +371,6 @@ public abstract class Cocos2dxActivity extends Activity implements Cocos2dxHelpe
msg.obj = new Cocos2dxHandler.DialogMessage(pTitle, pMessage); msg.obj = new Cocos2dxHandler.DialogMessage(pTitle, pMessage);
this.mHandler.sendMessage(msg); this.mHandler.sendMessage(msg);
} }
@Override
public void showEditTextDialog(final String pTitle, final String pContent, final int pInputMode, final int pInputFlag, final int pReturnType, final int pMaxLength) {
Message msg = new Message();
msg.what = Cocos2dxHandler.HANDLER_SHOW_EDITBOX_DIALOG;
msg.obj = new Cocos2dxHandler.EditBoxMessage(pTitle, pContent, pInputMode, pInputFlag, pReturnType, pMaxLength);
this.mHandler.sendMessage(msg);
}
@Override @Override
public void runOnGLThread(final Runnable pRunnable) { public void runOnGLThread(final Runnable pRunnable) {
@ -340,7 +388,7 @@ public abstract class Cocos2dxActivity extends Activity implements Cocos2dxHelpe
} }
protected FrameLayout mFrameLayout = null; protected ResizeLayout mFrameLayout = null;
// =========================================================== // ===========================================================
// Methods // Methods
// =========================================================== // ===========================================================
@ -350,7 +398,9 @@ public abstract class Cocos2dxActivity extends Activity implements Cocos2dxHelpe
ViewGroup.LayoutParams framelayout_params = ViewGroup.LayoutParams framelayout_params =
new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT); ViewGroup.LayoutParams.MATCH_PARENT);
mFrameLayout = new FrameLayout(this);
mFrameLayout = new ResizeLayout(this);
mFrameLayout.setLayoutParams(framelayout_params); mFrameLayout.setLayoutParams(framelayout_params);
// Cocos2dxEditText layout // Cocos2dxEditText layout
@ -360,7 +410,7 @@ public abstract class Cocos2dxActivity extends Activity implements Cocos2dxHelpe
Cocos2dxEditText edittext = new Cocos2dxEditText(this); Cocos2dxEditText edittext = new Cocos2dxEditText(this);
edittext.setLayoutParams(edittext_layout_params); edittext.setLayoutParams(edittext_layout_params);
// ...add to FrameLayout
mFrameLayout.addView(edittext); mFrameLayout.addView(edittext);
// Cocos2dxGLSurfaceView // Cocos2dxGLSurfaceView
@ -379,6 +429,7 @@ public abstract class Cocos2dxActivity extends Activity implements Cocos2dxHelpe
// Set framelayout as the content view // Set framelayout as the content view
setContentView(mFrameLayout); setContentView(mFrameLayout);
} }
public Cocos2dxGLSurfaceView onCreateView() { public Cocos2dxGLSurfaceView onCreateView() {
Cocos2dxGLSurfaceView glSurfaceView = new Cocos2dxGLSurfaceView(this); Cocos2dxGLSurfaceView glSurfaceView = new Cocos2dxGLSurfaceView(this);

View File

@ -1,6 +1,6 @@
/**************************************************************************** /****************************************************************************
Copyright (c) 2010-2012 cocos2d-x.org Copyright (c) 2010-2012 cocos2d-x.org
Copyright (c) 2013-2014 Chukong Technologies Inc. Copyright (c) 2013-2015 Chukong Technologies Inc.
http://www.cocos2d-x.org http://www.cocos2d-x.org
@ -24,9 +24,6 @@ THE SOFTWARE.
****************************************************************************/ ****************************************************************************/
package org.cocos2dx.lib; package org.cocos2dx.lib;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import android.content.Context; import android.content.Context;
import android.graphics.Bitmap; import android.graphics.Bitmap;
import android.graphics.Canvas; import android.graphics.Canvas;
@ -38,6 +35,9 @@ import android.text.TextPaint;
import android.text.TextUtils; import android.text.TextUtils;
import android.util.Log; import android.util.Log;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
public final class Cocos2dxBitmap { public final class Cocos2dxBitmap {
// =========================================================== // ===========================================================
// Constants // Constants
@ -211,7 +211,7 @@ public final class Cocos2dxBitmap {
return null; return null;
} }
private static int getFontSizeAccordingHeight(int height) { public static int getFontSizeAccordingHeight(int height) {
TextPaint paint = new TextPaint(); TextPaint paint = new TextPaint();
Rect bounds = new Rect(); Rect bounds = new Rect();

View File

@ -0,0 +1,238 @@
/****************************************************************************
Copyright (c) 2010-2012 cocos2d-x.org
Copyright (c) 2013-2015 Chukong Technologies Inc.
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
package org.cocos2dx.lib;
import android.content.Context;
import android.graphics.Color;
import android.text.InputFilter;
import android.text.InputType;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.FrameLayout;
public class Cocos2dxEditBox extends EditText {
/**
* The user is allowed to enter any text, including line breaks.
*/
private final int kEditBoxInputModeAny = 0;
/**
* The user is allowed to enter an e-mail address.
*/
private final int kEditBoxInputModeEmailAddr = 1;
/**
* The user is allowed to enter an integer value.
*/
private final int kEditBoxInputModeNumeric = 2;
/**
* The user is allowed to enter a phone number.
*/
private final int kEditBoxInputModePhoneNumber = 3;
/**
* The user is allowed to enter a URL.
*/
private final int kEditBoxInputModeUrl = 4;
/**
* The user is allowed to enter a real number value. This extends kEditBoxInputModeNumeric by allowing a decimal point.
*/
private final int kEditBoxInputModeDecimal = 5;
/**
* The user is allowed to enter any text, except for line breaks.
*/
private final int kEditBoxInputModeSingleLine = 6;
/**
* Indicates that the text entered is confidential data that should be obscured whenever possible. This implies EDIT_BOX_INPUT_FLAG_SENSITIVE.
*/
private final int kEditBoxInputFlagPassword = 0;
/**
* Indicates that the text entered is sensitive data that the implementation must never store into a dictionary or table for use in predictive, auto-completing, or other accelerated input schemes. A credit card number is an example of sensitive data.
*/
private final int kEditBoxInputFlagSensitive = 1;
/**
* This flag is a hint to the implementation that during text editing, the initial letter of each word should be capitalized.
*/
private final int kEditBoxInputFlagInitialCapsWord = 2;
/**
* This flag is a hint to the implementation that during text editing, the initial letter of each sentence should be capitalized.
*/
private final int kEditBoxInputFlagInitialCapsSentence = 3;
/**
* Capitalize all characters automatically.
*/
private final int kEditBoxInputFlagInitialCapsAllCharacters = 4;
private final int kKeyboardReturnTypeDefault = 0;
private final int kKeyboardReturnTypeDone = 1;
private final int kKeyboardReturnTypeSend = 2;
private final int kKeyboardReturnTypeSearch = 3;
private final int kKeyboardReturnTypeGo = 4;
private int mInputFlagConstraints;
private int mInputModeContraints;
private int mMaxLength;
public Cocos2dxEditBox(Context context){
super(context);
this.setFocusable(true);
this.setFocusableInTouchMode(true);
this.setInputFlag(kEditBoxInputFlagInitialCapsAllCharacters);
this.setInputMode(kEditBoxInputModeSingleLine);
this.setReturnType(kKeyboardReturnTypeDefault);
this.setHintTextColor(Color.GRAY);
this.setVisibility(View.INVISIBLE);
this.setBackgroundColor(Color.TRANSPARENT);
this.setTextColor(Color.WHITE);
this.setSingleLine();
}
public void setEditBoxViewRect(int left, int top, int maxWidth, int maxHeight) {
FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT,
FrameLayout.LayoutParams.WRAP_CONTENT);
layoutParams.leftMargin = left;
layoutParams.topMargin = top;
layoutParams.width = maxWidth;
layoutParams.height = maxHeight;
layoutParams.gravity = Gravity.TOP | Gravity.LEFT;
this.setLayoutParams(layoutParams);
}
public void setMaxLength(int maxLength){
this.mMaxLength = maxLength;
this.setFilters(new InputFilter[]{new InputFilter.LengthFilter(this.mMaxLength) });
}
public void setMultilineEnabled(boolean flag){
this.mInputModeContraints |= InputType.TYPE_TEXT_FLAG_MULTI_LINE;
}
public void setReturnType(int returnType) {
switch (returnType) {
case kKeyboardReturnTypeDefault:
this.setImeOptions(EditorInfo.IME_ACTION_NONE | EditorInfo.IME_FLAG_NO_EXTRACT_UI);
break;
case kKeyboardReturnTypeDone:
this.setImeOptions(EditorInfo.IME_ACTION_DONE | EditorInfo.IME_FLAG_NO_EXTRACT_UI);
break;
case kKeyboardReturnTypeSend:
this.setImeOptions(EditorInfo.IME_ACTION_SEND | EditorInfo.IME_FLAG_NO_EXTRACT_UI);
break;
case kKeyboardReturnTypeSearch:
this.setImeOptions(EditorInfo.IME_ACTION_SEARCH | EditorInfo.IME_FLAG_NO_EXTRACT_UI);
break;
case kKeyboardReturnTypeGo:
this.setImeOptions(EditorInfo.IME_ACTION_GO | EditorInfo.IME_FLAG_NO_EXTRACT_UI);
break;
default:
this.setImeOptions(EditorInfo.IME_ACTION_NONE | EditorInfo.IME_FLAG_NO_EXTRACT_UI);
break;
}
}
public void setInputMode(int inputMode){
switch (inputMode) {
case kEditBoxInputModeAny:
this.mInputModeContraints = InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_MULTI_LINE;
break;
case kEditBoxInputModeEmailAddr:
this.mInputModeContraints = InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS;
break;
case kEditBoxInputModeNumeric:
this.mInputModeContraints = InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_SIGNED;
break;
case kEditBoxInputModePhoneNumber:
this.mInputModeContraints = InputType.TYPE_CLASS_PHONE;
break;
case kEditBoxInputModeUrl:
this.mInputModeContraints = InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_URI;
break;
case kEditBoxInputModeDecimal:
this.mInputModeContraints = InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL | InputType.TYPE_NUMBER_FLAG_SIGNED;
break;
case kEditBoxInputModeSingleLine:
this.mInputModeContraints = InputType.TYPE_CLASS_TEXT;
break;
default:
break;
}
this.setInputType(this.mInputModeContraints | this.mInputFlagConstraints);
}
@Override
public boolean onKeyDown(final int pKeyCode, final KeyEvent pKeyEvent) {
switch (pKeyCode) {
case KeyEvent.KEYCODE_BACK:
Cocos2dxActivity activity = (Cocos2dxActivity)this.getContext();
activity.getGLSurfaceView().requestFocus();
return true;
default:
return super.onKeyDown(pKeyCode, pKeyEvent);
}
}
public void setInputFlag(int inputFlag) {
switch (inputFlag) {
case kEditBoxInputFlagPassword:
this.mInputFlagConstraints = InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD;
break;
case kEditBoxInputFlagSensitive:
this.mInputFlagConstraints = InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS;
break;
case kEditBoxInputFlagInitialCapsWord:
this.mInputFlagConstraints = InputType.TYPE_TEXT_FLAG_CAP_WORDS;
break;
case kEditBoxInputFlagInitialCapsSentence:
this.mInputFlagConstraints = InputType.TYPE_TEXT_FLAG_CAP_SENTENCES;
break;
case kEditBoxInputFlagInitialCapsAllCharacters:
this.mInputFlagConstraints = InputType.TYPE_TEXT_FLAG_CAP_CHARACTERS;
break;
default:
break;
}
this.setInputType(this.mInputFlagConstraints | this.mInputModeContraints);
}
}

View File

@ -1,321 +0,0 @@
/****************************************************************************
Copyright (c) 2010-2012 cocos2d-x.org
Copyright (c) 2013-2014 Chukong Technologies Inc.
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
package org.cocos2dx.lib;
import android.app.Dialog;
import android.content.Context;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.text.InputFilter;
import android.text.InputType;
import android.util.TypedValue;
import android.view.KeyEvent;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
public class Cocos2dxEditBoxDialog extends Dialog {
// ===========================================================
// Constants
// ===========================================================
/**
* The user is allowed to enter any text, including line breaks.
*/
private final int kEditBoxInputModeAny = 0;
/**
* The user is allowed to enter an e-mail address.
*/
private final int kEditBoxInputModeEmailAddr = 1;
/**
* The user is allowed to enter an integer value.
*/
private final int kEditBoxInputModeNumeric = 2;
/**
* The user is allowed to enter a phone number.
*/
private final int kEditBoxInputModePhoneNumber = 3;
/**
* The user is allowed to enter a URL.
*/
private final int kEditBoxInputModeUrl = 4;
/**
* The user is allowed to enter a real number value. This extends kEditBoxInputModeNumeric by allowing a decimal point.
*/
private final int kEditBoxInputModeDecimal = 5;
/**
* The user is allowed to enter any text, except for line breaks.
*/
private final int kEditBoxInputModeSingleLine = 6;
/**
* Indicates that the text entered is confidential data that should be obscured whenever possible. This implies EDIT_BOX_INPUT_FLAG_SENSITIVE.
*/
private final int kEditBoxInputFlagPassword = 0;
/**
* Indicates that the text entered is sensitive data that the implementation must never store into a dictionary or table for use in predictive, auto-completing, or other accelerated input schemes. A credit card number is an example of sensitive data.
*/
private final int kEditBoxInputFlagSensitive = 1;
/**
* This flag is a hint to the implementation that during text editing, the initial letter of each word should be capitalized.
*/
private final int kEditBoxInputFlagInitialCapsWord = 2;
/**
* This flag is a hint to the implementation that during text editing, the initial letter of each sentence should be capitalized.
*/
private final int kEditBoxInputFlagInitialCapsSentence = 3;
/**
* Capitalize all characters automatically.
*/
private final int kEditBoxInputFlagInitialCapsAllCharacters = 4;
private final int kKeyboardReturnTypeDefault = 0;
private final int kKeyboardReturnTypeDone = 1;
private final int kKeyboardReturnTypeSend = 2;
private final int kKeyboardReturnTypeSearch = 3;
private final int kKeyboardReturnTypeGo = 4;
// ===========================================================
// Fields
// ===========================================================
private EditText mInputEditText;
private TextView mTextViewTitle;
private final String mTitle;
private final String mMessage;
private final int mInputMode;
private final int mInputFlag;
private final int mReturnType;
private final int mMaxLength;
private int mInputFlagConstraints;
private int mInputModeContraints;
private boolean mIsMultiline;
// ===========================================================
// Constructors
// ===========================================================
public Cocos2dxEditBoxDialog(final Context pContext, final String pTitle, final String pMessage, final int pInputMode, final int pInputFlag, final int pReturnType, final int pMaxLength) {
super(pContext, android.R.style.Theme_Translucent_NoTitleBar_Fullscreen);
// super(context, R.style.Theme_Translucent);
this.mTitle = pTitle;
this.mMessage = pMessage;
this.mInputMode = pInputMode;
this.mInputFlag = pInputFlag;
this.mReturnType = pReturnType;
this.mMaxLength = pMaxLength;
}
@Override
protected void onCreate(final Bundle pSavedInstanceState) {
super.onCreate(pSavedInstanceState);
this.getWindow().setBackgroundDrawable(new ColorDrawable(0x80000000));
final LinearLayout layout = new LinearLayout(this.getContext());
layout.setOrientation(LinearLayout.VERTICAL);
final LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
this.mTextViewTitle = new TextView(this.getContext());
final LinearLayout.LayoutParams textviewParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
textviewParams.leftMargin = textviewParams.rightMargin = this.convertDipsToPixels(10);
this.mTextViewTitle.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 20);
layout.addView(this.mTextViewTitle, textviewParams);
this.mInputEditText = new EditText(this.getContext());
final LinearLayout.LayoutParams editTextParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
editTextParams.leftMargin = editTextParams.rightMargin = this.convertDipsToPixels(10);
layout.addView(this.mInputEditText, editTextParams);
this.setContentView(layout, layoutParams);
this.getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
this.mTextViewTitle.setText(this.mTitle);
this.mInputEditText.setText(this.mMessage);
int oldImeOptions = this.mInputEditText.getImeOptions();
this.mInputEditText.setImeOptions(oldImeOptions | EditorInfo.IME_FLAG_NO_EXTRACT_UI);
oldImeOptions = this.mInputEditText.getImeOptions();
switch (this.mInputMode) {
case kEditBoxInputModeAny:
this.mInputModeContraints = InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_MULTI_LINE;
break;
case kEditBoxInputModeEmailAddr:
this.mInputModeContraints = InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS;
break;
case kEditBoxInputModeNumeric:
this.mInputModeContraints = InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_SIGNED;
break;
case kEditBoxInputModePhoneNumber:
this.mInputModeContraints = InputType.TYPE_CLASS_PHONE;
break;
case kEditBoxInputModeUrl:
this.mInputModeContraints = InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_URI;
break;
case kEditBoxInputModeDecimal:
this.mInputModeContraints = InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL | InputType.TYPE_NUMBER_FLAG_SIGNED;
break;
case kEditBoxInputModeSingleLine:
this.mInputModeContraints = InputType.TYPE_CLASS_TEXT;
break;
default:
break;
}
if (this.mIsMultiline) {
this.mInputModeContraints |= InputType.TYPE_TEXT_FLAG_MULTI_LINE;
}
this.mInputEditText.setInputType(this.mInputModeContraints | this.mInputFlagConstraints);
switch (this.mInputFlag) {
case kEditBoxInputFlagPassword:
this.mInputFlagConstraints = InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD;
break;
case kEditBoxInputFlagSensitive:
this.mInputFlagConstraints = InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS;
break;
case kEditBoxInputFlagInitialCapsWord:
this.mInputFlagConstraints = InputType.TYPE_TEXT_FLAG_CAP_WORDS;
break;
case kEditBoxInputFlagInitialCapsSentence:
this.mInputFlagConstraints = InputType.TYPE_TEXT_FLAG_CAP_SENTENCES;
break;
case kEditBoxInputFlagInitialCapsAllCharacters:
this.mInputFlagConstraints = InputType.TYPE_TEXT_FLAG_CAP_CHARACTERS;
break;
default:
break;
}
this.mInputEditText.setInputType(this.mInputFlagConstraints | this.mInputModeContraints);
switch (this.mReturnType) {
case kKeyboardReturnTypeDefault:
this.mInputEditText.setImeOptions(oldImeOptions | EditorInfo.IME_ACTION_NONE);
break;
case kKeyboardReturnTypeDone:
this.mInputEditText.setImeOptions(oldImeOptions | EditorInfo.IME_ACTION_DONE);
break;
case kKeyboardReturnTypeSend:
this.mInputEditText.setImeOptions(oldImeOptions | EditorInfo.IME_ACTION_SEND);
break;
case kKeyboardReturnTypeSearch:
this.mInputEditText.setImeOptions(oldImeOptions | EditorInfo.IME_ACTION_SEARCH);
break;
case kKeyboardReturnTypeGo:
this.mInputEditText.setImeOptions(oldImeOptions | EditorInfo.IME_ACTION_GO);
break;
default:
this.mInputEditText.setImeOptions(oldImeOptions | EditorInfo.IME_ACTION_NONE);
break;
}
if (this.mMaxLength > 0) {
this.mInputEditText.setFilters(new InputFilter[] { new InputFilter.LengthFilter(this.mMaxLength) });
}
final Handler initHandler = new Handler();
initHandler.postDelayed(new Runnable() {
@Override
public void run() {
Cocos2dxEditBoxDialog.this.mInputEditText.requestFocus();
Cocos2dxEditBoxDialog.this.mInputEditText.setSelection(Cocos2dxEditBoxDialog.this.mInputEditText.length());
Cocos2dxEditBoxDialog.this.openKeyboard();
}
}, 200);
this.mInputEditText.setOnEditorActionListener(new OnEditorActionListener() {
@Override
public boolean onEditorAction(final TextView v, final int actionId, final KeyEvent event) {
// If user didn't set keyboard type, this callback will be invoked twice with 'KeyEvent.ACTION_DOWN' and 'KeyEvent.ACTION_UP'.
if (actionId != EditorInfo.IME_NULL || (actionId == EditorInfo.IME_NULL && event != null && event.getAction() == KeyEvent.ACTION_DOWN)) {
Cocos2dxHelper.setEditTextDialogResult(Cocos2dxEditBoxDialog.this.mInputEditText.getText().toString());
Cocos2dxEditBoxDialog.this.closeKeyboard();
Cocos2dxEditBoxDialog.this.dismiss();
return true;
}
return false;
}
});
}
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
private int convertDipsToPixels(final float pDIPs) {
final float scale = this.getContext().getResources().getDisplayMetrics().density;
return Math.round(pDIPs * scale);
}
private void openKeyboard() {
final InputMethodManager imm = (InputMethodManager) this.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(this.mInputEditText, 0);
}
private void closeKeyboard() {
final InputMethodManager imm = (InputMethodManager) this.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(this.mInputEditText.getWindowToken(), 0);
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}

View File

@ -0,0 +1,367 @@
/****************************************************************************
Copyright (c) 2010-2012 cocos2d-x.org
Copyright (c) 2013-2015 Chukong Technologies Inc.
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
package org.cocos2dx.lib;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Color;
import android.graphics.Typeface;
import android.text.Editable;
import android.text.InputType;
import android.text.TextWatcher;
import android.util.Log;
import android.util.SparseArray;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.FrameLayout;
import android.widget.TextView;
public class Cocos2dxEditBoxHelper {
private static final String TAG = Cocos2dxEditBoxHelper.class.getSimpleName();
private static Cocos2dxActivity mCocos2dxActivity;
private static ResizeLayout mFrameLayout;
private static SparseArray<Cocos2dxEditBox> mEditBoxArray;
private static int mViewTag = 0;
//Call native methods
private static native void editBoxEditingDidBegin(int index);
public static void __editBoxEditingDidBegin(int index){
editBoxEditingDidBegin(index);
}
private static native void editBoxEditingChanged(int index, String text);
public static void __editBoxEditingChanged(int index, String text){
editBoxEditingChanged(index, text);
}
private static native void editBoxEditingDidEnd(int index, String text);
public static void __editBoxEditingDidEnd(int index, String text){
editBoxEditingDidEnd(index, text);
}
public Cocos2dxEditBoxHelper(ResizeLayout layout) {
Cocos2dxEditBoxHelper.mFrameLayout = layout;
Cocos2dxEditBoxHelper.mCocos2dxActivity = (Cocos2dxActivity) Cocos2dxActivity.getContext();
Cocos2dxEditBoxHelper.mEditBoxArray = new SparseArray<Cocos2dxEditBox>();
}
public static int createEditBox(final int left, final int top, final int width, final int height) {
final int index = mViewTag;
mCocos2dxActivity.runOnUiThread(new Runnable() {
@Override
public void run() {
final Cocos2dxEditBox editBox = new Cocos2dxEditBox(mCocos2dxActivity);
FrameLayout.LayoutParams lParams = new FrameLayout.LayoutParams(
FrameLayout.LayoutParams.WRAP_CONTENT,
FrameLayout.LayoutParams.WRAP_CONTENT);
lParams.leftMargin = left;
lParams.topMargin = top;
lParams.width = width;
lParams.height = height+20;
lParams.gravity = Gravity.TOP | Gravity.LEFT;
mFrameLayout.addView(editBox, lParams);
editBox.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(final CharSequence s, int start, int before, int count) {
mFrameLayout.setEnableForceDoLayout(false);
mCocos2dxActivity.runOnGLThread(new Runnable() {
@Override
public void run() {
Cocos2dxEditBoxHelper.__editBoxEditingChanged(index, s.toString());
}
});
}
@Override
public void afterTextChanged(Editable s) {
}
});
editBox.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus) {
mCocos2dxActivity.runOnGLThread(new Runnable() {
@Override
public void run() {
Cocos2dxEditBoxHelper.__editBoxEditingDidBegin(index);
}
});
editBox.setSelection(editBox.getText().length());
mFrameLayout.setEnableForceDoLayout(true);
mCocos2dxActivity.getGLSurfaceView().setSoftKeyboardShown(true);
Log.d(TAG, "edit box get focus");
} else {
editBox.setVisibility(View.GONE);
mCocos2dxActivity.runOnGLThread(new Runnable() {
@Override
public void run() {
Cocos2dxEditBoxHelper.__editBoxEditingDidEnd(index, editBox.getText().toString());
}
});
mFrameLayout.setEnableForceDoLayout(false);
Log.d(TAG, "edit box lose focus");
}
}
});
editBox.setOnKeyListener(new View.OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
// If the event is a key-down event on the "enter" button
if ((event.getAction() == KeyEvent.ACTION_DOWN) &&
(keyCode == KeyEvent.KEYCODE_ENTER)) {
//if editbox doesn't support multiline, just hide the keyboard
if ((editBox.getInputType() & InputType.TYPE_TEXT_FLAG_MULTI_LINE) != InputType.TYPE_TEXT_FLAG_MULTI_LINE) {
Cocos2dxEditBoxHelper.closeKeyboard(index);
mCocos2dxActivity.getGLSurfaceView().requestFocus();
return true;
}
}
return false;
}
});
editBox.setOnEditorActionListener(new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_DONE) {
Cocos2dxEditBoxHelper.closeKeyboard(index);
mCocos2dxActivity.getGLSurfaceView().requestFocus();
}
return false;
}
});
mEditBoxArray.put(index, editBox);
}
});
return mViewTag++;
}
public static void removeEditBox(final int index) {
mCocos2dxActivity.runOnUiThread(new Runnable() {
@Override
public void run() {
Cocos2dxEditBox editBox = mEditBoxArray.get(index);
if (editBox != null) {
mEditBoxArray.remove(index);
mFrameLayout.removeView(editBox);
Log.e(TAG, "remove EditBox");
}
}
});
}
public static void setFont(final int index, final String fontName, final float fontSize){
mCocos2dxActivity.runOnUiThread(new Runnable() {
@Override
public void run() {
Cocos2dxEditBox editBox = mEditBoxArray.get(index);
if (editBox != null) {
Typeface tf;
if (!fontName.isEmpty()) {
tf = Typeface.create(fontName, Typeface.NORMAL);
}else{
tf = Typeface.DEFAULT;
}
//TODO: The font size is not the same across all the anroid devices...
if (fontSize >= 0){
editBox.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSize);
}
editBox.setTypeface(tf);
}
}
});
}
public static void setFontColor(final int index, final int red, final int green, final int blue, final int alpha){
mCocos2dxActivity.runOnUiThread(new Runnable() {
@Override
public void run() {
Cocos2dxEditBox editBox = mEditBoxArray.get(index);
if (editBox != null) {
editBox.setTextColor(Color.argb(alpha, red, green, blue));
}
}
});
}
public static void setPlaceHolderText(final int index, final String text){
mCocos2dxActivity.runOnUiThread(new Runnable() {
@Override
public void run() {
Cocos2dxEditBox editBox = mEditBoxArray.get(index);
if (editBox != null) {
editBox.setHint(text);
}
}
});
}
public static void setPlaceHolderTextColor(final int index, final int red, final int green, final int blue, final int alpha){
mCocos2dxActivity.runOnUiThread(new Runnable() {
@Override
public void run() {
Cocos2dxEditBox editBox = mEditBoxArray.get(index);
if (editBox != null) {
editBox.setHintTextColor(Color.argb(alpha, red, green, blue));
}
}
});
}
public static void setMaxLength(final int index, final int maxLength) {
mCocos2dxActivity.runOnUiThread(new Runnable() {
@Override
public void run() {
Cocos2dxEditBox editBox = mEditBoxArray.get(index);
if (editBox != null) {
editBox.setMaxLength(maxLength);
}
}
});
}
public static void setVisible(final int index, final boolean visible) {
mCocos2dxActivity.runOnUiThread(new Runnable() {
@Override
public void run() {
Cocos2dxEditBox editBox = mEditBoxArray.get(index);
if (editBox != null) {
editBox.setVisibility(visible ? View.VISIBLE : View.GONE);
if (visible) {
editBox.requestFocus();
Cocos2dxEditBoxHelper.openKeyboard(index);
}else{
mCocos2dxActivity.getGLSurfaceView().requestFocus();
Cocos2dxEditBoxHelper.closeKeyboard(index);
}
}
}
});
}
public static void setText(final int index, final String text){
mCocos2dxActivity.runOnUiThread(new Runnable() {
@Override
public void run() {
Cocos2dxEditBox editBox = mEditBoxArray.get(index);
if (editBox != null) {
editBox.setText(text);
}
}
});
}
public static void setReturnType(final int index, final int returnType) {
mCocos2dxActivity.runOnUiThread(new Runnable() {
@Override
public void run() {
Cocos2dxEditBox editBox = mEditBoxArray.get(index);
if (editBox != null) {
editBox.setReturnType(returnType);
}
}
});
}
public static void setInputMode(final int index, final int inputMode) {
mCocos2dxActivity.runOnUiThread(new Runnable() {
@Override
public void run() {
Cocos2dxEditBox editBox = mEditBoxArray.get(index);
if (editBox != null) {
editBox.setInputMode(inputMode);
}
}
});
}
public static void setInputFlag(final int index, final int inputFlag) {
mCocos2dxActivity.runOnUiThread(new Runnable() {
@Override
public void run() {
Cocos2dxEditBox editBox = mEditBoxArray.get(index);
if (editBox != null) {
editBox.setInputFlag(inputFlag);
}
}
});
}
public static void setEditBoxViewRect(final int index, final int left, final int top, final int maxWidth, final int maxHeight) {
mCocos2dxActivity.runOnUiThread(new Runnable() {
@Override
public void run() {
Cocos2dxEditBox editBox = mEditBoxArray.get(index);
if (editBox != null) {
editBox.setEditBoxViewRect(left, top, maxWidth, maxHeight);
}
}
});
}
public static void openKeyboard(int index) {
final InputMethodManager imm = (InputMethodManager) mCocos2dxActivity.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
Cocos2dxEditBox editBox = mEditBoxArray.get(index);
if (null != editBox) {
imm.showSoftInput(editBox, 0);
mCocos2dxActivity.getGLSurfaceView().setSoftKeyboardShown(true);
}
}
public static void closeKeyboard(int index) {
final InputMethodManager imm = (InputMethodManager) mCocos2dxActivity.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
Cocos2dxEditBox editBox = mEditBoxArray.get(index);
if (null != editBox) {
imm.hideSoftInputFromWindow(editBox.getWindowToken(), 0);
mCocos2dxActivity.getGLSurfaceView().setSoftKeyboardShown(false);
}
}
}

View File

@ -23,6 +23,7 @@ THE SOFTWARE.
****************************************************************************/ ****************************************************************************/
package org.cocos2dx.lib; package org.cocos2dx.lib;
import android.app.Activity;
import android.content.Context; import android.content.Context;
import android.opengl.GLSurfaceView; import android.opengl.GLSurfaceView;
import android.os.Handler; import android.os.Handler;
@ -31,6 +32,7 @@ import android.util.AttributeSet;
import android.util.Log; import android.util.Log;
import android.view.KeyEvent; import android.view.KeyEvent;
import android.view.MotionEvent; import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager; import android.view.inputmethod.InputMethodManager;
public class Cocos2dxGLSurfaceView extends GLSurfaceView { public class Cocos2dxGLSurfaceView extends GLSurfaceView {
@ -56,6 +58,17 @@ public class Cocos2dxGLSurfaceView extends GLSurfaceView {
private Cocos2dxRenderer mCocos2dxRenderer; private Cocos2dxRenderer mCocos2dxRenderer;
private Cocos2dxEditText mCocos2dxEditText; private Cocos2dxEditText mCocos2dxEditText;
public boolean isSoftKeyboardShown() {
return mSoftKeyboardShown;
}
public void setSoftKeyboardShown(boolean softKeyboardShown) {
this.mSoftKeyboardShown = softKeyboardShown;
}
private boolean mSoftKeyboardShown = false;
// =========================================================== // ===========================================================
// Constructors // Constructors
// =========================================================== // ===========================================================
@ -187,6 +200,14 @@ public class Cocos2dxGLSurfaceView extends GLSurfaceView {
final float[] xs = new float[pointerNumber]; final float[] xs = new float[pointerNumber];
final float[] ys = new float[pointerNumber]; final float[] ys = new float[pointerNumber];
if (mSoftKeyboardShown){
InputMethodManager imm = (InputMethodManager)this.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
View view = ((Activity)this.getContext()).getCurrentFocus();
imm.hideSoftInputFromWindow(view.getWindowToken(),0);
this.requestFocus();
mSoftKeyboardShown = false;
}
for (int i = 0; i < pointerNumber; i++) { for (int i = 0; i < pointerNumber; i++) {
ids[i] = pMotionEvent.getPointerId(i); ids[i] = pMotionEvent.getPointerId(i);
xs[i] = pMotionEvent.getX(i); xs[i] = pMotionEvent.getX(i);

View File

@ -24,20 +24,19 @@ THE SOFTWARE.
package org.cocos2dx.lib; package org.cocos2dx.lib;
import java.lang.ref.WeakReference;
import android.app.AlertDialog; import android.app.AlertDialog;
import android.content.DialogInterface; import android.content.DialogInterface;
import android.os.Handler; import android.os.Handler;
import android.os.Message; import android.os.Message;
import java.lang.ref.WeakReference;
public class Cocos2dxHandler extends Handler { public class Cocos2dxHandler extends Handler {
// =========================================================== // ===========================================================
// Constants // Constants
// =========================================================== // ===========================================================
public final static int HANDLER_SHOW_DIALOG = 1; public final static int HANDLER_SHOW_DIALOG = 1;
public final static int HANDLER_SHOW_EDITBOX_DIALOG = 2;
// =========================================================== // ===========================================================
// Fields // Fields
// =========================================================== // ===========================================================
@ -64,12 +63,9 @@ public class Cocos2dxHandler extends Handler {
public void handleMessage(Message msg) { public void handleMessage(Message msg) {
switch (msg.what) { switch (msg.what) {
case Cocos2dxHandler.HANDLER_SHOW_DIALOG: case Cocos2dxHandler.HANDLER_SHOW_DIALOG:
showDialog(msg); showDialog(msg);
break; break;
case Cocos2dxHandler.HANDLER_SHOW_EDITBOX_DIALOG:
showEditBoxDialog(msg);
break;
} }
} }
@ -89,17 +85,7 @@ public class Cocos2dxHandler extends Handler {
} }
}).create().show(); }).create().show();
} }
private void showEditBoxDialog(Message msg) {
EditBoxMessage editBoxMessage = (EditBoxMessage)msg.obj;
new Cocos2dxEditBoxDialog(this.mActivity.get(),
editBoxMessage.title,
editBoxMessage.content,
editBoxMessage.inputMode,
editBoxMessage.inputFlag,
editBoxMessage.returnType,
editBoxMessage.maxLength).show();
}
// =========================================================== // ===========================================================
// Inner and Anonymous Classes // Inner and Anonymous Classes
@ -114,22 +100,4 @@ public class Cocos2dxHandler extends Handler {
this.message = message; this.message = message;
} }
} }
public static class EditBoxMessage {
public String title;
public String content;
public int inputMode;
public int inputFlag;
public int returnType;
public int maxLength;
public EditBoxMessage(String title, String content, int inputMode, int inputFlag, int returnType, int maxLength){
this.content = content;
this.title = title;
this.inputMode = inputMode;
this.inputFlag = inputFlag;
this.returnType = returnType;
this.maxLength = maxLength;
}
}
} }

View File

@ -24,34 +24,31 @@ THE SOFTWARE.
****************************************************************************/ ****************************************************************************/
package org.cocos2dx.lib; package org.cocos2dx.lib;
import java.io.UnsupportedEncodingException;
import java.util.Locale;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
import java.lang.Runnable;
import com.chukong.cocosplay.client.CocosPlayClient;
import android.app.Activity; import android.app.Activity;
import android.content.ComponentName; //Enhance API modification import android.content.ComponentName;
import android.content.Context; import android.content.Context;
import android.content.Intent; import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences; import android.content.SharedPreferences;
import android.content.pm.ApplicationInfo; import android.content.pm.ApplicationInfo;
import android.content.res.AssetManager; import android.content.res.AssetManager;
import android.net.Uri; import android.net.Uri;
import android.os.Build; import android.os.Build;
import android.os.IBinder; //Enhance API modification import android.os.IBinder;
import android.os.Vibrator; import android.os.Vibrator;
import android.preference.PreferenceManager.OnActivityResultListener; import android.preference.PreferenceManager.OnActivityResultListener;
import android.util.DisplayMetrics; import android.util.DisplayMetrics;
import android.util.Log; //Enhance API modification
import android.view.Display; import android.view.Display;
import android.view.WindowManager; import android.view.WindowManager;
import android.content.ServiceConnection; //Enhance API modification
import com.enhance.gameservice.IGameTuningService; //Enhance API modification import com.chukong.cocosplay.client.CocosPlayClient;
import com.enhance.gameservice.IGameTuningService;
import java.io.UnsupportedEncodingException;
import java.util.LinkedHashSet;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
public class Cocos2dxHelper { public class Cocos2dxHelper {
// =========================================================== // ===========================================================
@ -176,7 +173,6 @@ public class Cocos2dxHelper {
public static String getCocos2dxPackageName() { public static String getCocos2dxPackageName() {
return Cocos2dxHelper.sPackageName; return Cocos2dxHelper.sPackageName;
} }
public static String getCocos2dxWritablePath() { public static String getCocos2dxWritablePath() {
return Cocos2dxHelper.sFileDirectory; return Cocos2dxHelper.sFileDirectory;
} }
@ -345,9 +341,6 @@ public class Cocos2dxHelper {
Cocos2dxHelper.sCocos2dxHelperListener.showDialog(pTitle, pMessage); Cocos2dxHelper.sCocos2dxHelperListener.showDialog(pTitle, pMessage);
} }
private static void showEditTextDialog(final String pTitle, final String pMessage, final int pInputMode, final int pInputFlag, final int pReturnType, final int pMaxLength) {
Cocos2dxHelper.sCocos2dxHelperListener.showEditTextDialog(pTitle, pMessage, pInputMode, pInputFlag, pReturnType, pMaxLength);
}
public static void setEditTextDialogResult(final String pResult) { public static void setEditTextDialogResult(final String pResult) {
try { try {
@ -550,7 +543,6 @@ public class Cocos2dxHelper {
public static interface Cocos2dxHelperListener { public static interface Cocos2dxHelperListener {
public void showDialog(final String pTitle, final String pMessage); public void showDialog(final String pTitle, final String pMessage);
public void showEditTextDialog(final String pTitle, final String pMessage, final int pInputMode, final int pInputFlag, final int pReturnType, final int pMaxLength);
public void runOnGLThread(final Runnable pRunnable); public void runOnGLThread(final Runnable pRunnable);
} }

View File

@ -23,44 +23,35 @@ THE SOFTWARE.
****************************************************************************/ ****************************************************************************/
package org.cocos2dx.lib; package org.cocos2dx.lib;
import android.util.Log;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.io.IOException; import java.io.IOException;
import java.io.OutputStream;
import java.util.zip.GZIPInputStream;
import java.util.zip.InflaterInputStream;
import java.io.BufferedInputStream;
import java.io.InputStream; import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection; import java.net.HttpURLConnection;
import javax.net.ssl.HttpsURLConnection;
import java.net.ProtocolException; import java.net.ProtocolException;
import java.net.URL; import java.net.URL;
import java.security.KeyStore;
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.text.ParseException; import java.text.ParseException;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
import java.util.Calendar; import java.util.Calendar;
import java.util.Iterator;
import java.util.List; import java.util.List;
import java.util.Locale; import java.util.Locale;
import java.util.Map; import java.util.Map;
import java.util.Map.Entry; import java.util.Map.Entry;
import java.util.zip.GZIPInputStream;
import java.util.zip.InflaterInputStream;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext; import javax.net.ssl.SSLContext;
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.security.KeyStore;
import javax.net.ssl.TrustManagerFactory; import javax.net.ssl.TrustManagerFactory;
import org.cocos2dx.lib.Cocos2dxHelper;
import android.content.res.AssetManager;
import android.util.Log;
public class Cocos2dxHttpURLConnection public class Cocos2dxHttpURLConnection
{ {
private static final String POST_METHOD = "POST" ; private static final String POST_METHOD = "POST" ;

View File

@ -25,15 +25,15 @@ THE SOFTWARE.
package org.cocos2dx.lib; package org.cocos2dx.lib;
import java.io.FileInputStream;
import com.chukong.cocosplay.client.CocosPlayClient;
import android.content.Context; import android.content.Context;
import android.content.res.AssetFileDescriptor; import android.content.res.AssetFileDescriptor;
import android.media.MediaPlayer; import android.media.MediaPlayer;
import android.util.Log; import android.util.Log;
import com.chukong.cocosplay.client.CocosPlayClient;
import java.io.FileInputStream;
public class Cocos2dxMusic { public class Cocos2dxMusic {
// =========================================================== // ===========================================================
// Constants // Constants

View File

@ -23,12 +23,10 @@ THE SOFTWARE.
****************************************************************************/ ****************************************************************************/
package org.cocos2dx.lib; package org.cocos2dx.lib;
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;
import android.opengl.GLSurfaceView; import android.opengl.GLSurfaceView;
import org.cocos2dx.lib.Cocos2dxHelper; import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;
public class Cocos2dxRenderer implements GLSurfaceView.Renderer { public class Cocos2dxRenderer implements GLSurfaceView.Renderer {
// =========================================================== // ===========================================================
// Constants // Constants

View File

@ -24,12 +24,6 @@ THE SOFTWARE.
****************************************************************************/ ****************************************************************************/
package org.cocos2dx.lib; package org.cocos2dx.lib;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;
import android.content.Context; import android.content.Context;
import android.media.AudioManager; import android.media.AudioManager;
import android.media.SoundPool; import android.media.SoundPool;
@ -37,6 +31,13 @@ import android.util.Log;
import com.chukong.cocosplay.client.CocosPlayClient; import com.chukong.cocosplay.client.CocosPlayClient;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;
public class Cocos2dxSound { public class Cocos2dxSound {
// =========================================================== // ===========================================================
// Constants // Constants

View File

@ -24,11 +24,11 @@ THE SOFTWARE.
****************************************************************************/ ****************************************************************************/
package org.cocos2dx.lib; package org.cocos2dx.lib;
import java.util.HashMap;
import android.content.Context; import android.content.Context;
import android.graphics.Typeface; import android.graphics.Typeface;
import java.util.HashMap;
public class Cocos2dxTypefaces { public class Cocos2dxTypefaces {
// =========================================================== // ===========================================================
// Constants // Constants

View File

@ -24,10 +24,6 @@ THE SOFTWARE.
package org.cocos2dx.lib; package org.cocos2dx.lib;
import java.lang.ref.WeakReference;
import org.cocos2dx.lib.Cocos2dxVideoView.OnVideoEventListener;
import android.graphics.Rect; import android.graphics.Rect;
import android.os.Handler; import android.os.Handler;
import android.os.Message; import android.os.Message;
@ -35,6 +31,10 @@ import android.util.SparseArray;
import android.view.View; import android.view.View;
import android.widget.FrameLayout; import android.widget.FrameLayout;
import org.cocos2dx.lib.Cocos2dxVideoView.OnVideoEventListener;
import java.lang.ref.WeakReference;
public class Cocos2dxVideoHelper { public class Cocos2dxVideoHelper {
private FrameLayout mLayout = null; private FrameLayout mLayout = null;

View File

@ -34,11 +34,11 @@ import android.view.SurfaceView;
import android.widget.FrameLayout; import android.widget.FrameLayout;
import android.widget.MediaController.MediaPlayerControl; import android.widget.MediaController.MediaPlayerControl;
import com.chukong.cocosplay.client.CocosPlayClient;
import java.io.IOException; import java.io.IOException;
import java.util.Map; import java.util.Map;
import com.chukong.cocosplay.client.CocosPlayClient;
public class Cocos2dxVideoView extends SurfaceView implements MediaPlayerControl { public class Cocos2dxVideoView extends SurfaceView implements MediaPlayerControl {
private String TAG = "Cocos2dxVideoView"; private String TAG = "Cocos2dxVideoView";

View File

@ -1,8 +1,5 @@
package org.cocos2dx.lib; package org.cocos2dx.lib;
import java.lang.reflect.Method;
import java.net.URI;
import android.annotation.SuppressLint; import android.annotation.SuppressLint;
import android.content.Context; import android.content.Context;
import android.util.Log; import android.util.Log;
@ -12,6 +9,9 @@ import android.webkit.WebView;
import android.webkit.WebViewClient; import android.webkit.WebViewClient;
import android.widget.FrameLayout; import android.widget.FrameLayout;
import java.lang.reflect.Method;
import java.net.URI;
public class Cocos2dxWebView extends WebView { public class Cocos2dxWebView extends WebView {
private static final String TAG = Cocos2dxWebViewHelper.class.getSimpleName(); private static final String TAG = Cocos2dxWebViewHelper.class.getSimpleName();

View File

@ -6,12 +6,12 @@ import android.util.SparseArray;
import android.view.View; import android.view.View;
import android.widget.FrameLayout; import android.widget.FrameLayout;
import com.chukong.cocosplay.client.CocosPlayClient;
import java.util.concurrent.Callable; import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask; import java.util.concurrent.FutureTask;
import com.chukong.cocosplay.client.CocosPlayClient;
public class Cocos2dxWebViewHelper { public class Cocos2dxWebViewHelper {
private static final String TAG = Cocos2dxWebViewHelper.class.getSimpleName(); private static final String TAG = Cocos2dxWebViewHelper.class.getSimpleName();

View File

@ -38,6 +38,7 @@ THE SOFTWARE.
#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG,LOG_TAG,__VA_ARGS__) #define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG,LOG_TAG,__VA_ARGS__)
#define CLASS_NAME "org/cocos2dx/lib/Cocos2dxHelper" #define CLASS_NAME "org/cocos2dx/lib/Cocos2dxHelper"
#define EDITBOX_CLASS_NAME "org/cocos2dx/lib/Cocos2dxEditBoxHelper"
static EditTextCallback s_editTextCallback = nullptr; static EditTextCallback s_editTextCallback = nullptr;
static void* s_ctx = nullptr; static void* s_ctx = nullptr;
@ -76,6 +77,7 @@ extern "C" {
if (s_editTextCallback) s_editTextCallback("", s_ctx); if (s_editTextCallback) s_editTextCallback("", s_ctx);
} }
} }
} }
const char * getApkPath() { const char * getApkPath() {
@ -106,35 +108,6 @@ void showDialogJNI(const char * message, const char * title) {
} }
} }
void showEditTextDialogJNI(const char* title, const char* message, int inputMode, int inputFlag, int returnType, int maxLength, EditTextCallback callback, void* ctx) {
if (message == nullptr) {
return;
}
s_editTextCallback = callback;
s_ctx = ctx;
JniMethodInfo t;
if (JniHelper::getStaticMethodInfo(t, CLASS_NAME, "showEditTextDialog", "(Ljava/lang/String;Ljava/lang/String;IIII)V")) {
jstring stringArg1;
if (!title) {
stringArg1 = t.env->NewStringUTF("");
} else {
stringArg1 = cocos2d::StringUtils::newStringUTFJNI(t.env, title);
}
jstring stringArg2 = cocos2d::StringUtils::newStringUTFJNI(t.env, message);
t.env->CallStaticVoidMethod(t.classID, t.methodID, stringArg1, stringArg2,inputMode, inputFlag, returnType, maxLength);
t.env->DeleteLocalRef(stringArg1);
t.env->DeleteLocalRef(stringArg2);
t.env->DeleteLocalRef(t.classID);
}
}
void terminateProcessJNI() { void terminateProcessJNI() {
JniMethodInfo t; JniMethodInfo t;
@ -417,6 +390,168 @@ void deleteValueForKeyJNI(const char* key)
} }
} }
int addEditBoxJNI(int left, int top, int width, int height){
JniMethodInfo t;
int ret = -1;
if (JniHelper::getStaticMethodInfo(t, EDITBOX_CLASS_NAME, "createEditBox", "(IIII)I")) {
ret = t.env->CallStaticIntMethod(t.classID, t.methodID, left, top, width, height);
t.env->DeleteLocalRef(t.classID);
}
return ret;
}
void removeEditBoxJNI(int index)
{
JniMethodInfo t;
if (JniHelper::getStaticMethodInfo(t, EDITBOX_CLASS_NAME, "removeEditBox", "(I)V")) {
t.env->CallStaticVoidMethod(t.classID, t.methodID, index);
t.env->DeleteLocalRef(t.classID);
}
}
void setEditBoxViewRectJNI(int index, int left, int top, int width, int height)
{
JniMethodInfo t;
if (JniHelper::getStaticMethodInfo(t, EDITBOX_CLASS_NAME, "setEditBoxViewRect", "(IIIII)V")) {
t.env->CallStaticVoidMethod(t.classID, t.methodID, index, left, top, width, height);
t.env->DeleteLocalRef(t.classID);
}
}
void setMaxLengthJNI(int index, int maxLength)
{
JniMethodInfo t;
if (JniHelper::getStaticMethodInfo(t, EDITBOX_CLASS_NAME, "setMaxLength", "(II)V")) {
t.env->CallStaticVoidMethod(t.classID, t.methodID, index, maxLength);
t.env->DeleteLocalRef(t.classID);
}
}
void openEditBoxKeyboardJNI(int index)
{
JniMethodInfo t;
if (JniHelper::getStaticMethodInfo(t, EDITBOX_CLASS_NAME, "openKeyboard", "(I)V")) {
t.env->CallStaticVoidMethod(t.classID, t.methodID, index);
t.env->DeleteLocalRef(t.classID);
}
}
void closeEditBoxKeyboardJNI(int index)
{
JniMethodInfo t;
if (JniHelper::getStaticMethodInfo(t, EDITBOX_CLASS_NAME, "closeKeyboard", "(I)V")) {
t.env->CallStaticVoidMethod(t.classID, t.methodID, index);
t.env->DeleteLocalRef(t.classID);
}
}
void setVisibleEditBoxJNI(int index, bool visibility)
{
JniMethodInfo t;
if (JniHelper::getStaticMethodInfo(t, EDITBOX_CLASS_NAME, "setVisible", "(IZ)V")) {
t.env->CallStaticVoidMethod(t.classID, t.methodID, index, visibility);
t.env->DeleteLocalRef(t.classID);
}
}
void setReturnTypeEditBoxJNI(int index, int returnType)
{
JniMethodInfo t;
if (JniHelper::getStaticMethodInfo(t, EDITBOX_CLASS_NAME, "setReturnType", "(II)V")) {
t.env->CallStaticVoidMethod(t.classID, t.methodID, index, returnType);
t.env->DeleteLocalRef(t.classID);
}
}
void setInputFlagEditBoxJNI(int index, int returnType)
{
JniMethodInfo t;
if (JniHelper::getStaticMethodInfo(t, EDITBOX_CLASS_NAME, "setInputFlag", "(II)V")) {
t.env->CallStaticVoidMethod(t.classID, t.methodID, index, returnType);
t.env->DeleteLocalRef(t.classID);
}
}
void setInputModeEditBoxJNI(int index, int inputMode)
{
JniMethodInfo t;
if (JniHelper::getStaticMethodInfo(t, EDITBOX_CLASS_NAME, "setInputMode", "(II)V")) {
t.env->CallStaticVoidMethod(t.classID, t.methodID, index, inputMode);
t.env->DeleteLocalRef(t.classID);
}
}
void setTextEditBoxJNI(int index, const char* text)
{
JniMethodInfo t;
if (JniHelper::getStaticMethodInfo(t, EDITBOX_CLASS_NAME, "setText", "(ILjava/lang/String;)V")) {
jstring stringText = StringUtils::newStringUTFJNI(t.env,text);
t.env->CallStaticVoidMethod(t.classID, t.methodID,index, stringText);
t.env->DeleteLocalRef(stringText);
t.env->DeleteLocalRef(t.classID);
}
}
void setFontEditBoxJNI(int index, const char* fontName, float fontSize)
{
JniMethodInfo t;
if (JniHelper::getStaticMethodInfo(t, EDITBOX_CLASS_NAME, "setFont", "(ILjava/lang/String;F)V")) {
jstring stringText = StringUtils::newStringUTFJNI(t.env,fontName);
t.env->CallStaticVoidMethod(t.classID, t.methodID,index, stringText, fontSize);
t.env->DeleteLocalRef(t.classID);
t.env->DeleteLocalRef(stringText);
}
}
void setFontColorEditBoxJNI(int index, int red, int green, int blue, int alpha)
{
JniMethodInfo t;
if (JniHelper::getStaticMethodInfo(t, EDITBOX_CLASS_NAME, "setFontColor", "(IIIII)V")) {
t.env->CallStaticVoidMethod(t.classID, t.methodID,index, red, green, blue, alpha);
t.env->DeleteLocalRef(t.classID);
}
}
void setPlaceHolderTextEditBoxJNI(int index, const char* text)
{
JniMethodInfo t;
if (JniHelper::getStaticMethodInfo(t, EDITBOX_CLASS_NAME, "setPlaceHolderText", "(ILjava/lang/String;)V")) {
jstring stringText = StringUtils::newStringUTFJNI(t.env,text);
t.env->CallStaticVoidMethod(t.classID, t.methodID,index, stringText);
t.env->DeleteLocalRef(t.classID);
t.env->DeleteLocalRef(stringText);
}
}
void setPlaceHolderTextColorEditBoxJNI(int index, int red, int green, int blue, int alpha)
{
JniMethodInfo t;
if (JniHelper::getStaticMethodInfo(t, EDITBOX_CLASS_NAME, "setPlaceHolderTextColor", "(IIIII)V")) {
t.env->CallStaticVoidMethod(t.classID, t.methodID,index, red, green, blue, alpha);
t.env->DeleteLocalRef(t.classID);
}
}
void conversionEncodingJNI(const char* src, int byteSize, const char* fromCharset, char* dst, const char* newCharset) void conversionEncodingJNI(const char* src, int byteSize, const char* fromCharset, char* dst, const char* newCharset)
{ {
JniMethodInfo methodInfo; JniMethodInfo methodInfo;

View File

@ -31,7 +31,6 @@ typedef void (*EditTextCallback)(const char* text, void* ctx);
extern const char * getApkPath(); extern const char * getApkPath();
extern void showDialogJNI(const char * message, const char * title); extern void showDialogJNI(const char * message, const char * title);
extern void showEditTextDialogJNI(const char* title, const char* content, int inputMode, int inputFlag, int returnType, int maxLength, EditTextCallback callback, void* ctx);
extern void terminateProcessJNI(); extern void terminateProcessJNI();
extern std::string getCurrentLanguageJNI(); extern std::string getCurrentLanguageJNI();
extern std::string getPackageNameJNI(); extern std::string getPackageNameJNI();
@ -54,7 +53,22 @@ extern void setFloatForKeyJNI(const char* key, float value);
extern void setDoubleForKeyJNI(const char* key, double value); extern void setDoubleForKeyJNI(const char* key, double value);
extern void setStringForKeyJNI(const char* key, const char* value); extern void setStringForKeyJNI(const char* key, const char* value);
extern void deleteValueForKeyJNI(const char* key); extern void deleteValueForKeyJNI(const char* key);
extern void conversionEncodingJNI(const char* src, int byteSize, const char* fromCharset, char* dst, const char* newCharset); extern void conversionEncodingJNI(const char* src, int byteSize, const char* fromCharset, char* dst, const char* newCharset);
//Added for new Android EditBox
extern int addEditBoxJNI(int left, int top, int width, int height);
extern void removeEditBoxJNI(int index);
extern void setEditBoxViewRectJNI(int index, int left, int top, int width, int height);
extern void setMaxLengthJNI(int index, int maxLength);
extern void openEditBoxKeyboardJNI(int index);
extern void closeEditBoxKeyboardJNI(int index);
extern void setVisibleEditBoxJNI(int index, bool visibility);
extern void setReturnTypeEditBoxJNI(int index, int returnType);
extern void setInputFlagEditBoxJNI(int index, int inputFlag);
extern void setInputModeEditBoxJNI(int index, int inputMode);
extern void setTextEditBoxJNI(int index, const char* text);
extern void setFontEditBoxJNI(int index, const char* fontName, float fontSize);
extern void setFontColorEditBoxJNI(int index, int red, int green, int blue, int alpha);
extern void setPlaceHolderTextEditBoxJNI(int index, const char* text);
extern void setPlaceHolderTextColorEditBoxJNI(int index, int red, int green, int blue, int alpha);
#endif /* __Java_org_cocos2dx_lib_Cocos2dxHelper_H__ */ #endif /* __Java_org_cocos2dx_lib_Cocos2dxHelper_H__ */

View File

@ -203,6 +203,7 @@ const char* EditBox::getText(void)
void EditBox::setFont(const char* pFontName, int fontSize) void EditBox::setFont(const char* pFontName, int fontSize)
{ {
CCASSERT(pFontName != nullptr, "fontName can't be nullptr");
_fontName = pFontName; _fontName = pFontName;
_fontSize = fontSize; _fontSize = fontSize;
if (pFontName != nullptr) if (pFontName != nullptr)
@ -216,8 +217,9 @@ void EditBox::setFont(const char* pFontName, int fontSize)
void EditBox::setFontName(const char* pFontName) void EditBox::setFontName(const char* pFontName)
{ {
CCASSERT(pFontName != nullptr, "fontName can't be nullptr");
_fontName = pFontName; _fontName = pFontName;
if (_editBoxImpl != nullptr && _fontSize != -1) if (_editBoxImpl != nullptr)
{ {
_editBoxImpl->setFont(pFontName, _fontSize); _editBoxImpl->setFont(pFontName, _fontSize);
} }
@ -226,7 +228,7 @@ void EditBox::setFontName(const char* pFontName)
void EditBox::setFontSize(int fontSize) void EditBox::setFontSize(int fontSize)
{ {
_fontSize = fontSize; _fontSize = fontSize;
if (_editBoxImpl != nullptr && _fontName.length() > 0) if (_editBoxImpl != nullptr)
{ {
_editBoxImpl->setFont(_fontName.c_str(), _fontSize); _editBoxImpl->setFont(_fontName.c_str(), _fontSize);
} }
@ -248,6 +250,7 @@ void EditBox::setFontColor(const Color4B& color)
void EditBox::setPlaceholderFont(const char* pFontName, int fontSize) void EditBox::setPlaceholderFont(const char* pFontName, int fontSize)
{ {
CCASSERT(pFontName != nullptr, "fontName can't be nullptr");
_placeholderFontName = pFontName; _placeholderFontName = pFontName;
_placeholderFontSize = fontSize; _placeholderFontSize = fontSize;
if (pFontName != nullptr) if (pFontName != nullptr)
@ -261,8 +264,9 @@ void EditBox::setPlaceholderFont(const char* pFontName, int fontSize)
void EditBox::setPlaceholderFontName(const char* pFontName) void EditBox::setPlaceholderFontName(const char* pFontName)
{ {
CCASSERT(pFontName != nullptr, "fontName can't be nullptr");
_placeholderFontName = pFontName; _placeholderFontName = pFontName;
if (_editBoxImpl != nullptr && _placeholderFontSize != -1) if (_editBoxImpl != nullptr)
{ {
_editBoxImpl->setPlaceholderFont(pFontName, _fontSize); _editBoxImpl->setPlaceholderFont(pFontName, _fontSize);
} }
@ -271,7 +275,7 @@ void EditBox::setPlaceholderFontName(const char* pFontName)
void EditBox::setPlaceholderFontSize(int fontSize) void EditBox::setPlaceholderFontSize(int fontSize)
{ {
_placeholderFontSize = fontSize; _placeholderFontSize = fontSize;
if (_editBoxImpl != nullptr && _placeholderFontName.length() > 0) if (_editBoxImpl != nullptr)
{ {
_editBoxImpl->setPlaceholderFont(_placeholderFontName.c_str(), fontSize); _editBoxImpl->setPlaceholderFont(_placeholderFontName.c_str(), fontSize);
} }
@ -400,12 +404,12 @@ std::string EditBox::getDescription() const
return "EditBox"; return "EditBox";
} }
void EditBox::visit(Renderer *renderer, const Mat4 &parentTransform, uint32_t parentFlags) void EditBox::draw(Renderer *renderer, const Mat4 &parentTransform, uint32_t parentFlags)
{ {
Widget::visit(renderer, parentTransform, parentFlags); Widget::draw(renderer, parentTransform, parentFlags);
if (_editBoxImpl != nullptr) if (_editBoxImpl != nullptr)
{ {
_editBoxImpl->visit(); _editBoxImpl->draw(renderer, parentTransform, parentFlags & FLAGS_TRANSFORM_DIRTY);
} }
} }

View File

@ -308,14 +308,14 @@ namespace ui {
const char* getText(void); const char* getText(void);
/** /**
* Set the font. * Set the font. Only system font is allowed.
* @param pFontName The font name. * @param pFontName The font name.
* @param fontSize The font size. * @param fontSize The font size.
*/ */
void setFont(const char* pFontName, int fontSize); void setFont(const char* pFontName, int fontSize);
/** /**
* Set the font name. * Set the font name. Only system font is allowed.
* @param pFontName The font name. * @param pFontName The font name.
*/ */
void setFontName(const char* pFontName); void setFontName(const char* pFontName);
@ -333,14 +333,14 @@ namespace ui {
void setFontColor(const Color4B& color); void setFontColor(const Color4B& color);
/** /**
* Set the placeholder's font. * Set the placeholder's font. Only system font is allowed.
* @param pFontName The font name. * @param pFontName The font name.
* @param fontSize The font size. * @param fontSize The font size.
*/ */
void setPlaceholderFont(const char* pFontName, int fontSize); void setPlaceholderFont(const char* pFontName, int fontSize);
/** /**
* Set the placeholder's font name. * Set the placeholder's font name. only system font is allowed.
* @param pFontName The font name. * @param pFontName The font name.
*/ */
void setPlaceholderFontName(const char* pFontName); void setPlaceholderFontName(const char* pFontName);
@ -423,7 +423,7 @@ namespace ui {
* @js NA * @js NA
* @lua NA * @lua NA
*/ */
virtual void visit(Renderer *renderer, const Mat4 &parentTransform, uint32_t parentFlags) override; virtual void draw(Renderer *renderer, const Mat4 &parentTransform, uint32_t parentFlags) override;
/** /**
* @js NA * @js NA
* @lua NA * @lua NA

View File

@ -28,18 +28,118 @@
#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) #if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)
#include "UIEditBox.h" #include "UIEditBox.h"
#include <jni.h>
#include "jni/Java_org_cocos2dx_lib_Cocos2dxBitmap.h" #include "jni/Java_org_cocos2dx_lib_Cocos2dxBitmap.h"
#include "jni/Java_org_cocos2dx_lib_Cocos2dxHelper.h" #include "jni/Java_org_cocos2dx_lib_Cocos2dxHelper.h"
#include "2d/CCLabel.h" #include "2d/CCLabel.h"
#include "base/ccUTF8.h" #include "base/ccUTF8.h"
#include "math/Vec2.h"
#include "ui/UIHelper.h"
#include "base/ccUTF8.h"
NS_CC_BEGIN NS_CC_BEGIN
namespace ui { namespace ui {
EditBoxImpl* __createSystemEditBox(EditBox* pEditBox) #define LOGD(...) __android_log_print(ANDROID_LOG_ERROR,"",__VA_ARGS__)
static void editBoxEditingDidBegin(int index);
static void editBoxEditingDidChanged(int index, const std::string& text);
static void editBoxEditingDidEnd(int index, const std::string& text);
extern "C"{
JNIEXPORT void JNICALL Java_org_cocos2dx_lib_Cocos2dxEditBoxHelper_editBoxEditingDidBegin(JNIEnv *env, jclass, jint index) {
editBoxEditingDidBegin(index);
}
JNIEXPORT void JNICALL Java_org_cocos2dx_lib_Cocos2dxEditBoxHelper_editBoxEditingChanged(JNIEnv *env, jclass, jint index, jstring text) {
std::string textString = StringUtils::getStringUTFCharsJNI(env,text);
editBoxEditingDidChanged(index, textString);
}
JNIEXPORT void JNICALL Java_org_cocos2dx_lib_Cocos2dxEditBoxHelper_editBoxEditingDidEnd(JNIEnv *env, jclass, jint index, jstring text) {
std::string textString = StringUtils::getStringUTFCharsJNI(env,text);
editBoxEditingDidEnd(index, textString);
}
}
static std::unordered_map<int, EditBoxImplAndroid*> s_allEditBoxes;
EditBoxImpl* __createSystemEditBox(EditBox* editBox)
{ {
return new EditBoxImplAndroid(pEditBox); return new EditBoxImplAndroid(editBox);
}
void EditBoxImplAndroid::editBoxEditingDidBegin()
{
// LOGD("textFieldShouldBeginEditing...");
cocos2d::ui::EditBoxDelegate *pDelegate = _editBox->getDelegate();
if (pDelegate != nullptr)
{
pDelegate->editBoxEditingDidBegin(_editBox);
}
#if CC_ENABLE_SCRIPT_BINDING
if (NULL != _editBox && 0 != _editBox->getScriptEditBoxHandler())
{
cocos2d::CommonScriptData data(_editBox->getScriptEditBoxHandler(), "began", _editBox);
cocos2d::ScriptEvent event(cocos2d::kCommonEvent, (void *)&data);
cocos2d::ScriptEngineManager::getInstance()->getScriptEngine()->sendEvent(&event);
}
#endif
}
void EditBoxImplAndroid::editBoxEditingDidEnd(const std::string& text)
{
// LOGD("textFieldShouldEndEditing...");
_text = text;
this->refreshInactiveText();
cocos2d::ui::EditBoxDelegate *pDelegate = _editBox->getDelegate();
if (pDelegate != nullptr)
{
pDelegate->editBoxEditingDidEnd(_editBox);
pDelegate->editBoxReturn(_editBox);
}
#if CC_ENABLE_SCRIPT_BINDING
if (_editBox != nullptr && 0 != _editBox->getScriptEditBoxHandler())
{
cocos2d::CommonScriptData data(_editBox->getScriptEditBoxHandler(), "ended", _editBox);
cocos2d::ScriptEvent event(cocos2d::kCommonEvent, (void *)&data);
cocos2d::ScriptEngineManager::getInstance()->getScriptEngine()->sendEvent(&event);
memset(data.eventName, 0, sizeof(data.eventName));
strncpy(data.eventName, "return", sizeof(data.eventName));
event.data = (void *)&data;
cocos2d::ScriptEngineManager::getInstance()->getScriptEngine()->sendEvent(&event);
}
#endif
if (_editBox != nullptr)
{
this->onEndEditing(text);
}
}
void EditBoxImplAndroid::editBoxEditingChanged(const std::string& text)
{
// LOGD("editBoxTextChanged...");
cocos2d::ui::EditBoxDelegate *pDelegate = _editBox->getDelegate();
_text = text;
if (pDelegate != nullptr)
{
pDelegate->editBoxTextChanged(_editBox, text);
}
#if CC_ENABLE_SCRIPT_BINDING
if (NULL != _editBox && 0 != _editBox->getScriptEditBoxHandler())
{
cocos2d::CommonScriptData data(_editBox->getScriptEditBoxHandler(), "changed", _editBox);
cocos2d::ScriptEvent event(cocos2d::kCommonEvent, (void *)&data);
cocos2d::ScriptEngineManager::getInstance()->getScriptEngine()->sendEvent(&event);
}
#endif
} }
EditBoxImplAndroid::EditBoxImplAndroid(EditBox* pEditText) EditBoxImplAndroid::EditBoxImplAndroid(EditBox* pEditText)
@ -52,13 +152,14 @@ EditBoxImplAndroid::EditBoxImplAndroid(EditBox* pEditText)
, _colText(Color3B::WHITE) , _colText(Color3B::WHITE)
, _colPlaceHolder(Color3B::GRAY) , _colPlaceHolder(Color3B::GRAY)
, _maxLength(-1) , _maxLength(-1)
, _editBoxIndex(-1)
{ {
} }
EditBoxImplAndroid::~EditBoxImplAndroid() EditBoxImplAndroid::~EditBoxImplAndroid()
{ {
s_allEditBoxes.erase(_editBoxIndex);
removeEditBoxJNI(_editBoxIndex);
} }
void EditBoxImplAndroid::doAnimationWhenKeyboardMove(float duration, float distance) void EditBoxImplAndroid::doAnimationWhenKeyboardMove(float duration, float distance)
@ -70,7 +171,10 @@ static const int CC_EDIT_BOX_PADDING = 5;
bool EditBoxImplAndroid::initWithSize(const Size& size) bool EditBoxImplAndroid::initWithSize(const Size& size)
{ {
int fontSize = getFontSizeAccordingHeightJni(size.height-12); auto rect = Rect(0,0, size.width, size.height);
_editBoxIndex = addEditBoxJNI(rect.origin.x, rect.origin.y, rect.size.width, rect.size.height);
s_allEditBoxes[_editBoxIndex] = this;
_label = Label::create(); _label = Label::create();
_label->setSystemFontSize(size.height-12); _label->setSystemFontSize(size.height-12);
// align the text vertically center // align the text vertically center
@ -94,45 +198,72 @@ bool EditBoxImplAndroid::initWithSize(const Size& size)
void EditBoxImplAndroid::setFont(const char* pFontName, int fontSize) void EditBoxImplAndroid::setFont(const char* pFontName, int fontSize)
{ {
if(_label != NULL) { if(_label != NULL)
_label->setSystemFontName(pFontName); {
_label->setSystemFontSize(fontSize); if(strlen(pFontName) > 0)
} {
_label->setSystemFontName(pFontName);
}
if(fontSize > 0)
{
_label->setSystemFontSize(fontSize);
}
}
if(_labelPlaceHolder != NULL) { if(_labelPlaceHolder != NULL)
_labelPlaceHolder->setSystemFontName(pFontName); {
_labelPlaceHolder->setSystemFontSize(fontSize); if(strlen(pFontName) > 0)
} {
_labelPlaceHolder->setSystemFontName(pFontName);
}
if(fontSize > 0)
{
_labelPlaceHolder->setSystemFontSize(fontSize);
}
}
setFontEditBoxJNI(_editBoxIndex, pFontName, fontSize);
} }
void EditBoxImplAndroid::setFontColor(const Color4B& color) void EditBoxImplAndroid::setFontColor(const Color4B& color)
{ {
_colText = color; _colText = color;
_label->setTextColor(color); _label->setTextColor(color);
setFontColorEditBoxJNI(_editBoxIndex, color.r, color.g, color.b, color.a);
} }
void EditBoxImplAndroid::setPlaceholderFont(const char* pFontName, int fontSize) void EditBoxImplAndroid::setPlaceholderFont(const char* pFontName, int fontSize)
{ {
if(_labelPlaceHolder != NULL) { if(_labelPlaceHolder != NULL)
_labelPlaceHolder->setSystemFontName(pFontName); {
_labelPlaceHolder->setSystemFontSize(fontSize); if(strlen(pFontName) > 0)
} {
_labelPlaceHolder->setSystemFontName(pFontName);
}
if(fontSize > 0)
{
_labelPlaceHolder->setSystemFontSize(fontSize);
}
}
CCLOG("Wraning! You can't change Andriod Hint fontName and fontSize");
} }
void EditBoxImplAndroid::setPlaceholderFontColor(const Color4B& color) void EditBoxImplAndroid::setPlaceholderFontColor(const Color4B& color)
{ {
_colPlaceHolder = color; _colPlaceHolder = color;
_labelPlaceHolder->setTextColor(color); _labelPlaceHolder->setTextColor(color);
setPlaceHolderTextColorEditBoxJNI(_editBoxIndex, color.r, color.g, color.b, color.a);
} }
void EditBoxImplAndroid::setInputMode(EditBox::InputMode inputMode) void EditBoxImplAndroid::setInputMode(EditBox::InputMode inputMode)
{ {
_editBoxInputMode = inputMode; _editBoxInputMode = inputMode;
setInputModeEditBoxJNI(_editBoxIndex, static_cast<int>(inputMode));
} }
void EditBoxImplAndroid::setMaxLength(int maxLength) void EditBoxImplAndroid::setMaxLength(int maxLength)
{ {
_maxLength = maxLength; _maxLength = maxLength;
setMaxLengthJNI(_editBoxIndex, _maxLength);
} }
int EditBoxImplAndroid::getMaxLength() int EditBoxImplAndroid::getMaxLength()
@ -143,11 +274,13 @@ int EditBoxImplAndroid::getMaxLength()
void EditBoxImplAndroid::setInputFlag(EditBox::InputFlag inputFlag) void EditBoxImplAndroid::setInputFlag(EditBox::InputFlag inputFlag)
{ {
_editBoxInputFlag = inputFlag; _editBoxInputFlag = inputFlag;
setInputFlagEditBoxJNI(_editBoxIndex, static_cast<int>(inputFlag));
} }
void EditBoxImplAndroid::setReturnType(EditBox::KeyboardReturnType returnType) void EditBoxImplAndroid::setReturnType(EditBox::KeyboardReturnType returnType)
{ {
_keyboardReturnType = returnType; _keyboardReturnType = returnType;
setReturnTypeEditBoxJNI(_editBoxIndex, static_cast<int>(returnType));
} }
bool EditBoxImplAndroid::isEditing() bool EditBoxImplAndroid::isEditing()
@ -155,48 +288,46 @@ bool EditBoxImplAndroid::isEditing()
return false; return false;
} }
void EditBoxImplAndroid::setInactiveText(const char* pText)
{
if(EditBox::InputFlag::PASSWORD == _editBoxInputFlag)
{
std::string passwordString;
for(int i = 0; i < strlen(pText); ++i)
passwordString.append("\u25CF");
_label->setString(passwordString.c_str());
}
else
{
_label->setString(pText);
}
// Clip the text width to fit to the text box
float fMaxWidth = _editBox->getContentSize().width - CC_EDIT_BOX_PADDING * 2;
Size labelSize = _label->getContentSize();
if(labelSize.width > fMaxWidth) {
_label->setDimensions(fMaxWidth,labelSize.height);
}
}
void EditBoxImplAndroid::refreshInactiveText()
{
setInactiveText(_text.c_str());
if(_text.size() == 0)
{
_label->setVisible(false);
_labelPlaceHolder->setVisible(true);
}
else
{
_label->setVisible(true);
_labelPlaceHolder->setVisible(false);
}
}
void EditBoxImplAndroid::setText(const char* pText) void EditBoxImplAndroid::setText(const char* pText)
{ {
if (pText != NULL) setTextEditBoxJNI(_editBoxIndex, pText);
{ _text = pText;
_text = pText; refreshInactiveText();
if (_text.length() > 0)
{
_labelPlaceHolder->setVisible(false);
std::string strToShow;
if (EditBox::InputFlag::PASSWORD == _editBoxInputFlag)
{
long length = cc_utf8_strlen(_text.c_str(), -1);
for (long i = 0; i < length; i++)
{
strToShow.append("*");
}
}
else
{
strToShow = _text;
}
_label->setString(strToShow.c_str());
// Clip the text width to fit to the text box
float fMaxWidth = _editSize.width - CC_EDIT_BOX_PADDING * 2;
auto labelSize = _label->getContentSize();
if(labelSize.width > fMaxWidth) {
_label->setDimensions(fMaxWidth,labelSize.height);
}
}
else
{
_labelPlaceHolder->setVisible(true);
_label->setString("");
}
}
} }
const char* EditBoxImplAndroid::getText(void) const char* EditBoxImplAndroid::getText(void)
@ -215,105 +346,98 @@ void EditBoxImplAndroid::setPlaceHolder(const char* pText)
} }
_labelPlaceHolder->setString(_placeHolder.c_str()); _labelPlaceHolder->setString(_placeHolder.c_str());
setPlaceHolderTextEditBoxJNI(_editBoxIndex, pText);
} }
} }
void EditBoxImplAndroid::setPosition(const Vec2& pos) void EditBoxImplAndroid::setPosition(const Vec2& pos)
{ // don't need to be implemented on android platform. { // don't need to be implemented on android platform.
} }
void EditBoxImplAndroid::setVisible(bool visible) void EditBoxImplAndroid::setVisible(bool visible)
{ // don't need to be implemented on android platform. { // don't need to be implemented on android platform.
setVisibleEditBoxJNI(_editBoxIndex, visible);
} }
void EditBoxImplAndroid::setContentSize(const Size& size) void EditBoxImplAndroid::setContentSize(const Size& size)
{ // don't need to be implemented on android platform. { // don't need to be implemented on android platform.
} }
void EditBoxImplAndroid::setAnchorPoint(const Vec2& anchorPoint) void EditBoxImplAndroid::setAnchorPoint(const Vec2& anchorPoint)
{ // don't need to be implemented on android platform. { // don't need to be implemented on android platform.
} }
void EditBoxImplAndroid::visit(void) void EditBoxImplAndroid::draw(Renderer *renderer, const Mat4 &parentTransform, uint32_t parentFlags)
{ // don't need to be implemented on android platform. { // don't need to be implemented on android platform.
if(parentFlags)
{
auto rect = ui::Helper::convertBoundingBoxToScreen(_editBox);
setEditBoxViewRectJNI(_editBoxIndex, rect.origin.x, rect.origin.y, rect.size.width, rect.size.height);
}
} }
void EditBoxImplAndroid::onEnter(void) void EditBoxImplAndroid::onEnter(void)
{ // don't need to be implemented on android platform. { // don't need to be implemented on android platform.
}
static void editBoxCallbackFunc(const char* pText, void* ctx)
{
EditBoxImplAndroid* thiz = (EditBoxImplAndroid*)ctx;
thiz->setText(pText);
if (thiz->getDelegate() != NULL)
{
thiz->getDelegate()->editBoxTextChanged(thiz->getEditBox(), thiz->getText());
thiz->getDelegate()->editBoxEditingDidEnd(thiz->getEditBox());
thiz->getDelegate()->editBoxReturn(thiz->getEditBox());
}
#if CC_ENABLE_SCRIPT_BINDING
EditBox* pEditBox = thiz->getEditBox();
if (NULL != pEditBox && 0 != pEditBox->getScriptEditBoxHandler())
{
CommonScriptData data(pEditBox->getScriptEditBoxHandler(), "changed",pEditBox);
ScriptEvent event(kCommonEvent,(void*)&data);
ScriptEngineManager::getInstance()->getScriptEngine()->sendEvent(&event);
memset(data.eventName, 0, sizeof(data.eventName));
strncpy(data.eventName, "ended", sizeof(data.eventName));
event.data = (void*)&data;
ScriptEngineManager::getInstance()->getScriptEngine()->sendEvent(&event);
memset(data.eventName, 0, sizeof(data.eventName));
strncpy(data.eventName, "return", sizeof(data.eventName));
event.data = (void*)&data;
ScriptEngineManager::getInstance()->getScriptEngine()->sendEvent(&event);
}
#endif
} }
void EditBoxImplAndroid::openKeyboard() void EditBoxImplAndroid::openKeyboard()
{ {
if (_delegate != NULL) _label->setVisible(false);
{ _labelPlaceHolder->setVisible(false);
_delegate->editBoxEditingDidBegin(_editBox);
} //it will also open up the soft keyboard
setVisibleEditBoxJNI(_editBoxIndex,true);
#if CC_ENABLE_SCRIPT_BINDING
EditBox* pEditBox = this->getEditBox();
if (NULL != pEditBox && 0 != pEditBox->getScriptEditBoxHandler())
{
CommonScriptData data(pEditBox->getScriptEditBoxHandler(), "began",pEditBox);
ScriptEvent event(cocos2d::kCommonEvent,(void*)&data);
ScriptEngineManager::getInstance()->getScriptEngine()->sendEvent(&event);
}
#endif
showEditTextDialogJNI( _placeHolder.c_str(),
_text.c_str(),
(int)_editBoxInputMode,
(int)_editBoxInputFlag,
(int)_keyboardReturnType,
_maxLength,
editBoxCallbackFunc,
(void*)this );
} }
void EditBoxImplAndroid::closeKeyboard() void EditBoxImplAndroid::closeKeyboard()
{ {
closeEditBoxKeyboardJNI(_editBoxIndex);
} }
void EditBoxImplAndroid::onEndEditing(const std::string& text)
{
setVisibleEditBoxJNI(_editBoxIndex, false);
if(text.size() == 0)
{
_label->setVisible(false);
_labelPlaceHolder->setVisible(true);
}
else
{
_label->setVisible(true);
_labelPlaceHolder->setVisible(false);
setInactiveText(text.c_str());
}
} }
void editBoxEditingDidBegin(int index)
{
auto it = s_allEditBoxes.find(index);
if (it != s_allEditBoxes.end())
{
s_allEditBoxes[index]->editBoxEditingDidBegin();
}
}
void editBoxEditingDidChanged(int index, const std::string& text)
{
auto it = s_allEditBoxes.find(index);
if (it != s_allEditBoxes.end())
{
s_allEditBoxes[index]->editBoxEditingChanged(text);
}
}
void editBoxEditingDidEnd(int index, const std::string& text)
{
auto it = s_allEditBoxes.find(index);
if (it != s_allEditBoxes.end())
{
s_allEditBoxes[index]->editBoxEditingDidEnd(text);
}
}
} //end of ui namespace
NS_CC_END NS_CC_END
#endif /* #if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) */ #endif /* #if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) */

View File

@ -53,40 +53,49 @@ public:
*/ */
virtual ~EditBoxImplAndroid(); virtual ~EditBoxImplAndroid();
virtual bool initWithSize(const Size& size); virtual bool initWithSize(const Size& size) override;
virtual void setFont(const char* pFontName, int fontSize); virtual void setFont(const char* pFontName, int fontSize) override;
virtual void setFontColor(const Color4B& color); virtual void setFontColor(const Color4B& color) override;
virtual void setPlaceholderFont(const char* pFontName, int fontSize); virtual void setPlaceholderFont(const char* pFontName, int fontSize) override;
virtual void setPlaceholderFontColor(const Color4B& color); virtual void setPlaceholderFontColor(const Color4B& color) override;
virtual void setInputMode(EditBox::InputMode inputMode); virtual void setInputMode(EditBox::InputMode inputMode) override;
virtual void setInputFlag(EditBox::InputFlag inputFlag); virtual void setInputFlag(EditBox::InputFlag inputFlag) override;
virtual void setMaxLength(int maxLength); virtual void setMaxLength(int maxLength) override;
virtual int getMaxLength(); virtual int getMaxLength() override;
virtual void setReturnType(EditBox::KeyboardReturnType returnType); virtual void setReturnType(EditBox::KeyboardReturnType returnType) override;
virtual bool isEditing(); virtual bool isEditing() override;
virtual void setText(const char* pText); virtual void setText(const char* pText) override;
virtual const char* getText(void); virtual const char* getText(void) override;
virtual void setPlaceHolder(const char* pText); virtual void setPlaceHolder(const char* pText) override;
virtual void setPosition(const Vec2& pos); virtual void setPosition(const Vec2& pos) override;
virtual void setVisible(bool visible); virtual void setVisible(bool visible) override;
virtual void setContentSize(const Size& size); virtual void setContentSize(const Size& size) override;
virtual void setAnchorPoint(const Vec2& anchorPoint); virtual void setAnchorPoint(const Vec2& anchorPoint) override;
/** /**
* @js NA * @js NA
* @lua NA * @lua NA
*/ */
virtual void visit(void); virtual void draw(Renderer *renderer, const Mat4 &parentTransform, uint32_t parentFlags) override;
/** /**
* @js NA * @js NA
* @lua NA * @lua NA
*/ */
virtual void onEnter(void); virtual void onEnter(void) override;
virtual void doAnimationWhenKeyboardMove(float duration, float distance); virtual void doAnimationWhenKeyboardMove(float duration, float distance) override;
virtual void openKeyboard(); virtual void openKeyboard() override;
virtual void closeKeyboard(); virtual void closeKeyboard() override;
void editBoxEditingDidBegin();
void editBoxEditingChanged(const std::string& text);
void editBoxEditingDidEnd(const std::string& text);
private: private:
void setInactiveText(const char* pText);
void onEndEditing(const std::string& text);
void refreshInactiveText();
Label* _label; Label* _label;
Label* _labelPlaceHolder; Label* _labelPlaceHolder;
EditBox::InputMode _editBoxInputMode; EditBox::InputMode _editBoxInputMode;
@ -101,6 +110,8 @@ private:
int _maxLength; int _maxLength;
Size _editSize; Size _editSize;
int _editBoxIndex;
}; };

View File

@ -79,7 +79,7 @@ public:
* @js NA * @js NA
* @lua NA * @lua NA
*/ */
virtual void visit(void); virtual void draw(Renderer *renderer, const Mat4 &transform, uint32_t flags)override;
/** /**
* @js NA * @js NA
* @lua NA * @lua NA
@ -95,6 +95,7 @@ private:
void setInactiveText(const char* pText); void setInactiveText(const char* pText);
void adjustTextFieldPosition(); void adjustTextFieldPosition();
void placeInactiveLabels(); void placeInactiveLabels();
UIFont* constructFont(const char* fontName, int fontSize);
Label* _label; Label* _label;
Label* _labelPlaceHolder; Label* _labelPlaceHolder;

View File

@ -406,36 +406,53 @@ void EditBoxImplIOS::setInactiveText(const char* pText)
_label->setDimensions(fMaxWidth,labelSize.height); _label->setDimensions(fMaxWidth,labelSize.height);
} }
} }
UIFont* EditBoxImplIOS::constructFont(const char *fontName, int fontSize)
{
CCASSERT(fontName != nullptr, "fontName can't be nullptr");
CCEAGLView *eaglview = static_cast<CCEAGLView *>(cocos2d::Director::getInstance()->getOpenGLView()->getEAGLView());
float retinaFactor = eaglview.contentScaleFactor;
NSString * fntName = [NSString stringWithUTF8String:fontName];
auto glview = cocos2d::Director::getInstance()->getOpenGLView();
float scaleFactor = glview->getScaleX();
if (fontSize == -1)
{
fontSize = [_systemControl.textField frame].size.height*2/3;
}
else
{
fontSize = fontSize * scaleFactor / retinaFactor;
}
UIFont *textFont = nil;
if (strlen(fontName) > 0)
{
textFont = [UIFont fontWithName:fntName size:fontSize];
}
else
{
textFont = [UIFont systemFontOfSize:fontSize];
}
return textFont;
}
void EditBoxImplIOS::setFont(const char* pFontName, int fontSize) void EditBoxImplIOS::setFont(const char* pFontName, int fontSize)
{ {
bool isValidFontName = true; UIFont* textFont = constructFont(pFontName, fontSize);
if(pFontName == NULL || strlen(pFontName) == 0) {
isValidFontName = false;
}
CCEAGLView *eaglview = static_cast<CCEAGLView *>(cocos2d::Director::getInstance()->getOpenGLView()->getEAGLView());
float retinaFactor = eaglview.contentScaleFactor;
NSString * fntName = [NSString stringWithUTF8String:pFontName];
auto glview = cocos2d::Director::getInstance()->getOpenGLView();
float scaleFactor = glview->getScaleX();
UIFont *textFont = nil;
if (isValidFontName) {
textFont = [UIFont fontWithName:fntName size:fontSize * scaleFactor / retinaFactor];
}
if (!isValidFontName || textFont == nil){
textFont = [UIFont systemFontOfSize:fontSize * scaleFactor / retinaFactor];
}
if(textFont != nil) { if(textFont != nil) {
[_systemControl.textField setFont:textFont]; [_systemControl.textField setFont:textFont];
} }
_label->setSystemFontName(pFontName); if(strlen(pFontName) > 0)
_label->setSystemFontSize(fontSize); {
_label->setSystemFontName(pFontName);
}
if(fontSize > 0)
{
_label->setSystemFontSize(fontSize);
}
} }
void EditBoxImplIOS::setFontColor(const Color4B& color) void EditBoxImplIOS::setFontColor(const Color4B& color)
@ -446,8 +463,14 @@ void EditBoxImplIOS::setFontColor(const Color4B& color)
void EditBoxImplIOS::setPlaceholderFont(const char* pFontName, int fontSize) void EditBoxImplIOS::setPlaceholderFont(const char* pFontName, int fontSize)
{ {
_labelPlaceHolder->setSystemFontName(pFontName); if( strlen(pFontName) > 0)
_labelPlaceHolder->setSystemFontSize(fontSize); {
_labelPlaceHolder->setSystemFontName(pFontName);
}
if(fontSize > 0)
{
_labelPlaceHolder->setSystemFontSize(fontSize);
}
} }
void EditBoxImplIOS::setPlaceholderFontColor(const Color4B &color) void EditBoxImplIOS::setPlaceholderFontColor(const Color4B &color)
@ -647,7 +670,7 @@ void EditBoxImplIOS::setAnchorPoint(const Vec2& anchorPoint)
setPosition(_position); setPosition(_position);
} }
void EditBoxImplIOS::visit(void) void EditBoxImplIOS::draw(Renderer *renderer, const Mat4 &transform, uint32_t flags)
{ {
} }

View File

@ -76,7 +76,7 @@ public:
* @js NA * @js NA
* @lua NA * @lua NA
*/ */
virtual void visit(void); virtual void draw(Renderer *renderer, const Mat4 &transform, uint32_t flags)override;
virtual void doAnimationWhenKeyboardMove(float duration, float distance); virtual void doAnimationWhenKeyboardMove(float duration, float distance);
virtual void openKeyboard(); virtual void openKeyboard();
virtual void closeKeyboard(); virtual void closeKeyboard();
@ -89,12 +89,13 @@ public:
private: private:
NSPoint convertDesignCoordToScreenCoord(const Vec2& designCoord, bool bInRetinaMode); NSPoint convertDesignCoordToScreenCoord(const Vec2& designCoord, bool bInRetinaMode);
void adjustTextFieldPosition(); void adjustTextFieldPosition();
Size _contentSize; NSFont* constructFont(const char* fontName, int fontSize);
Vec2 _position; Size _contentSize;
Vec2 _anchorPoint; Vec2 _position;
int _maxTextLength; Vec2 _anchorPoint;
bool _inRetinaMode; int _maxTextLength;
UIEditBoxImplMac* _sysEdit; bool _inRetinaMode;
UIEditBoxImplMac* _sysEdit;
}; };

View File

@ -352,14 +352,40 @@ bool EditBoxImplMac::initWithSize(const Size& size)
return true; return true;
} }
void EditBoxImplMac::setFont(const char* pFontName, int fontSize) NSFont* EditBoxImplMac::constructFont(const char *fontName, int fontSize)
{ {
NSString * fntName = [NSString stringWithUTF8String:pFontName]; NSString * fntName = [NSString stringWithUTF8String:fontName];
float retinaFactor = _inRetinaMode ? 2.0f : 1.0f; float retinaFactor = _inRetinaMode ? 2.0f : 1.0f;
auto glview = cocos2d::Director::getInstance()->getOpenGLView(); auto glview = cocos2d::Director::getInstance()->getOpenGLView();
float scaleFactor = glview->getScaleX(); float scaleFactor = glview->getScaleX();
NSFont *textFont = [NSFont fontWithName:fntName size:fontSize * scaleFactor / retinaFactor];
if (fontSize == -1)
{
NSRect frameRect = [_sysEdit.textField frame];
fontSize = frameRect.size.height*2/3;
}
else
{
fontSize = fontSize * scaleFactor / retinaFactor;
}
NSFont *textFont = nil;
if (strlen(fontName) == 0)
{
textFont = [NSFont systemFontOfSize:fontSize];
}
else
{
textFont = [NSFont fontWithName:fntName size:fontSize];
}
return textFont;
}
void EditBoxImplMac::setFont(const char* pFontName, int fontSize)
{
NSFont* textFont = constructFont(pFontName, fontSize);
if (textFont != nil) { if (textFont != nil) {
[_sysEdit.textField setFont:textFont]; [_sysEdit.textField setFont:textFont];
[_sysEdit.secureTextField setFont:textFont]; [_sysEdit.secureTextField setFont:textFont];
@ -368,18 +394,14 @@ void EditBoxImplMac::setFont(const char* pFontName, int fontSize)
void EditBoxImplMac::setPlaceholderFont(const char* pFontName, int fontSize) void EditBoxImplMac::setPlaceholderFont(const char* pFontName, int fontSize)
{ {
NSString *fontName = [NSString stringWithUTF8String:pFontName]; NSFont *textFont = constructFont(pFontName, fontSize);
float retinaFactor = _inRetinaMode ? 2.0f : 1.0f;
auto glview = cocos2d::Director::getInstance()->getOpenGLView();
float scaleFactor = glview->getScaleX();
NSFont *font = [NSFont fontWithName:fontName size:fontSize * scaleFactor / retinaFactor];
if (!font) { if (!textFont) {
CCLOGWARN("Font not found: %s", pFontName); CCLOGWARN("Font not found: %s", pFontName);
return; return;
} }
[_sysEdit.placeholderAttributes setObject:font forKey:NSFontAttributeName]; [_sysEdit.placeholderAttributes setObject:textFont forKey:NSFontAttributeName];
/* reload placeholder */ /* reload placeholder */
const char *placeholder = [_sysEdit.textField.cell placeholderAttributedString].string.UTF8String; const char *placeholder = [_sysEdit.textField.cell placeholderAttributedString].string.UTF8String;
@ -550,7 +572,7 @@ void EditBoxImplMac::setAnchorPoint(const Vec2& anchorPoint)
setPosition(_position); setPosition(_position);
} }
void EditBoxImplMac::visit(void) void EditBoxImplMac::draw(Renderer *renderer, const Mat4 &transform, uint32_t flags)
{ {
} }

View File

@ -530,16 +530,28 @@ bool EditBoxImplWin::initWithSize(const Size& size)
void EditBoxImplWin::setFont(const char* pFontName, int fontSize) void EditBoxImplWin::setFont(const char* pFontName, int fontSize)
{ {
if (_label != nullptr) if (_label != nullptr)
{ {
_label->setSystemFontName(pFontName); if(strlen(pFontName) > 0)
_label->setSystemFontSize(fontSize); {
} _label->setSystemFontName(pFontName);
}
if(fontSize > 0)
{
_label->setSystemFontSize(fontSize);
}
}
if (_labelPlaceHolder != nullptr) if (_labelPlaceHolder != nullptr)
{ {
_labelPlaceHolder->setSystemFontName(pFontName); if(strlen(pFontName) > 0)
_labelPlaceHolder->setSystemFontSize(fontSize); {
} _labelPlaceHolder->setSystemFontName(pFontName);
}
if(fontSize > 0)
{
_labelPlaceHolder->setSystemFontSize(fontSize);
}
}
} }
void EditBoxImplWin::setFontColor(const Color4B& color) void EditBoxImplWin::setFontColor(const Color4B& color)
@ -551,10 +563,16 @@ void EditBoxImplWin::setFontColor(const Color4B& color)
void EditBoxImplWin::setPlaceholderFont(const char* pFontName, int fontSize) void EditBoxImplWin::setPlaceholderFont(const char* pFontName, int fontSize)
{ {
if (_labelPlaceHolder != nullptr) if (_labelPlaceHolder != nullptr)
{ {
_labelPlaceHolder->setSystemFontName(pFontName); if(strlen(pFontName) > 0)
_labelPlaceHolder->setSystemFontSize(fontSize); {
} _labelPlaceHolder->setSystemFontName(pFontName);
}
if(fontSize > 0)
{
_labelPlaceHolder->setSystemFontSize(fontSize);
}
}
} }
void EditBoxImplWin::setPlaceholderFontColor(const Color4B& color) void EditBoxImplWin::setPlaceholderFontColor(const Color4B& color)
@ -676,7 +694,7 @@ void EditBoxImplWin::setAnchorPoint(const Vec2& anchorPoint)
} }
void EditBoxImplWin::visit(void) void EditBoxImplWin::draw(Renderer *renderer, const Mat4 &transform, uint32_t flags)
{ {
} }

View File

@ -74,7 +74,7 @@ public:
* @js NA * @js NA
* @lua NA * @lua NA
*/ */
virtual void visit(void); virtual void draw(Renderer *renderer, const Mat4 &transform, uint32_t flags)override;
virtual void doAnimationWhenKeyboardMove(float duration, float distance); virtual void doAnimationWhenKeyboardMove(float duration, float distance);
virtual void openKeyboard(); virtual void openKeyboard();
virtual void closeKeyboard(); virtual void closeKeyboard();

View File

@ -392,14 +392,27 @@ bool UIEditBoxImplWinrt::initWithSize( const Size& size )
void UIEditBoxImplWinrt::setFont( const char* pFontName, int fontSize ) void UIEditBoxImplWinrt::setFont( const char* pFontName, int fontSize )
{ {
if(m_pLabel != NULL) { if(m_pLabel != NULL)
m_pLabel->setSystemFontName(pFontName); {
m_pLabel->setSystemFontSize(fontSize); if(strlen(pFontName) > 0)
{
m_pLabel->setSystemFontName(pFontName);
}
if(fontSize > 0)
{
m_pLabel->setSystemFontSize(fontSize);
}
} }
if(m_pLabelPlaceHolder != NULL) { if(m_pLabelPlaceHolder != NULL) {
m_pLabelPlaceHolder->setSystemFontName(pFontName); if(strlen(pFontName) > 0)
m_pLabelPlaceHolder->setSystemFontSize(fontSize); {
m_pLabelPlaceHolder->setSystemFontName(pFontName);
}
if(fontSize > 0)
{
m_pLabelPlaceHolder->setSystemFontSize(fontSize);
}
} }
} }
@ -411,9 +424,16 @@ void UIEditBoxImplWinrt::setFontColor( const Color4B& color )
void UIEditBoxImplWinrt::setPlaceholderFont( const char* pFontName, int fontSize ) void UIEditBoxImplWinrt::setPlaceholderFont( const char* pFontName, int fontSize )
{ {
if(m_pLabelPlaceHolder != NULL) { if(m_pLabelPlaceHolder != NULL)
m_pLabelPlaceHolder->setSystemFontName(pFontName); {
m_pLabelPlaceHolder->setSystemFontSize(fontSize); if(strlen(pFontName) > 0)
{
m_pLabelPlaceHolder->setSystemFontName(pFontName);
}
if(fontSize > 0)
{
m_pLabelPlaceHolder->setSystemFontSize(fontSize);
}
} }
} }
@ -530,7 +550,7 @@ void UIEditBoxImplWinrt::setAnchorPoint( const Vec2& anchorPoint )
} }
void UIEditBoxImplWinrt::visit( void ) void UIEditBoxImplWinrt::draw(cocos2d::Renderer *renderer, cocos2d::Mat4 const &transform, uint32_t flags)
{ {
} }

View File

@ -110,7 +110,7 @@ namespace ui {
virtual void setVisible(bool visible); virtual void setVisible(bool visible);
virtual void setContentSize(const Size& size); virtual void setContentSize(const Size& size);
virtual void setAnchorPoint(const Vec2& anchorPoint); virtual void setAnchorPoint(const Vec2& anchorPoint);
virtual void visit(void); virtual void draw(cocos2d::Renderer *renderer, cocos2d::Mat4 const &transform, uint32_t flags) override;
virtual void doAnimationWhenKeyboardMove(float duration, float distance); virtual void doAnimationWhenKeyboardMove(float duration, float distance);
virtual void openKeyboard(); virtual void openKeyboard();
virtual void closeKeyboard(); virtual void closeKeyboard();

View File

@ -78,7 +78,7 @@ namespace cocos2d {
* @js NA * @js NA
* @lua NA * @lua NA
*/ */
virtual void visit(void) = 0; virtual void draw(cocos2d::Renderer *renderer, cocos2d::Mat4 const &transform, uint32_t flags) = 0;
/** /**
* @js NA * @js NA
* @lua NA * @lua NA

View File

@ -25,6 +25,7 @@ THE SOFTWARE.
#include "ui/UIHelper.h" #include "ui/UIHelper.h"
#include "ui/UIWidget.h" #include "ui/UIWidget.h"
#include "ui/UILayoutComponent.h" #include "ui/UILayoutComponent.h"
#include "base/CCDirector.h"
NS_CC_BEGIN NS_CC_BEGIN
@ -191,6 +192,26 @@ Rect Helper::restrictCapInsetRect(const cocos2d::Rect &capInsets, const Size& te
} }
return Rect(x, y, width, height); return Rect(x, y, width, height);
} }
Rect Helper::convertBoundingBoxToScreen(Node* node)
{
auto director = Director::getInstance();
auto glView = director->getOpenGLView();
auto frameSize = glView->getFrameSize();
auto winSize = director->getWinSize();
auto leftBottom = node->convertToWorldSpace(Point::ZERO);
auto contentSize = node->getContentSize();
auto rightTop = node->convertToWorldSpace(Point(contentSize.width, contentSize.height));
auto uiLeft = frameSize.width / 2 + (leftBottom.x - winSize.width / 2 ) * glView->getScaleX();
auto uiTop = frameSize.height /2 - (rightTop.y - winSize.height / 2) * glView->getScaleY();
return Rect(uiLeft,uiTop,
(rightTop.x - leftBottom.x) * glView->getScaleX(),
(rightTop.y - leftBottom.y) * glView->getScaleY());
}
} }
NS_CC_END NS_CC_END

View File

@ -111,6 +111,15 @@ public:
*@return a restricted capInset. *@return a restricted capInset.
*/ */
static Rect restrictCapInsetRect(const Rect& capInsets, const Size& textureSize); static Rect restrictCapInsetRect(const Rect& capInsets, const Size& textureSize);
/**
*@brief Convert a node's boundingBox rect into screen coordinates.
*
* @param node Any node pointer.
*
* @return A Rect in screen coordinates.
*/
static Rect convertBoundingBoxToScreen(Node* node);
}; };
} }

View File

@ -33,6 +33,7 @@
#include "base/CCDirector.h" #include "base/CCDirector.h"
#include "base/CCEventListenerKeyboard.h" #include "base/CCEventListenerKeyboard.h"
#include "platform/CCFileUtils.h" #include "platform/CCFileUtils.h"
#include "ui/UIHelper.h"
//----------------------------------------------------------------------------------------------------------- //-----------------------------------------------------------------------------------------------------------
#define CLASS_NAME "org/cocos2dx/lib/Cocos2dxVideoHelper" #define CLASS_NAME "org/cocos2dx/lib/Cocos2dxVideoHelper"
@ -212,21 +213,10 @@ void VideoPlayer::draw(Renderer* renderer, const Mat4 &transform, uint32_t flags
if (flags & FLAGS_TRANSFORM_DIRTY) if (flags & FLAGS_TRANSFORM_DIRTY)
{ {
auto directorInstance = Director::getInstance(); auto uiRect = cocos2d::ui::Helper::convertBoundingBoxToScreen(this);
auto glView = directorInstance->getOpenGLView();
auto frameSize = glView->getFrameSize();
auto winSize = directorInstance->getWinSize(); setVideoRectJNI(_videoPlayerIndex, uiRect.origin.x, uiRect.origin.y,
uiRect.size.width, uiRect.size.height);
auto leftBottom = convertToWorldSpace(Point::ZERO);
auto rightTop = convertToWorldSpace(Point(_contentSize.width,_contentSize.height));
auto uiLeft = frameSize.width / 2 + (leftBottom.x - winSize.width / 2 ) * glView->getScaleX();
auto uiTop = frameSize.height /2 - (rightTop.y - winSize.height / 2) * glView->getScaleY();
setVideoRectJNI(_videoPlayerIndex,uiLeft,uiTop,
(rightTop.x - leftBottom.x) * glView->getScaleX(),
(rightTop.y - leftBottom.y) * glView->getScaleY());
} }
#if CC_VIDEOPLAYER_DEBUG_DRAW #if CC_VIDEOPLAYER_DEBUG_DRAW

View File

@ -36,6 +36,7 @@
#include "platform/CCGLView.h" #include "platform/CCGLView.h"
#include "base/CCDirector.h" #include "base/CCDirector.h"
#include "platform/CCFileUtils.h" #include "platform/CCFileUtils.h"
#include "ui/UIHelper.h"
#define CLASS_NAME "org/cocos2dx/lib/Cocos2dxWebViewHelper" #define CLASS_NAME "org/cocos2dx/lib/Cocos2dxWebViewHelper"
@ -443,21 +444,10 @@ namespace cocos2d {
void WebViewImpl::draw(cocos2d::Renderer *renderer, cocos2d::Mat4 const &transform, uint32_t flags) { void WebViewImpl::draw(cocos2d::Renderer *renderer, cocos2d::Mat4 const &transform, uint32_t flags) {
if (flags & cocos2d::Node::FLAGS_TRANSFORM_DIRTY) { if (flags & cocos2d::Node::FLAGS_TRANSFORM_DIRTY) {
auto directorInstance = cocos2d::Director::getInstance(); auto uiRect = cocos2d::ui::Helper::convertBoundingBoxToScreen(_webView);
auto glView = directorInstance->getOpenGLView();
auto frameSize = glView->getFrameSize();
auto winSize = directorInstance->getWinSize(); setWebViewRectJNI(_viewTag, uiRect.origin.x, uiRect.origin.y,
uiRect.size.width, uiRect.size.height);
auto leftBottom = this->_webView->convertToWorldSpace(cocos2d::Point::ZERO);
auto rightTop = this->_webView->convertToWorldSpace(cocos2d::Point(this->_webView->getContentSize().width,this->_webView->getContentSize().height));
auto uiLeft = frameSize.width / 2 + (leftBottom.x - winSize.width / 2 ) * glView->getScaleX();
auto uiTop = frameSize.height /2 - (rightTop.y - winSize.height / 2) * glView->getScaleY();
setWebViewRectJNI(_viewTag,uiLeft,uiTop,
(rightTop.x - leftBottom.x) * glView->getScaleX(),
(rightTop.y - leftBottom.y) * glView->getScaleY());
} }
} }

View File

@ -60,11 +60,12 @@ bool UIEditBoxTest::init()
_editName = ui::EditBox::create(editBoxSize, ui::Scale9Sprite::create(pNormalSprite)); _editName = ui::EditBox::create(editBoxSize, ui::Scale9Sprite::create(pNormalSprite));
_editName->setPosition(Vec2(visibleOrigin.x+visibleSize.width/2, visibleOrigin.y+visibleSize.height*3/4)); _editName->setPosition(Vec2(visibleOrigin.x+visibleSize.width/2, visibleOrigin.y+visibleSize.height*3/4));
_editName->setFontName("Paint Boy"); _editName->setFontName("Paint Boy");
_editName->setFontSize(25);
_editName->setFontColor(Color3B::RED); _editName->setFontColor(Color3B::RED);
_editName->setPlaceHolder("Name:"); _editName->setPlaceHolder("Name:");
_editName->setPlaceholderFontColor(Color3B::WHITE); _editName->setPlaceholderFontColor(Color3B::WHITE);
_editName->setMaxLength(8); _editName->setMaxLength(8);
_editName->setFontSize(editBoxSize.height/2);
_editName->setText("v👐👊💝");
_editName->setReturnType(ui::EditBox::KeyboardReturnType::DONE); _editName->setReturnType(ui::EditBox::KeyboardReturnType::DONE);
_editName->setDelegate(this); _editName->setDelegate(this);
addChild(_editName); addChild(_editName);
@ -77,15 +78,18 @@ bool UIEditBoxTest::init()
_editPassword->setMaxLength(6); _editPassword->setMaxLength(6);
_editPassword->setInputFlag(ui::EditBox::InputFlag::PASSWORD); _editPassword->setInputFlag(ui::EditBox::InputFlag::PASSWORD);
_editPassword->setInputMode(ui::EditBox::InputMode::SINGLE_LINE); _editPassword->setInputMode(ui::EditBox::InputMode::SINGLE_LINE);
_editPassword->setFontSize(editBoxSize.height/2);
_editPassword->setDelegate(this); _editPassword->setDelegate(this);
addChild(_editPassword); addChild(_editPassword);
// bottom // bottom
_editEmail = ui::EditBox::create(Size(editBoxSize.width, editBoxSize.height), "extensions/yellow_edit.png"); auto bottomButtonSize = Size(editBoxSize.width, editBoxSize.height + 10);
_editEmail = ui::EditBox::create(bottomButtonSize, "extensions/yellow_edit.png");
_editEmail->setPosition(Vec2(visibleOrigin.x+visibleSize.width/2, visibleOrigin.y+visibleSize.height/4)); _editEmail->setPosition(Vec2(visibleOrigin.x+visibleSize.width/2, visibleOrigin.y+visibleSize.height/4));
_editEmail->setPlaceHolder("Email:"); _editEmail->setPlaceHolder("Email:");
_editEmail->setInputMode(ui::EditBox::InputMode::EMAIL_ADDRESS); _editEmail->setInputMode(ui::EditBox::InputMode::EMAIL_ADDRESS);
_editEmail->setDelegate(this); _editEmail->setDelegate(this);
_editEmail->setFontSize(bottomButtonSize.height/2);
addChild(_editEmail); addChild(_editEmail);
return true; return true;

View File

@ -45,7 +45,7 @@ var EditBoxTestLayer = cc.Layer.extend({
this._box1.setDelegate(this); this._box1.setDelegate(this);
this.addChild(this._box1); this.addChild(this._box1);
this._box2 = new cc.EditBox(cc.size(130, 40), new cc.Scale9Sprite("extensions/green_edit.png")); this._box2 = new cc.EditBox(cc.size(130, 50), new cc.Scale9Sprite("extensions/green_edit.png"));
this._box2.setString("EditBox Sample"); this._box2.setString("EditBox Sample");
this._box2.x = 220; this._box2.x = 220;
this._box2.y = 190; this._box2.y = 190;
@ -56,7 +56,7 @@ var EditBoxTestLayer = cc.Layer.extend({
this._box2.setDelegate(this); this._box2.setDelegate(this);
this.addChild(this._box2); this.addChild(this._box2);
this._box3 = new cc.EditBox(cc.size(65, 40), new cc.Scale9Sprite("extensions/orange_edit.png")); this._box3 = new cc.EditBox(cc.size(65, 50), new cc.Scale9Sprite("extensions/orange_edit.png"));
this._box3.setString("Image"); this._box3.setString("Image");
this._box3.x = 220; this._box3.x = 220;
this._box3.y = 250; this._box3.y = 250;
@ -64,7 +64,7 @@ var EditBoxTestLayer = cc.Layer.extend({
this._box3.setDelegate(this); this._box3.setDelegate(this);
this.addChild(this._box3); this.addChild(this._box3);
this._box4 = new cc.EditBox(cc.size(180, 40), new cc.Scale9Sprite("extensions/yellow_edit.png")); this._box4 = new cc.EditBox(cc.size(180, 50), new cc.Scale9Sprite("extensions/yellow_edit.png"));
this._box4.setPlaceholderFontColor(cc.color(255, 0, 0)); this._box4.setPlaceholderFontColor(cc.color(255, 0, 0));
this._box4.setPlaceHolder("Tooltip:"); this._box4.setPlaceHolder("Tooltip:");
this._box4.x = 40; this._box4.x = 40;
@ -125,4 +125,4 @@ var runEditBoxTest = function () {
var pLayer = new EditBoxTestLayer(); var pLayer = new EditBoxTestLayer();
pScene.addChild(pLayer); pScene.addChild(pLayer);
cc.director.runScene(pScene); cc.director.runScene(pScene);
}; };