In ChromeActivity.Java, I customized some code, but it's not working like webview's addJavascriptInterface I did:
import org.chromium.content.browser.JavascriptInterface;
#SuppressLint("JavascriptInterface")
#Override
public void createContextualSearchTab(String searchUrl) {
Tab currentTab = getActivityTab();
if (currentTab == null) return;
Class<? extends Annotation> requiredAnnotation = JavascriptInterface.class;
currentTab.getWebContents().addPossiblyUnsafeJavascriptInterface(new MyJavaScriptInterface(this), "MyJS", requiredAnnotation);
TabCreator tabCreator = getTabCreator(currentTab.isIncognito());
if (tabCreator == null) return;
tabCreator.createNewTab(
new LoadUrlParams(searchUrl, PageTransition.LINK),
TabModel.TabLaunchType.FROM_LINK, currentTab);
}
public class MyJavaScriptInterface {
ChromeActivity context;
public MyJavaScriptInterface(ChromeActivity activity) {
this.context = activity;
}
#JavascriptInterface
#SuppressWarnings("unused")
public void closeApp(){
this.context._closeApp();
}
}
Chromium for android studio source code: https://github.com/kuoruan/Chromium-Android
Since Chromium 65, addPossiblyUnsafeJavascriptInterface has been changed to addPossiblyUnsafeInterface
mTabModelSelectorTabObserver = new TabModelSelectorTabObserver(mTabModelSelector) {
#Override
public void onShown(Tab tab) {
setStatusBarColor(tab, tab.getThemeColor());
JavascriptInjector ji = JavascriptInjector.fromWebContents(tab.getWebContents());
ji.setAllowInspection(true);
ji.addPossiblyUnsafeInterface(new MyJavaScriptInterface(ChromeActivity.this), "BEEB", JavascriptInterface.class);
}
}
public class MyJavaScriptInterface {
ChromeActivity context;
public MyJavaScriptInterface(ChromeActivity activity) {
this.context = activity;
}
#JavascriptInterface
public void closeApp(){
Context context = getApplicationContext();
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, "ccccccccccccccccccccccccccccccc", duration);
toast.show();
}
}
Related
As you know, when selecting a text, it appears a popup menu.
When I click the "copy" on the menu, I can't get selected/copied text but the event is fired. (in MyMenuItemOnMenuItemClickListener class > OnMenuItemClick method)
--
If I copy it using "Share > Copy to Clipboard" menu, I can get it. The event isn't fired. (This is not our goal. Just for comparison.)
And if I copy any text except the WebView and then click the copy button (not 'copy to clipboard') I could get last copied text. What's wrong with Webview's copy button? Why I couldn't get selected text?
There is no problem with iOS.
--
Xaml;
CustomWebView Class;
public class CustomWebView : WebView
{
public static readonly BindableProperty UriProperty = BindableProperty.Create(
propertyName: "Uri",
returnType: typeof(string),
declaringType: typeof(CustomWebView),
defaultValue: default(string));
public string Uri
{
get { return (string)GetValue(UriProperty); }
set { SetValue(UriProperty, value); }
}
}
Custom Renderer;
[assembly: ExportRenderer(typeof(CustomWebView), typeof(WebViewRendererDroid))]
namespace TApp.Droid
{
public class WebViewRendererDroid : ViewRenderer<CustomWebView, Android.Webkit.WebView>, IOnPrimaryClipChangedListener /* ViewRenderer<CustomWebView, Android.Webkit.WebView>*/
{
Context _context;
public WebViewRendererDroid(Context context) : base(context)
{
_context = context;
}
protected override void OnElementChanged(ElementChangedEventArgs<CustomWebView> e)
{
base.OnElementChanged(e);
if (Control == null)
{
var webView = new Android.Webkit.WebView(_context);
webView.Settings.JavaScriptEnabled = true;
webView.Settings.AllowContentAccess = true;
webView.LoadUrl("https://learn.microsoft.com/en-us/xamarin/ios/");
SetNativeControl(webView);
}
if (e.NewElement != null)
{
Control.LoadUrl("https://learn.microsoft.com/en-us/xamarin/ios/");
}
}
ClipboardManager myClipBoard;
public void OnPrimaryClipChanged()
{
ClipData clipData = myClipBoard.PrimaryClip;
ClipData.Item item = clipData.GetItemAt(0);
MessagingCenter.Send<object, string>(this, "Hi", item.Text);
}
}
}
MainActivity.cs;
namespace TApp.Droid
{
[Activity(Label = "TApp", Icon = "#mipmap/icon", Theme = "#style/MainTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
{
protected override void OnCreate(Bundle savedInstanceState)
{
TabLayoutResource = Resource.Layout.Tabbar;
ToolbarResource = Resource.Layout.Toolbar;
base.OnCreate(savedInstanceState);
global::Xamarin.Forms.Forms.Init(this, savedInstanceState);
LoadApplication(new App());
}
public override void OnActionModeStarted(ActionMode mode)
{
IMenu menu = mode.Menu;
menu.GetItem(0).SetOnMenuItemClickListener(new MyMenuItemOnMenuItemClickListener(this));
base.OnActionModeStarted(mode);
}
}
public class MyMenuItemOnMenuItemClickListener : Java.Lang.Object, IMenuItemOnMenuItemClickListener
{
private MainActivity mContext;
public MyMenuItemOnMenuItemClickListener(MainActivity activity)
{
this.mContext = activity;
}
public bool OnMenuItemClick(IMenuItem item)
{
var clipboard = (ClipboardManager)mContext.GetSystemService(Context.ClipboardService);
var clipboard2 = (Android.Text.ClipboardManager)Android.App.Application.Context.GetSystemService(Context.ClipboardService);
var pasteData = "";
string aaa = clipboard.Text;
if (!(clipboard.HasPrimaryClip))
{
// If it does contain data, decide if you can handle the data.
}
else if (!(clipboard.PrimaryClipDescription.HasMimeType(ClipDescription.MimetypeTextPlain)))
{
// since the clipboard has data but it is not plain text
}
else
{
//since the clipboard contains plain text
var copiedText = clipboard.PrimaryClip.GetItemAt(0);
// Gets the clipboard as text
pasteData = copiedText.Text;
}
Toast.MakeText(mContext, pasteData, ToastLength.Short).Show();
return true;
}
}
}
i write a simple sample,you could check it :
1.define an Interface ActionSelectListener in your Android.Project:
public interface ActionSelectListener
{
void onClick(string selectText);
}
2.custom a WebView CustomActionWebViewin your Android.Project:
class CustomActionWebView:WebView,IMenuItemOnMenuItemClickListener
{
public CustomActionWebView(Context context):base(context)
{
_context = context;
}
public CustomActionWebView(Context context, IAttributeSet attrs):base(context,attrs)
{
_context = context;
}
public CustomActionWebView(Context context, IAttributeSet attrs, int defStyleAttr):base(context,attrs,defStyleAttr)
{
_context = context;
}
private Context _context;
ActionMode mActionMode;
static ActionSelectListener mActionSelectListener;
private ActionMode resolveActionMode(ActionMode actionMode)
{
if (actionMode != null)
{
IMenu menu = actionMode.Menu;
mActionMode = actionMode;
IMenuItem menuItem = menu.GetItem(0);//here only handle the copy button
menuItem.SetOnMenuItemClickListener(this);
}
mActionMode = actionMode;
return actionMode;
}
public override ActionMode StartActionMode(ActionMode.ICallback callback)
{
ActionMode actionMode = base.StartActionMode(callback);
return resolveActionMode(actionMode);
}
public override ActionMode StartActionMode(ActionMode.ICallback callback, [GeneratedEnum] ActionModeType type)
{
ActionMode actionMode = base.StartActionMode(callback, type);
return resolveActionMode(actionMode);
}
private void releaseAction()
{
if (mActionMode != null)
{
mActionMode.Finish();
mActionMode = null;
}
}
/**
* When you click, get the selected text from the page and drop it back to the native js interface
* #param passes in the text of the clicked item, which is returned to the native interface via js
*/
private void getSelectedData()
{
String js = "(function getSelectedText() {" +
"var txt;" +
"if (window.getSelection) {" +
"txt = window.getSelection().toString();" +
"} else if (window.document.getSelection) {" +
"txt = window.document.getSelection().toString();" +
"} else if (window.document.selection) {" +
"txt = window.document.selection.createRange().text;" +
"}" +
"JSInterface.callback(txt);" +
"})()";
if (Build.VERSION.SdkInt >= Build.VERSION_CODES.Kitkat)
{
EvaluateJavascript( js, null);
}
else
{
LoadUrl("javascript:" + js);
}
}
public void linkJSInterface()
{
AddJavascriptInterface(new ActionSelectInterface(_context), "JSInterface");
}
/**
* click call back
* #param actionSelectListener
*/
public void setActionSelectListener(ActionSelectListener actionSelectListener)
{
mActionSelectListener = actionSelectListener;
}
public bool OnMenuItemClick(IMenuItem item)
{
getSelectedData();
releaseAction();
return true;
}
/**
* js call back interface
*/
class ActionSelectInterface : Java.Lang.Object
{
Context mContext;
public ActionSelectInterface(Context c)
{
mContext = c;
}
[JavascriptInterface]
[Export]
public void callback(string value)
{
if (mActionSelectListener != null)
{
mActionSelectListener.onClick(value);
}
}
}
}
3.use in your CustomRenderer :
[assembly: ExportRenderer(typeof(CustomWebView), typeof(WebViewRendererDroid))]
namespace TApp.Droid
{
public class WebViewRendererDroid : ViewRenderer<CustomWebView, Android.Webkit.WebView>, ActionSelectListenerr /* ViewRenderer<CustomWebView, Android.Webkit.WebView>*/
{
Context _context;
public WebViewRendererDroid(Context context) : base(context)
{
_context = context;
}
protected override void OnElementChanged(ElementChangedEventArgs<CustomWebView> e)
{
base.OnElementChanged(e);
if (Control == null)
{
var webView = new CustomActionWebView(_context);
webView.Settings.JavaScriptEnabled = true;
webView.Settings.AllowContentAccess = true;
webView.linkJSInterface();
webView.LoadUrl("https://learn.microsoft.com/en-us/xamarin/ios/");
SetNativeControl(webView);
}
}
public void onClick(string selectText)
{
ClipboardManager cm = (ClipboardManager)_context.GetSystemService(Context.ClipboardService);
// Place the text in the system clipboard.
ClipData clipData = ClipData.NewPlainText(null, selectText);
// Set (copy) the dataset to the clipboard
cm.PrimaryClip = clipData;
}
}
please check this code completely and suggest me some ideas
i had executed this in android studio 3.0.1 and showing me no error but doesnt shows any ouput
HomeWatcher mHomeWatcher = new HomeWatcher(this);
mHomeWatcher.setOnHomePressedListener(new OnHomePressedListener() {
#Override
public void onHomePressed() {
// do something here...
}
#Override
public void onHomeLongPressed() {
}
});
mHomeWatcher.startWatch();
check this
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.util.Log;
public class HomeWatcher {
static final String TAG = "hg";
private Context mContext;
private IntentFilter mFilter;
private OnHomePressedListener mListener;
private InnerRecevier mRecevier;
public HomeWatcher(Context context) {
mContext = context;
mFilter = new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
}
public void setOnHomePressedListener(OnHomePressedListener listener) {
mListener = listener;
mRecevier = new InnerRecevier();
}
public void startWatch() {
if (mRecevier != null) {
mContext.registerReceiver(mRecevier, mFilter);
}
}
public void stopWatch() {
if (mRecevier != null) {
mContext.unregisterReceiver(mRecevier);
}
}
class InnerRecevier extends BroadcastReceiver {
final String SYSTEM_DIALOG_REASON_KEY = "reason";
final String SYSTEM_DIALOG_REASON_GLOBAL_ACTIONS = "globalactions";
final String SYSTEM_DIALOG_REASON_RECENT_APPS = "recentapps";
final String SYSTEM_DIALOG_REASON_HOME_KEY = "homekey";
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)) {
String reason = intent.getStringExtra(SYSTEM_DIALOG_REASON_KEY);
if (reason != null) {
Log.e(TAG, "action:" + action + ",reason:" + reason);
if (mListener != null) {
if (reason.equals(SYSTEM_DIALOG_REASON_HOME_KEY)) {
mListener.onHomePressed();
} else if (reason.equals(SYSTEM_DIALOG_REASON_RECENT_APPS)) {
mListener.onHomeLongPressed();
}
}
}
}
}
}
}
check this
public interface OnHomePressedListener {
public void onHomePressed();
public void onHomeLongPressed();
}
this code was not working for me i tried of toasting a msg when home button is pressed in onHomePressed() method but msg not display plz help me to get through it
You arenĀ“t supposed to see when users press the "Home" key, mostly for security reasons and consistent behaviour for the user.
(Except for special cases like Launchers)
Most methods of doing it have been disabled already, your method probably has been disabled aswell.
I am trying to develop network app which shows a dialog when network is disconnected. I have made everything but the text inside the dialog is not centered.
package com.example.ayyappaboddupalli.networkchecker;
import android.app.Application;
import android.content.Context;
import android.content.DialogInterface;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.support.v7.app.AlertDialog;
import android.view.LayoutInflater;
import android.view.View;
/**
* Created by ayyappaboddupalli on 10/23/2017.
*/
public class ApplicationClass extends Application implements android.app.AlertDialog.OnDismissListener {
private static ApplicationClass mInstance;
private NetworkObserver networkObserver;
private NetworkDetector detector;
private AlertDialog.Builder ad = null;
private AlertDialog alertDialog;
public AlertDialog getAlertDialog() {
return alertDialog;
}
#Override
public void onCreate() {
super.onCreate();
networkObserver = new NetworkObserver();
}
public static ApplicationClass getmInstance() {
if (mInstance == null) {
synchronized (Object.class) {
mInstance = mInstance == null ? new ApplicationClass() : mInstance;
}
}
return mInstance;
}
public NetworkObserver getNetworkObserver() {
if (networkObserver == null) {
networkObserver = new NetworkObserver();
return networkObserver;
} else {
return networkObserver;
}
}
public void registerReceiver(Context context) {
detector = new NetworkDetector();
context.registerReceiver(detector, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
}
public void unRegisterReciver(Context context) {
try {
unregisterReceiver(detector);
} catch (Exception f) {
}
}
public void showDialog(Context context) {
if(alertDialog!=null)
{
alertDialog.dismiss();
}
ad = new AlertDialog.Builder(context);
LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(LAYOUT_INFLATER_SERVICE);
View view = layoutInflater.inflate(R.layout.weak_net_dialog, null);
ad.setView(view);
alertDialog = ad.create();
alertDialog.show();
alertDialog.setCancelable(false);
}
#Override
public void onDismiss(DialogInterface dialog) {
alertDialog=null;
}
}
public class NetworkDetector extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
boolean isNetOn=isnetworkOnline(context);
ApplicationClass.getmInstance().getNetworkObserver().setValue(isNetOn);
}
public boolean isnetworkOnline(Context context)
{
try {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
//should check null because in airplane mode it will be null
return (netInfo != null && netInfo.isConnected());
} catch (NullPointerException e) {
e.printStackTrace();
return false;
}
}
}
public class NetworkObserver extends Observable {
private boolean netWorkOff=false;
public boolean isNetWorkOff() {
return netWorkOff;
}
public void setValue(boolean netWorkOff) {
this.netWorkOff = netWorkOff;
setChanged();
notifyObservers();
}
}
#Override
public void update(Observable o, Object arg) {
if(ApplicationClass.getmInstance().getNetworkObserver().isNetWorkOff()) {
Toast.makeText(getApplicationContext(),"Network is online",Toast.LENGTH_LONG).show();
if(ApplicationClass.getmInstance().getAlertDialog()!=null&&ApplicationClass.getmInstance().getAlertDialog().isShowing())
ApplicationClass.getmInstance().getAlertDialog().dismiss();
}
else
{
ApplicationClass.getmInstance().showDialog(this);
// Toast.makeText(getApplicationContext(),"Network is offline",Toast.LENGTH_LONG).show();
}
}
Try this:
android:layout_gravity="center"
use following lines in ur xml file:
android:center_vertical = true
android:center_horizontal=true
It will work if you are using relativeLayout
also set width to match_parent of your dialogue and editText
I am implementing an android fingerprint authentication. I want to know which user, who has registered in device before, is authenticating. Is there any information about the user, who has registered and is valid for the device, in the FingerprintManager.AuthenticationResult argument in onAuthenticationSucceeded method?!
I am using this sample.
this is my class, which is implementing FingerprintManager.AuthenticationCallback:
public class FingerprintUiHelper extends FingerprintManager.AuthenticationCallback {
private static final long ERROR_TIMEOUT_MILLIS = 1600;
private static final long SUCCESS_DELAY_MILLIS = 1300;
private final FingerprintManager mFingerprintManager;
private final ImageView mIcon;
private final TextView mErrorTextView;
private final Callback mCallback;
private CancellationSignal mCancellationSignal;
private boolean mSelfCancelled;
/**
* Constructor for {#link FingerprintUiHelper}.
*/
FingerprintUiHelper(FingerprintManager fingerprintManager,
ImageView icon, TextView errorTextView, Callback callback) {
mFingerprintManager = fingerprintManager;
mIcon = icon;
mErrorTextView = errorTextView;
mCallback = callback;
}
public boolean isFingerprintAuthAvailable() {
// The line below prevents the false positive inspection from Android Studio
// noinspection ResourceType
return mFingerprintManager.isHardwareDetected()
&& mFingerprintManager.hasEnrolledFingerprints();
}
public void startListening(FingerprintManager.CryptoObject cryptoObject) {
if (!isFingerprintAuthAvailable()) {
return;
}
mCancellationSignal = new CancellationSignal();
mSelfCancelled = false;
// The line below prevents the false positive inspection from Android Studio
// noinspection ResourceType
mFingerprintManager
.authenticate(cryptoObject, mCancellationSignal, 0 /* flags */, this, null);
mIcon.setImageResource(R.drawable.ic_fp_40px);
}
public void stopListening() {
if (mCancellationSignal != null) {
mSelfCancelled = true;
mCancellationSignal.cancel();
mCancellationSignal = null;
}
}
#Override
public void onAuthenticationError(int errMsgId, CharSequence errString) {
if (!mSelfCancelled) {
showError(errString);
mIcon.postDelayed(new Runnable() {
#Override
public void run() {
mCallback.onError();
}
}, ERROR_TIMEOUT_MILLIS);
}
}
#Override
public void onAuthenticationHelp(int helpMsgId, CharSequence helpString) {
showError(helpString);
}
#Override
public void onAuthenticationFailed() {
showError(mIcon.getResources().getString(
R.string.fingerprint_not_recognized));
}
#Override
public void onAuthenticationSucceeded(FingerprintManager.AuthenticationResult result) {
mErrorTextView.removeCallbacks(mResetErrorTextRunnable);
mIcon.setImageResource(R.drawable.ic_fingerprint_success);
mErrorTextView.setTextColor(
mErrorTextView.getResources().getColor(R.color.success_color, null));
mErrorTextView.setText(
mErrorTextView.getResources().getString(R.string.fingerprint_success));
mIcon.postDelayed(new Runnable() {
#Override
public void run() {
mCallback.onAuthenticated();
}
}, SUCCESS_DELAY_MILLIS);
}
private void showError(CharSequence error) {
mIcon.setImageResource(R.drawable.ic_fingerprint_error);
mErrorTextView.setText(error);
mErrorTextView.setTextColor(
mErrorTextView.getResources().getColor(R.color.warning_color, null));
mErrorTextView.removeCallbacks(mResetErrorTextRunnable);
mErrorTextView.postDelayed(mResetErrorTextRunnable, ERROR_TIMEOUT_MILLIS);
}
private Runnable mResetErrorTextRunnable = new Runnable() {
#Override
public void run() {
mErrorTextView.setTextColor(
mErrorTextView.getResources().getColor(R.color.hint_color, null));
mErrorTextView.setText(
mErrorTextView.getResources().getString(R.string.fingerprint_hint));
mIcon.setImageResource(R.drawable.ic_fp_40px);
}
};
public interface Callback {
void onAuthenticated();
void onError();
}
}
i had made an application. And i wanted to add an End User license agreement to my app. So i had created a class to do it...
firstly i used to show my EULA with the inbuilt AlertDialog of android.
it worked fine..
Then i had made my own custom AlertDialog, and then tried to show the ELUA on my custom dialog. Now it works fine... The files were like...
//my Eula.java file...
//Gets the Eula file from assests folder...
class Eula {
private static final String ASSET_EULA = "EULA";
private static final String PREFERENCE_EULA_ACCEPTED = "eula.accepted";
private static final String PREFERENCES_EULA = "eula";
static interface OnEulaAgreedTo {
void onEulaAgreedTo();
}
static boolean show(final Activity activity)
{
final SharedPreferences preferences = activity.getSharedPreferences(PREFERENCES_EULA,
Activity.MODE_PRIVATE);
if (!preferences.getBoolean(PREFERENCE_EULA_ACCEPTED, false))
{
final CustomDialog.Builder builder = new CustomDialog.Builder(activity);
builder.setTitle(R.string.app_name1);
//builder.setCancelable(true);
builder.setPositiveButton(R.string.eula_accept, new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
accept(preferences);
/*if(activity instanceof OnEulaAgreedTo)
{
((OnEulaAgreedTo) activity).onEulaAgreedTo();
}*/
dialog.dismiss();
}
});
builder.setNegativeButton(R.string.eula_refuse, new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which) {
refuse(activity);
}
});
CharSequence s = readEula(activity);
builder.setMessage(s.toString());
builder.create().show();
return false;
}
return true;
}
private static void accept(SharedPreferences preferences) {
preferences.edit().putBoolean(PREFERENCE_EULA_ACCEPTED, true).commit();
}
private static void refuse(Activity activity) {
activity.finish();
}
private static CharSequence readEula(Activity activity) {
BufferedReader in = null;
try {
in = new BufferedReader(new InputStreamReader(activity.getAssets().open(ASSET_EULA)));
String line;
StringBuilder buffer = new StringBuilder();
while ((line = in.readLine()) != null) buffer.append(line).append('\n');
return buffer;
} catch (IOException e) {
return "";
} finally {
closeStream(in);
}
}
private static void closeStream(Closeable stream) {
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
}
}
}
}
And then i have my CustomDialog file
//my CustomDialog.java file...
public class CustomDialog extends Dialog {
private static final String ASSET_EULA = "EULA";
public CustomDialog(Context context, int theme) {
super(context, theme);
}
public CustomDialog(Context context) {
super(context);
}
public static class Builder {
private Context context;
private String title;
private String message;
private String positiveButtonText;
private String negativeButtonText;
//private String cancelButtonText;
private View contentView;
private DialogInterface.OnClickListener
positiveButtonClickListener,
negativeButtonClickListener;
public Builder(Context context) {
this.context = context;
}
public Builder setMessage(String message) {
this.message = message;
return this;
}
public Builder setMessage(int message) {
this.message = (String) context.getText(message);
return this;
}
public Builder setTitle(int title) {
this.title = (String) context.getText(title);
return this;
}
public Builder setTitle(String title) {
this.title = title;
return this;
}
public Builder setContentView(View v) {
this.contentView = v;
return this;
}
public Builder setPositiveButton(int positiveButtonText,
DialogInterface.OnClickListener listener) {
this.positiveButtonText = (String) context
.getText(positiveButtonText);
this.positiveButtonClickListener = listener;
return this;
}
public Builder setPositiveButton(String positiveButtonText,
DialogInterface.OnClickListener listener) {
this.positiveButtonText = positiveButtonText;
this.positiveButtonClickListener = listener;
return this;
}
public Builder setNegativeButton(int negativeButtonText,
DialogInterface.OnClickListener listener) {
this.negativeButtonText = (String) context
.getText(negativeButtonText);
this.negativeButtonClickListener = listener;
return this;
}
public Builder setNegativeButton(String negativeButtonText,
DialogInterface.OnClickListener listener) {
this.negativeButtonText = negativeButtonText;
this.negativeButtonClickListener = listener;
return this;
}
public CustomDialog create() {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// instantiate the dialog with the custom Theme
final CustomDialog dialog = new CustomDialog(context,
R.style.Dialog);
View layout = inflater.inflate(R.layout.dialog, null);
dialog.addContentView(layout, new LayoutParams(
LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
// set the dialog title
((TextView) layout.findViewById(R.id.title)).setText(title);
// set the confirm button
if (positiveButtonText != null)
{
((Button) layout.findViewById(R.id.positiveButton)).setText(positiveButtonText);
if (positiveButtonClickListener != null)
{
((Button) layout.findViewById(R.id.positiveButton)).setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
positiveButtonClickListener.onClick(dialog, DialogInterface.BUTTON_POSITIVE);
}
});
}
} else {
// if no confirm button just set the visibility to GONE
layout.findViewById(R.id.positiveButton).setVisibility(
View.GONE);
}
// set the cancel button
if (negativeButtonText != null) {
((Button) layout.findViewById(R.id.negativeButton))
.setText(negativeButtonText);
if (negativeButtonClickListener != null) {
((Button) layout.findViewById(R.id.negativeButton))
.setOnClickListener(new View.OnClickListener() {
public void onClick(View v)
{
negativeButtonClickListener.onClick(dialog, DialogInterface.BUTTON_NEGATIVE);
}
});
}
} else {
// if no confirm button just set the visibility to GONE
layout.findViewById(R.id.negativeButton).setVisibility(
View.GONE);
}
// set the content message
if (message != null) {
((TextView) layout.findViewById(
R.id.message)).setText(message);
} else if (contentView != null) {
// if no message set
// add the contentView to the dialog body
((LinearLayout) layout.findViewById(R.id.content))
.removeAllViews();
((LinearLayout) layout.findViewById(R.id.content))
.addView(contentView,
new LayoutParams(
LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT));
}
dialog.setContentView(layout);
return dialog;
}
public void dismiss()
{
this.dismiss();
}
public void setCancelable(boolean b) {
// TODO Auto-generated method stub
this.setCancelable(true);
}
}
}
Atfirst, the onClickfor setPositive button for eula.java file was like
public void onClick(DialogInterface dialog, int which)
{
accept(preferences);
if(activity instanceof OnEulaAgreedTo)
{
((OnEulaAgreedTo) activity).onEulaAgreedTo();
}
}
it worked fine for the inbuilt AlertDialog. but when i changed it with my custom dialog, that codition is resulting false always...
Can anyone tell me what that code is meant for?
For dialog disappearing you should use Dialog.dismiss(). You can dismiss dialog just at the end of positive button behavior.
When you click on refuse button you finish activity, and that's why you dialog dismisses.
The issue may be in the following condition. please check the activity instance whether it agrres the condition?
if(activity instanceof OnEulaAgreedTo)
{
((OnEulaAgreedTo) activity).onEulaAgreedTo();
}