com.afollestad.materialdialogs.MaterialDialog

Here are the examples of the java api com.afollestad.materialdialogs.MaterialDialog taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

395 Examples 7

19 Source : BaseMaterialDialog.java
with Apache License 2.0
from vsona

public clreplaced BaseMaterialDialog {

    private MaterialDialog dialog;

    protected void dismiss() {
        if (dialog != null) {
            dialog.dismiss();
            dialog = null;
        }
    }

    public MaterialDialog getDialog() {
        return this.dialog;
    }

    protected void showWithBuilder(MaterialDialog.Builder builder) {
        dismiss();
        if (builder == null)
            return;
        this.dialog = builder.build();
        this.dialog.show();
    }

    protected void showLoading(Context context) {
        dismiss();
        if (context == null)
            return;
        MaterialDialog.Builder builder = newSimpleProgressLoadingBuilder(context);
        this.dialog = builder.build();
        this.dialog.show();
    }

    protected static MaterialDialog.Builder newBuilder(Context context) {
        return new MaterialDialog.Builder(context);
    }

    protected static MaterialDialog.Builder newSimpleProgressLoadingBuilder(Context context, CharSequence cs) {
        CharSequence message = "加载中...";
        if (!TextUtils.isEmpty(cs)) {
            message = cs;
        }
        return newBuilder(context).replacedle(message).progress(true, 0);
    }

    protected static MaterialDialog.Builder newSimpleProgressLoadingBuilder(Context context, @StringRes int StrRes) {
        String message = context.getString(StrRes);
        return newSimpleProgressLoadingBuilder(context, message);
    }

    protected static MaterialDialog.Builder newSimpleProgressLoadingBuilder(Context context) {
        return newSimpleProgressLoadingBuilder(context, null);
    }

    protected static MaterialDialog.Builder newSimplereplacedleContentBuilder(Context context, CharSequence replacedle, CharSequence content) {
        return newBuilder(context).replacedle(replacedle).content(content);
    }

    protected static MaterialDialog.Builder newSimplereplacedleContentPositiveBuilder(Context context, CharSequence replacedle, CharSequence content) {
        return newSimplereplacedleContentBuilder(context, replacedle, content).positiveText("确定");
    }
}

19 Source : DialogAsyncTask.java
with GNU General Public License v3.0
from tianma8023

public abstract clreplaced DialogAsyncTask<Param, Progress, Result> extends AsyncTask<Param, Progress, Result> implements DialogInterface.OnCancelListener {

    private boolean mCancelable;

    private MaterialDialog mProgressDialog;

    public DialogAsyncTask(Context context, String progressMsg, boolean cancelable) {
        mProgressDialog = new MaterialDialog.Builder(context).content(progressMsg).progress(true, 100).cancelable(mCancelable).build();
        mCancelable = cancelable;
    }

    @Override
    protected void onPreExecute() {
        if (mCancelable) {
            mProgressDialog.setOnCancelListener(this);
        }
        mProgressDialog.show();
    }

    @Override
    public void onCancel(DialogInterface dialog) {
        cancel(true);
    }

    @Override
    protected void onPostExecute(Result result) {
        mProgressDialog.dismiss();
    }

    @Override
    protected void onCancelled() {
        mProgressDialog.dismiss();
    }
}

19 Source : BaseActivity.java
with Apache License 2.0
from shensky711

/**
 * @author HansChen
 */
public clreplaced BaseActivity extends AppCompatActivity {

    private MaterialDialog mWaitingDialog;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    protected void showWaitingDialog(String replacedle, String message) {
        dismissDialog();
        mWaitingDialog = new MaterialDialog.Builder(this).replacedle(replacedle).cancelable(false).canceledOnTouchOutside(false).progress(true, 0).progressIndeterminateStyle(true).content(message).build();
        mWaitingDialog.show();
    }

    protected void dismissDialog() {
        if (mWaitingDialog != null && mWaitingDialog.isShowing()) {
            mWaitingDialog.dismiss();
            mWaitingDialog = null;
        }
    }
}

19 Source : ShareAdapter.java
with GNU General Public License v3.0
from PowerExplorer

void updateMatDialog(MaterialDialog b) {
    this.dialog = b;
}

19 Source : HiddenAdapter.java
with GNU General Public License v3.0
from PowerExplorer

public void updateDialog(final MaterialDialog dialog) {
    materialDialog = dialog;
}

19 Source : ProgressDialog.java
with Mozilla Public License 2.0
from newPersonKing

/**
 * Created by Stardust on 2017/7/31.
 */
public clreplaced ProgressDialog {

    private MaterialDialog mDialog;

    public ProgressDialog(Context context) {
        this(context, R.string.text_on_progress);
    }

    public ProgressDialog(Context context, int resId) {
        mDialog = new MaterialDialog.Builder(context).progress(true, 0).cancelable(false).content(resId).show();
    }

    public void dismiss() {
        mDialog.dismiss();
    }
}

19 Source : BlacklistPreferenceDialog.java
with GNU General Public License v3.0
from MaxFour

private void refreshBlacklistData() {
    paths = BlacklistStore.getInstance(getContext()).getPaths();
    MaterialDialog dialog = (MaterialDialog) getDialog();
    if (dialog != null) {
        String[] pathArray = new String[paths.size()];
        pathArray = paths.toArray(pathArray);
        dialog.sereplacedems((CharSequence[]) pathArray);
    }
}

19 Source : AndroidProfileNavigator.java
with Apache License 2.0
from marcovann

/**
 * Created by marco on 09/09/16.
 */
public clreplaced AndroidProfileNavigator implements ProfileNavigator {

    private static final int SELECT_PHOTO = 1;

    private final AppCompatActivity activity;

    private final MaterialDialog.Builder progressDialogBuilder;

    private MaterialDialog progressDialog;

    private ProfileDialogListener dialogListener;

    public AndroidProfileNavigator(AppCompatActivity activity) {
        this.activity = activity;
        this.progressDialogBuilder = new MaterialDialog.Builder(activity).replacedle(R.string.profile_dialog_upload_replacedle).content(R.string.profile_dialog_upload_message).progress(true, 0);
    }

    @Override
    public void showInputTextDialog(String hint, final TextView textView, final User user) {
        final MaterialDialog dialog = new MaterialDialog.Builder(activity).replacedle(R.string.profile_dialog_name_replacedle).inputType(InputType.TYPE_CLreplaced_TEXT).input(activity.getString(R.string.profile_hint_name), textView.getText().toString(), new MaterialDialog.InputCallback() {

            @Override
            public void onInput(MaterialDialog dialog, CharSequence input) {
            // Do something
            }
        }).negativeText(R.string.profile_dialog_input_close).onPositive(new MaterialDialog.SingleButtonCallback() {

            @Override
            public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                String inputText = dialog.getInputEditText().getText().toString();
                if (inputText.length() == 0) {
                    Toast.makeText(activity, "Name cannot be empty", Toast.LENGTH_SHORT).show();
                    return;
                }
                dialogListener.onNameSelected(inputText, user);
                textView.setText(inputText);
                dialog.dismiss();
            }
        }).show();
    }

    @Override
    public void showInputPreplacedwordDialog(String hint, User user) {
        new MaterialDialog.Builder(activity).replacedle(R.string.profile_dialog_preplacedword_replacedle).inputType(InputType.TYPE_TEXT_VARIATION_PreplacedWORD).input(null, null, new MaterialDialog.InputCallback() {

            @Override
            public void onInput(MaterialDialog dialog, CharSequence input) {
            // Do something
            }
        }).negativeText(R.string.profile_dialog_input_close).onPositive(new MaterialDialog.SingleButtonCallback() {

            @Override
            public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                String preplacedword = dialog.getInputEditText().getText().toString();
                if (preplacedword.length() < 8) {
                    Toast.makeText(activity, R.string.login_snackbar_preplacedword_short, Toast.LENGTH_SHORT).show();
                    return;
                }
                dialogListener.onPreplacedwordSelected(preplacedword);
                dialog.dismiss();
            }
        }).show();
    }

    @Override
    public void showImagePicker() {
        Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
        photoPickerIntent.setType("image/*");
        activity.startActivityForResult(photoPickerIntent, SELECT_PHOTO);
    }

    @Override
    public void showRemoveDialog() {
        new MaterialDialog.Builder(activity).content(R.string.profile_dialog_remove_content).positiveText(R.string.profile_dialog_remove_positive).negativeText(R.string.profile_dialog_remove_negative).onPositive(new MaterialDialog.SingleButtonCallback() {

            @Override
            public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                dialogListener.onRemoveSelected();
                Toast.makeText(activity, R.string.profile_toast_preplacedword_positive, Toast.LENGTH_SHORT).show();
                dialog.dismiss();
                // TODO
                activity.finish();
            }
        }).show();
    }

    @Override
    public void showProgressDialog() {
        this.progressDialog = this.progressDialogBuilder.show();
    }

    @Override
    public void dismissProgressDialog() {
        this.progressDialog.dismiss();
    }

    @Override
    public void attach(ProfileDialogListener dialogListener) {
        this.dialogListener = dialogListener;
    }

    @Override
    public void detach(ProfileDialogListener dialogListener) {
        this.dialogListener = null;
    }

    @Override
    public void toLogin() {
    }

    @Override
    public void toMainActivity() {
    }

    @Override
    public void toParent() {
        activity.finish();
    }

    public boolean onActivityResult(int requestCode, int resultCode, Intent intent) {
        if (requestCode != SELECT_PHOTO) {
            return false;
        }
        if (intent == null) {
            return false;
        }
        try {
            final Uri imageUri = intent.getData();
            final InputStream imageStream = activity.getContentResolver().openInputStream(imageUri);
            final Bitmap selectedImage = BitmapFactory.decodeStream(imageStream);
            dialogListener.onImageSelected(selectedImage);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        return true;
    }
}

19 Source : CommonFragment.java
with Apache License 2.0
from lky1001

/**
 * Created by user on 2018. 5. 25..
 */
public abstract clreplaced CommonFragment extends DaggerFragment {

    protected MaterialDialog mMaterialDialog;

    protected abstract void refresh();

    @Override
    public void onHiddenChanged(boolean hidden) {
        if (!hidden) {
            refresh();
        }
    }

    @Override
    public void onDestroy() {
        hideDialog();
        super.onDestroy();
    }

    public void showProgressDialog(@Nullable String replacedle, @NonNull String msg) {
        hideDialog();
        MaterialDialog.Builder builder = new MaterialDialog.Builder(getActivity());
        if (!TextUtils.isEmpty(replacedle)) {
            builder.replacedle(replacedle);
        }
        mMaterialDialog = builder.replacedleColorRes(R.color.colorAccent).contentColorRes(R.color.colorAccent).backgroundColorRes(android.R.color.white).content(msg).progress(true, 0).canceledOnTouchOutside(false).show();
    }

    protected void hideDialog() {
        if (mMaterialDialog != null) {
            mMaterialDialog.dismiss();
            mMaterialDialog = null;
        }
    }
}

19 Source : FixDataTask.java
with GNU General Public License v3.0
from ihewro

/**
 * <pre>
 *     author : hewro
 *     e-mail : [email protected]
 *     time   : 2019/07/03
 *     desc   : 修复数据库功能
 *     功能:删除错误数据(收藏关系表中id为<=0的数据)、导入以前的feeditem里面的收藏数据、删除多余的collection内容(在关系表中不存在该collection)
 *     version: 1.0
 * </pre>
 */
public clreplaced FixDataTask extends AsyncTask<Void, Void, Boolean> {

    @SuppressLint("StaticFieldLeak")
    private Activity activity;

    private MaterialDialog loading;

    public FixDataTask() {
    }

    public FixDataTask(Activity activity) {
        this.activity = activity;
    }

    @Override
    protected void onPreExecute() {
        loading = new MaterialDialog.Builder(activity).content("马上就好……").progress(true, 0).show();
    }

    @Override
    protected Boolean doInBackground(Void... voids) {
        CollectionFolder collectionFolder = new CollectionFolder("旧版本数据迁移");
        try {
            collectionFolder.saveThrows();
        } catch (LitePalSupportException e) {
            ALog.d(e);
            collectionFolder.setId(LitePal.where("name = ?", collectionFolder.getName()).find(CollectionFolder.clreplaced).get(0).getId());
        }
        // 所有收藏的文章
        List<FeedItem> feedItems = LitePal.where("favorite = ?", "1").find(FeedItem.clreplaced);
        for (FeedItem feedItem : feedItems) {
            Collection collection = new Collection(feedItem.getreplacedle(), feedItem.getFeedName(), feedItem.getDate(), feedItem.getSummary(), feedItem.getContent(), feedItem.getUrl(), Collection.FEED_ITEM, DateUtil.getNowDateRFCInt());
            try {
                collection.saveThrows();
            } catch (LitePalSupportException e) {
                ALog.d(e);
                collection.setId(LitePal.where("url = ?", collection.getUrl()).find(Collection.clreplaced).get(0).getId());
            }
            // 查询数据库是否有这样的关系,如果有就不需要存储的了
            List<CollectionAndFolderRelation> temp = LitePal.where("collectionid = ? and collectionfolderid = ?", collection.getId() + "", collectionFolder.getId() + "").find(CollectionAndFolderRelation.clreplaced);
            // 保存新的关系
            if (temp.size() == 0) {
                CollectionAndFolderRelation collectionAndFolderRelation = new CollectionAndFolderRelation(collection.getId(), collectionFolder.getId());
                collectionAndFolderRelation.save();
            }
        }
        // 删除错误数据
        LitePal.deleteAll(CollectionAndFolderRelation.clreplaced, "collectionid = ? or collectionfolderid = ?", "0", "0");
        return true;
    }

    @Override
    protected void onPostExecute(Boolean aBoolean) {
        // 显示成功
        if (loading.isShowing()) {
            loading.dismiss();
            Toasty.success(activity, "修复成功").show();
            EventBus.getDefault().post(new EventMessage(EventMessage.DATABASE_RECOVER));
        }
    }
}

19 Source : InboxFragment.java
with Apache License 2.0
from hbmartin

void showAutocompleteDialog() {
    MaterialDialog dialog = new MaterialDialog.Builder(getActivity()).replacedle(R.string.new_conversation).customView(R.layout.autocomplete_dialog, false).show();
    setupAutocomplete(dialog);
}

19 Source : BaseFragment.java
with Apache License 2.0
from goldze

/**
 * Created by goldze on 2017/6/15.
 */
public abstract clreplaced BaseFragment<V extends ViewDataBinding, VM extends BaseViewModel> extends RxFragment implements IBaseView {

    protected V binding;

    protected VM viewModel;

    private int viewModelId;

    private MaterialDialog dialog;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initParam();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        binding = DataBindingUtil.inflate(inflater, initContentView(inflater, container, savedInstanceState), container, false);
        return binding.getRoot();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        // 解除Messenger注册
        Messenger.getDefault().unregister(viewModel);
        if (viewModel != null) {
            viewModel.removeRxBus();
        }
        if (binding != null) {
            binding.unbind();
        }
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        // 私有的初始化Databinding和ViewModel方法
        initViewDataBinding();
        // 私有的ViewModel与View的契约事件回调逻辑
        registorUIChangeLiveDataCallBack();
        // 页面数据初始化方法
        initData();
        // 页面事件监听的方法,一般用于ViewModel层转到View层的事件注册
        initViewObservable();
        // 注册RxBus
        viewModel.registerRxBus();
    }

    /**
     * 注入绑定
     */
    private void initViewDataBinding() {
        viewModelId = initVariableId();
        viewModel = initViewModel();
        if (viewModel == null) {
            Clreplaced modelClreplaced;
            Type type = getClreplaced().getGenericSuperclreplaced();
            if (type instanceof ParameterizedType) {
                modelClreplaced = (Clreplaced) ((ParameterizedType) type).getActualTypeArguments()[1];
            } else {
                // 如果没有指定泛型参数,则默认使用BaseViewModel
                modelClreplaced = BaseViewModel.clreplaced;
            }
            viewModel = (VM) createViewModel(this, modelClreplaced);
        }
        binding.setVariable(viewModelId, viewModel);
        // 支持LiveData绑定xml,数据改变,UI自动会更新
        binding.setLifecycleOwner(this);
        // 让ViewModel拥有View的生命周期感应
        getLifecycle().addObserver(viewModel);
        // 注入RxLifecycle生命周期
        viewModel.injectLifecycleProvider(this);
    }

    /**
     * =====================================================================
     */
    // 注册ViewModel与View的契约UI回调事件
    protected void registorUIChangeLiveDataCallBack() {
        // 加载对话框显示
        viewModel.getUC().getShowDialogEvent().observe(this, new Observer<String>() {

            @Override
            public void onChanged(@Nullable String replacedle) {
                showDialog(replacedle);
            }
        });
        // 加载对话框消失
        viewModel.getUC().getDismissDialogEvent().observe(this, new Observer<Void>() {

            @Override
            public void onChanged(@Nullable Void v) {
                dismissDialog();
            }
        });
        // 跳入新页面
        viewModel.getUC().getStartActivityEvent().observe(this, new Observer<Map<String, Object>>() {

            @Override
            public void onChanged(@Nullable Map<String, Object> params) {
                Clreplaced<?> clz = (Clreplaced<?>) params.get(ParameterField.CLreplaced);
                Bundle bundle = (Bundle) params.get(ParameterField.BUNDLE);
                startActivity(clz, bundle);
            }
        });
        // 跳入ContainerActivity
        viewModel.getUC().getStartContainerActivityEvent().observe(this, new Observer<Map<String, Object>>() {

            @Override
            public void onChanged(@Nullable Map<String, Object> params) {
                String canonicalName = (String) params.get(ParameterField.CANONICAL_NAME);
                Bundle bundle = (Bundle) params.get(ParameterField.BUNDLE);
                startContainerActivity(canonicalName, bundle);
            }
        });
        // 关闭界面
        viewModel.getUC().getFinishEvent().observe(this, new Observer<Void>() {

            @Override
            public void onChanged(@Nullable Void v) {
                getActivity().finish();
            }
        });
        // 关闭上一层
        viewModel.getUC().getOnBackPressedEvent().observe(this, new Observer<Void>() {

            @Override
            public void onChanged(@Nullable Void v) {
                getActivity().onBackPressed();
            }
        });
    }

    public void showDialog(String replacedle) {
        if (dialog != null) {
            dialog = dialog.getBuilder().replacedle(replacedle).build();
            dialog.show();
        } else {
            MaterialDialog.Builder builder = MaterialDialogUtils.showIndeterminateProgressDialog(getActivity(), replacedle, true);
            dialog = builder.show();
        }
    }

    public void dismissDialog() {
        if (dialog != null && dialog.isShowing()) {
            dialog.dismiss();
        }
    }

    /**
     * 跳转页面
     *
     * @param clz 所跳转的目的Activity类
     */
    public void startActivity(Clreplaced<?> clz) {
        startActivity(new Intent(getContext(), clz));
    }

    /**
     * 跳转页面
     *
     * @param clz    所跳转的目的Activity类
     * @param bundle 跳转所携带的信息
     */
    public void startActivity(Clreplaced<?> clz, Bundle bundle) {
        Intent intent = new Intent(getContext(), clz);
        if (bundle != null) {
            intent.putExtras(bundle);
        }
        startActivity(intent);
    }

    /**
     * 跳转容器页面
     *
     * @param canonicalName 规范名 : Fragment.clreplaced.getCanonicalName()
     */
    public void startContainerActivity(String canonicalName) {
        startContainerActivity(canonicalName, null);
    }

    /**
     * 跳转容器页面
     *
     * @param canonicalName 规范名 : Fragment.clreplaced.getCanonicalName()
     * @param bundle        跳转所携带的信息
     */
    public void startContainerActivity(String canonicalName, Bundle bundle) {
        Intent intent = new Intent(getContext(), ContainerActivity.clreplaced);
        intent.putExtra(ContainerActivity.FRAGMENT, canonicalName);
        if (bundle != null) {
            intent.putExtra(ContainerActivity.BUNDLE, bundle);
        }
        startActivity(intent);
    }

    /**
     * =====================================================================
     */
    // 刷新布局
    public void refreshLayout() {
        if (viewModel != null) {
            binding.setVariable(viewModelId, viewModel);
        }
    }

    @Override
    public void initParam() {
    }

    /**
     * 初始化根布局
     *
     * @return 布局layout的id
     */
    public abstract int initContentView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState);

    /**
     * 初始化ViewModel的id
     *
     * @return BR的id
     */
    public abstract int initVariableId();

    /**
     * 初始化ViewModel
     *
     * @return 继承BaseViewModel的ViewModel
     */
    public VM initViewModel() {
        return null;
    }

    @Override
    public void initData() {
    }

    @Override
    public void initViewObservable() {
    }

    public boolean isBackPressed() {
        return false;
    }

    /**
     * 创建ViewModel
     *
     * @param cls
     * @param <T>
     * @return
     */
    public <T extends ViewModel> T createViewModel(Fragment fragment, Clreplaced<T> cls) {
        return ViewModelProviders.of(fragment).get(cls);
    }
}

19 Source : BaseActivity.java
with Apache License 2.0
from goldze

/**
 * Created by goldze on 2017/6/15.
 * 一个拥有DataBinding框架的基Activity
 * 这里根据项目业务可以换成你自己熟悉的BaseActivity, 但是需要继承RxAppCompatActivity,方便LifecycleProvider管理生命周期
 */
public abstract clreplaced BaseActivity<V extends ViewDataBinding, VM extends BaseViewModel> extends RxAppCompatActivity implements IBaseView {

    protected V binding;

    protected VM viewModel;

    private int viewModelId;

    private MaterialDialog dialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 页面接受的参数方法
        initParam();
        // 私有的初始化Databinding和ViewModel方法
        initViewDataBinding(savedInstanceState);
        // 私有的ViewModel与View的契约事件回调逻辑
        registorUIChangeLiveDataCallBack();
        // 页面数据初始化方法
        initData();
        // 页面事件监听的方法,一般用于ViewModel层转到View层的事件注册
        initViewObservable();
        // 注册RxBus
        viewModel.registerRxBus();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 解除Messenger注册
        Messenger.getDefault().unregister(viewModel);
        if (viewModel != null) {
            viewModel.removeRxBus();
        }
        if (binding != null) {
            binding.unbind();
        }
    }

    /**
     * 注入绑定
     */
    private void initViewDataBinding(Bundle savedInstanceState) {
        // DataBindingUtil类需要在project的build中配置 dataBinding {enabled true }, 同步后会自动关联android.databinding包
        binding = DataBindingUtil.setContentView(this, initContentView(savedInstanceState));
        viewModelId = initVariableId();
        viewModel = initViewModel();
        if (viewModel == null) {
            Clreplaced modelClreplaced;
            Type type = getClreplaced().getGenericSuperclreplaced();
            if (type instanceof ParameterizedType) {
                modelClreplaced = (Clreplaced) ((ParameterizedType) type).getActualTypeArguments()[1];
            } else {
                // 如果没有指定泛型参数,则默认使用BaseViewModel
                modelClreplaced = BaseViewModel.clreplaced;
            }
            viewModel = (VM) createViewModel(this, modelClreplaced);
        }
        // 关联ViewModel
        binding.setVariable(viewModelId, viewModel);
        // 支持LiveData绑定xml,数据改变,UI自动会更新
        binding.setLifecycleOwner(this);
        // 让ViewModel拥有View的生命周期感应
        getLifecycle().addObserver(viewModel);
        // 注入RxLifecycle生命周期
        viewModel.injectLifecycleProvider(this);
    }

    // 刷新布局
    public void refreshLayout() {
        if (viewModel != null) {
            binding.setVariable(viewModelId, viewModel);
        }
    }

    /**
     * =====================================================================
     */
    // 注册ViewModel与View的契约UI回调事件
    protected void registorUIChangeLiveDataCallBack() {
        // 加载对话框显示
        viewModel.getUC().getShowDialogEvent().observe(this, new Observer<String>() {

            @Override
            public void onChanged(@Nullable String replacedle) {
                showDialog(replacedle);
            }
        });
        // 加载对话框消失
        viewModel.getUC().getDismissDialogEvent().observe(this, new Observer<Void>() {

            @Override
            public void onChanged(@Nullable Void v) {
                dismissDialog();
            }
        });
        // 跳入新页面
        viewModel.getUC().getStartActivityEvent().observe(this, new Observer<Map<String, Object>>() {

            @Override
            public void onChanged(@Nullable Map<String, Object> params) {
                Clreplaced<?> clz = (Clreplaced<?>) params.get(ParameterField.CLreplaced);
                Bundle bundle = (Bundle) params.get(ParameterField.BUNDLE);
                startActivity(clz, bundle);
            }
        });
        // 跳入ContainerActivity
        viewModel.getUC().getStartContainerActivityEvent().observe(this, new Observer<Map<String, Object>>() {

            @Override
            public void onChanged(@Nullable Map<String, Object> params) {
                String canonicalName = (String) params.get(ParameterField.CANONICAL_NAME);
                Bundle bundle = (Bundle) params.get(ParameterField.BUNDLE);
                startContainerActivity(canonicalName, bundle);
            }
        });
        // 关闭界面
        viewModel.getUC().getFinishEvent().observe(this, new Observer<Void>() {

            @Override
            public void onChanged(@Nullable Void v) {
                finish();
            }
        });
        // 关闭上一层
        viewModel.getUC().getOnBackPressedEvent().observe(this, new Observer<Void>() {

            @Override
            public void onChanged(@Nullable Void v) {
                onBackPressed();
            }
        });
    }

    public void showDialog(String replacedle) {
        if (dialog != null) {
            dialog = dialog.getBuilder().replacedle(replacedle).build();
            dialog.show();
        } else {
            MaterialDialog.Builder builder = MaterialDialogUtils.showIndeterminateProgressDialog(this, replacedle, true);
            dialog = builder.show();
        }
    }

    public void dismissDialog() {
        if (dialog != null && dialog.isShowing()) {
            dialog.dismiss();
        }
    }

    /**
     * 跳转页面
     *
     * @param clz 所跳转的目的Activity类
     */
    public void startActivity(Clreplaced<?> clz) {
        startActivity(new Intent(this, clz));
    }

    /**
     * 跳转页面
     *
     * @param clz    所跳转的目的Activity类
     * @param bundle 跳转所携带的信息
     */
    public void startActivity(Clreplaced<?> clz, Bundle bundle) {
        Intent intent = new Intent(this, clz);
        if (bundle != null) {
            intent.putExtras(bundle);
        }
        startActivity(intent);
    }

    /**
     * 跳转容器页面
     *
     * @param canonicalName 规范名 : Fragment.clreplaced.getCanonicalName()
     */
    public void startContainerActivity(String canonicalName) {
        startContainerActivity(canonicalName, null);
    }

    /**
     * 跳转容器页面
     *
     * @param canonicalName 规范名 : Fragment.clreplaced.getCanonicalName()
     * @param bundle        跳转所携带的信息
     */
    public void startContainerActivity(String canonicalName, Bundle bundle) {
        Intent intent = new Intent(this, ContainerActivity.clreplaced);
        intent.putExtra(ContainerActivity.FRAGMENT, canonicalName);
        if (bundle != null) {
            intent.putExtra(ContainerActivity.BUNDLE, bundle);
        }
        startActivity(intent);
    }

    /**
     * =====================================================================
     */
    @Override
    public void initParam() {
    }

    /**
     * 初始化根布局
     *
     * @return 布局layout的id
     */
    public abstract int initContentView(Bundle savedInstanceState);

    /**
     * 初始化ViewModel的id
     *
     * @return BR的id
     */
    public abstract int initVariableId();

    /**
     * 初始化ViewModel
     *
     * @return 继承BaseViewModel的ViewModel
     */
    public VM initViewModel() {
        return null;
    }

    @Override
    public void initData() {
    }

    @Override
    public void initViewObservable() {
    }

    /**
     * 创建ViewModel
     *
     * @param cls
     * @param <T>
     * @return
     */
    public <T extends ViewModel> T createViewModel(FragmentActivity activity, Clreplaced<T> cls) {
        return ViewModelProviders.of(activity).get(cls);
    }
}

19 Source : LoginActivity.java
with Apache License 2.0
from Freelander

/**
 * Created by Jun on 2016/10/14.
 */
public clreplaced LoginActivity extends BaseFrameActivity<LoginPresenter, LoginModel> implements ZXingScannerView.ResultHandler, LoginContract.View {

    private ZXingScannerView mScannerView;

    private MaterialDialog mLoadingDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mScannerView = new ZXingScannerView(this);
        setContentView(mScannerView);
    }

    @Override
    public void initView() {
        super.initView();
        getLoadingDialog().content("正在登录...");
        mLoadingDialog = getLoadingDialog().build();
    }

    @Override
    public void onResume() {
        super.onResume();
        mScannerView.setResultHandler(this);
        mScannerView.startCamera();
    }

    @Override
    public void onPause() {
        super.onPause();
        mScannerView.stopCamera();
    }

    @Override
    public void handleResult(Result result) {
        String mUserName = "";
        String mLoginToken = "";
        String s = result.getText();
        if (!TextUtils.isEmpty(s) && s.contains(",")) {
            String[] data = s.split(",", 2);
            if (data.length == 2) {
                mUserName = data[0];
                mLoginToken = data[1];
            }
        }
        JLog.d("Login info: ", "UserName === " + mUserName + " LoginToken ======= " + mLoginToken);
        mPresenter.login(this, mUserName, mLoginToken);
    }

    @Override
    public void onRequestStart() {
        mLoadingDialog.show();
    }

    @Override
    public void onRequestEnd() {
        mLoadingDialog.dismiss();
    }

    @Override
    public void onLoginSuccess(UserInfoEnreplacedy userInfoEnreplacedy) {
        Bundle bundle = new Bundle();
        bundle.putParcelable(Constants.Key.USER_DATA, userInfoEnreplacedy);
        Intent intent = new Intent();
        intent.putExtras(bundle);
        setResult(RESULT_OK, intent);
        finish();
    }

    @Override
    public void onInternetError() {
        super.onInternetError();
        showShortToast(getString(R.string.toast_login_fail));
        // 重置扫描
        mScannerView.resumeCameraPreview(this);
    }
}

19 Source : ScriptFileChooserDialogBuilder.java
with Mozilla Public License 2.0
from feifadaima

public MaterialDialog build() {
    if (mStorageScriptProvider != null) {
        mScriptListWithProgressBarView.setStorageScriptProvider(mStorageScriptProvider);
    }
    customView(mScriptListWithProgressBarView, false);
    final MaterialDialog dialog = super.build();
    if (mFileCallback != null) {
        mScriptListWithProgressBarView.setOnItemClickListener(new ScriptAndFolderListRecyclerView.OnScriptFileClickListener() {

            @Override
            public void onClick(ScriptFile file, int position) {
                mFileCallback.onFileSelection(dialog, file);
            }
        });
    }
    return dialog;
}

19 Source : SettingActivity.java
with Apache License 2.0
from CooLoongWu

public clreplaced SettingActivity extends BaseActivity implements View.OnClickListener {

    private MaterialDialog progressDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_setting);
        initToolbar();
        initView();
    }

    private void initToolbar() {
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        toolbar.setreplacedle("设置");
        setSupportActionBar(toolbar);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                finish();
            }
        });
    }

    private void initView() {
        TextView text_logout = (TextView) findViewById(R.id.text_logout);
        TextView text_check = (TextView) findViewById(R.id.text_check);
        text_logout.setOnClickListener(this);
        text_check.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch(view.getId()) {
            case R.id.text_logout:
                logout();
                break;
            case R.id.text_check:
                checkUpdate();
                break;
            default:
                break;
        }
    }

    private void checkUpdate() {
        Api.getUpdateInfo(SettingActivity.this, new JsonHttpResponseHandler() {

            @Override
            public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                super.onSuccess(statusCode, headers, response);
                LogUtils.e("检查更新", "成功:" + response.toString());
                try {
                    String versionName = response.getString("version");
                    String description = response.getString("description");
                    String apkUrl = response.getString("apkUrl");
                    if (!versionName.equals(AppConfig.getVersionName(SettingActivity.this))) {
                        showUpdateInfo("有更新啦", description, apkUrl);
                    } else {
                        new MaterialDialog.Builder(SettingActivity.this).replacedle("温馨提示").content("当前已是最新版本").positiveText("确定").onPositive(new MaterialDialog.SingleButtonCallback() {

                            @Override
                            public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                                dialog.dismiss();
                            }
                        }).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
                super.onFailure(statusCode, headers, throwable, errorResponse);
                ToastUtils.showShort(SettingActivity.this, "检查更新失败,稍后再试吧");
            }

            @Override
            public void onCancel() {
                super.onCancel();
                LogUtils.e("检查更新", "取消");
            }
        });
    }

    private void showUpdateInfo(String replacedle, String content, final String url) {
        new MaterialDialog.Builder(this).replacedle(replacedle).content(content).positiveText("立即更新").negativeText("稍后更新").onPositive(new MaterialDialog.SingleButtonCallback() {

            @Override
            public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                dialog.dismiss();
                downloadApk(url);
            }
        }).onNegative(new MaterialDialog.SingleButtonCallback() {

            @Override
            public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                dialog.dismiss();
            }
        }).show();
    }

    private void downloadApk(String url) {
        // 加.apk确保
        final String fileName = url.substring(url.lastIndexOf("/") + 1) + ".apk";
        File fileDir = new File(AppConfig.FILE_SAVE_PATH);
        File filePath = new File(AppConfig.FILE_SAVE_PATH, fileName);
        if (filePath.exists()) {
            Api.installApk(SettingActivity.this, fileName);
            return;
        }
        showProgressDialog();
        if (!fileDir.exists()) {
            fileDir.mkdirs();
        }
        Api.download(SettingActivity.this, url, new FileAsyncHttpResponseHandler(filePath) {

            @Override
            public void onFailure(int statusCode, Header[] headers, Throwable throwable, File file) {
            // showToast("下载失败,请稍后再试~");
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, File file) {
                progressDialog.dismiss();
                Api.installApk(SettingActivity.this, fileName);
            }

            @Override
            public void onProgress(long bytesWritten, long totalSize) {
                super.onProgress(bytesWritten, totalSize);
                int progress = (int) ((bytesWritten * 1.0 / totalSize) * 100);
                LogUtils.e("下载进度>>>>>", progress + "%");
                progressDialog.setProgress(progress);
            }
        });
    }

    private void showProgressDialog() {
        progressDialog = new MaterialDialog.Builder(SettingActivity.this).replacedle("下载中...").content("正在下载").progress(false, 100, true).progressNumberFormat("%1d/%2d").canceledOnTouchOutside(false).show();
    }

    private void logout() {
        // 清除SharedPreferences的数据
        AppConfig.clearAllInfo(SettingActivity.this);
        // 清除数据库的数据
        GreenDAOUtils.getInstance(SettingActivity.this).clearAllData();
        // 打开登录页面
        startActivity(new Intent(SettingActivity.this, LoginActivity.clreplaced));
        // 删除其他的Activity
        AppManager.getInstance().finishAllActivityExcept(LoginActivity.clreplaced);
    }
}

19 Source : PopupMethodResolver.java
with GNU General Public License v3.0
from Blockstream

public clreplaced PopupMethodResolver implements MethodResolver {

    private Activity activity;

    private MaterialDialog dialog;

    public PopupMethodResolver(final Activity activity) {
        this.activity = activity;
    }

    @Override
    public SettableFuture<String> method(List<String> methods) {
        final SettableFuture<String> future = SettableFuture.create();
        if (methods.size() == 1) {
            future.set(methods.get(0));
        } else {
            final MaterialDialog.Builder builder = UI.popup(activity, R.string.id_choose_method_to_authorize_the).cancelable(false).items(methods).itemsCallbackSingleChoice(0, (dialog, v, which, text) -> {
                Log.d("RSV", "PopupMethodResolver CHOOSE callback");
                future.set(methods.get(which));
                return true;
            }).onNegative((dialog, which) -> {
                Log.d("RSV", "PopupMethodResolver CANCEL callback");
                future.set(null);
            });
            activity.runOnUiThread(() -> {
                Log.d("RSV", "PopupMethodResolver dialog show");
                dialog = builder.show();
            });
        }
        return future;
    }

    @Override
    public void dismiss() {
        if (dialog != null) {
            activity.runOnUiThread(() -> {
                dialog.dismiss();
            });
        }
    }
}

19 Source : PopupCodeResolver.java
with GNU General Public License v3.0
from Blockstream

public clreplaced PopupCodeResolver implements CodeResolver {

    private Activity activity;

    private MaterialDialog dialog;

    public PopupCodeResolver(final Activity activity) {
        this.activity = activity;
    }

    @Override
    public SettableFuture<String> hardwareRequest(final HWDeviceRequiredData requiredData) {
        return null;
    }

    @Override
    public SettableFuture<String> code(final String method) {
        final SettableFuture<String> future = SettableFuture.create();
        final MaterialDialog.Builder builder = UI.popup(activity, activity.getString(R.string.id_please_provide_your_1s_code, method)).inputType(InputType.TYPE_CLreplaced_NUMBER).icon(getIconFor(method)).cancelable(false).input("", "", (dialog, input) -> {
            Log.d("RSV", "PopupCodeResolver OK callback");
            future.set(input.toString());
        }).onNegative((dialog, which) -> {
            Log.d("RSV", "PopupCodeResolver CANCEL callback");
            future.set(null);
        });
        activity.runOnUiThread(() -> {
            Log.d("RSV", "PopupCodeResolver dialog show");
            dialog = builder.show();
        });
        return future;
    }

    @Override
    public void dismiss() {
        if (dialog != null) {
            activity.runOnUiThread(() -> {
                dialog.dismiss();
            });
        }
    }

    private Drawable getIconFor(final String method) {
        switch(method) {
            case "email":
                return ContextCompat.getDrawable(activity, R.drawable.ic_2fa_email);
            case "sms":
                return ContextCompat.getDrawable(activity, R.drawable.ic_2fa_sms);
            case "gauth":
                return ContextCompat.getDrawable(activity, R.drawable.ic_2fa_google);
            case "phone":
                return ContextCompat.getDrawable(activity, R.drawable.ic_2fa_call);
            default:
                return null;
        }
    }
}

19 Source : TabbedMainActivity.java
with GNU General Public License v3.0
from Blockstream

// Problem with the above is that in the horizontal orientation the tabs don't go in the top bar
public clreplaced TabbedMainActivity extends LoggedActivity {

    private static final String TAG = TabbedMainActivity.clreplaced.getSimpleName();

    public static final int REQUEST_BITCOIN_URL_LOGIN = 1, REQUEST_TX_DETAILS = 2, REQUEST_BITCOIN_URL_SEND = 3, REQUEST_SELECT_replacedET = 4, REQUEST_SELECT_SUBACCOUNT = 5;

    private MaterialDialog mSubaccountDialog;

    private boolean mIsBitcoinUri = false;

    static boolean isBitcoinScheme(final Intent intent) {
        final Uri uri = intent.getData();
        return uri != null && uri.getScheme() != null && uri.getScheme().equals("bitcoin");
    }

    @Override
    protected void onCreate(final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        final Intent intent = getIntent();
        mIsBitcoinUri = isBitcoinScheme(intent) || intent.hasCategory(Intent.CATEGORY_BROWSABLE) || NfcAdapter.ACTION_NDEF_DISCOVERED.equals(intent.getAction());
        if (mIsBitcoinUri) {
            // Not logged in, force the user to login
            final Intent login = new Intent(this, RequestLoginActivity.clreplaced);
            startActivityForResult(login, REQUEST_BITCOIN_URL_LOGIN);
            return;
        }
        launch();
        final boolean isResetActive = getSession().isTwoFAReset();
        if (mIsBitcoinUri && !isResetActive) {
            // If logged in, open send activity
            onBitcoinUri();
        }
        if (savedInstanceState == null) {
            FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
            ft.add(R.id.container, new MainFragment()).commit();
        }
    }

    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu_main, menu);
        // Update notification Icon
        MenuItem notificationMenuItem = menu.findItem(R.id.action_notifications);
        notificationMenuItem.setIcon(!getSession().getNotificationModel().getEvents().isEmpty() ? R.drawable.bottom_navigation_notifications_2 : R.drawable.bottom_navigation_notifications);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch(item.gereplacedemId()) {
            case R.id.action_notifications:
                startActivity(new Intent(this, NotificationsActivity.clreplaced));
                break;
            case R.id.action_settings:
                startActivity(new Intent(this, SettingsActivity.clreplaced));
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    private void onBitcoinUri() {
        Uri uri = null;
        if (!NfcAdapter.ACTION_NDEF_DISCOVERED.equals(getIntent().getAction()))
            uri = getIntent().getData();
        else {
            final Parcelable[] rawMessages;
            rawMessages = getIntent().getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
            for (final Parcelable parcel : rawMessages) {
                final NdefMessage ndefMsg = (NdefMessage) parcel;
                for (final NdefRecord record : ndefMsg.getRecords()) if (record.getTnf() == NdefRecord.TNF_WELL_KNOWN && Arrays.equals(record.getType(), NdefRecord.RTD_URI))
                    uri = record.toUri();
            }
        }
        if (uri == null)
            return;
        final Intent intent = new Intent(this, SendAmountActivity.clreplaced);
        final String text = uri.toString();
        try {
            final int subaccount = getActiveAccount();
            final GDKTwoFactorCall call = getSession().createTransactionFromUri(null, text, subaccount);
            final ObjectNode transactionFromUri = call.resolve(null, new HardwareCodeResolver(this));
            final String error = transactionFromUri.get("error").asText();
            if ("id_invalid_address".equals(error)) {
                UI.toast(this, R.string.id_invalid_address, Toast.LENGTH_SHORT);
                return;
            }
            removeUtxosIfTooBig(transactionFromUri);
            intent.putExtra(PrefKeys.INTENT_STRING_TX, transactionFromUri.toString());
        } catch (final Exception e) {
            e.printStackTrace();
            if (e.getMessage() != null)
                UI.toast(this, e.getMessage(), Toast.LENGTH_SHORT);
            return;
        }
        intent.putExtra("internal_qr", getIntent().getBooleanExtra("internal_qr", false));
        startActivityForResult(intent, REQUEST_BITCOIN_URL_SEND);
    }

    private void launch() {
        setContentView(R.layout.activity_tabbed_main);
        final Toolbar toolbar = UI.find(this, R.id.toolbar);
        setSupportActionBar(toolbar);
        // Set network Icon
        setreplacedleWithNetwork(R.string.id_wallets);
        // Set replacedle as null as we use a custom replacedle element with an arrow and clicklistener
        setreplacedle(null);
        TextView toolbarreplacedle = UI.find(this, R.id.toolbarreplacedle);
        toolbarreplacedle.setText(getNetwork().getName());
        toolbarreplacedle.setOnClickListener(v -> {
            showDialog();
        });
    }

    private void showDialog() {
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        ft.addToBackStack(null);
        // Create and show the dialog.
        DialogFragment newFragment = SwitchNetworkFragment.newInstance();
        newFragment.show(ft, "dialog");
    }

    @Override
    public void onResume() {
        super.onResume();
        if (isFinishing())
            return;
        // check available preferred exchange rate
        try {
            final BalanceData balanceData = getSession().convertBalance(0);
            Double.parseDouble(balanceData.getFiat());
        } catch (final Exception e) {
            UI.popup(this, R.string.id_your_favourite_exchange_rate_is).show();
        }
        invalidateOptionsMenu();
    }

    @Override
    public void onPause() {
        super.onPause();
        if (isFinishing())
            return;
        mSubaccountDialog = UI.dismiss(this, mSubaccountDialog);
    }

    @Override
    protected void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch(requestCode) {
            case REQUEST_BITCOIN_URL_SEND:
                mIsBitcoinUri = false;
                break;
            case REQUEST_BITCOIN_URL_LOGIN:
                if (resultCode != RESULT_OK) {
                    // The user failed to login after clicking on a bitcoin Uri
                    finish();
                    return;
                }
                mIsBitcoinUri = true;
                break;
            case REQUEST_TX_DETAILS:
                break;
        }
    }

    @Override
    public void onBackPressed() {
        this.moveTaskToBack(true);
    }
}

19 Source : AutomationFragment.java
with Apache License 2.0
from bing-zhub

private void showThatDialog() {
    MaterialDialog dialog = new MaterialDialog.Builder(getContext()).replacedle("操作").content("在触发条件时执行的操作").items(new String[] { "通知我", "操作1", "操作2" }).itemsCallback(new MaterialDialog.ListCallback() {

        @Override
        public void onSelection(MaterialDialog dialog, View itemView, int position, CharSequence text) {
            if (position != 0) {
                CommonUtils.showMessage(getContext(), "正待开发");
                return;
            }
            automationItem.setType("info");
            automationItem.setTargetTopic("");
            tvThat.setTextColor(Color.GRAY);
            tvThat.setText("提醒我");
            ivThat.setImageResource(R.drawable.notification);
            ivConfirm.setVisibility(View.VISIBLE);
        }
    }).show();
}

19 Source : ExportingUtils.java
with Apache License 2.0
from BennyKok

/**
 * Created by BennyKok on 10/17/2016.
 */
public clreplaced ExportingUtils {

    private static ExportingUtils ourInstance = new ExportingUtils();

    public static ExportingUtils getInstance() {
        return ourInstance;
    }

    public MaterialDialog currentProgressDialog;

    private ExportingUtils() {
    }

    public void dismissAllDialogs() {
        if (currentProgressDialog != null)
            currentProgressDialog.dismiss();
    }

    public File checkAndCreateProjectDirs() {
        String path = Environment.getExternalStorageDirectory().getPath().concat("/PxerStudio/Export");
        File dirs = new File(path);
        if (!dirs.exists()) {
            dirs.mkdirs();
        }
        return dirs;
    }

    public static String getExportPath() {
        return Environment.getExternalStorageDirectory().getPath().concat("/PxerStudio/Export");
    }

    public static String getProjectPath() {
        return Environment.getExternalStorageDirectory().getPath().concat("/PxerStudio/Project");
    }

    public File checkAndCreateProjectDirs(String extraFolder) {
        if (extraFolder == null || extraFolder.isEmpty())
            return checkAndCreateProjectDirs();
        String path = Environment.getExternalStorageDirectory().getPath().concat("/PxerStudio/Export/" + extraFolder);
        File dirs = new File(path);
        if (!dirs.exists()) {
            dirs.mkdirs();
        }
        return dirs;
    }

    public void toastAndFinishExport(Context context, String fileName) {
        if (fileName != null && !fileName.isEmpty())
            MediaScannerConnection.scanFile(context, new String[] { fileName }, null, new MediaScannerConnection.OnScanCompletedListener() {

                public void onScanCompleted(String path, Uri uri) {
                }
            });
        Tool.toast(context, "Exported successfully");
    }

    public void screplacedotsOfFile(Context context, List<File> files) {
        String[] paths = new String[files.size()];
        for (int i = 0; i < files.size(); i++) {
            paths[i] = files.get(i).toString();
        }
        MediaScannerConnection.scanFile(context, paths, null, new MediaScannerConnection.OnScanCompletedListener() {

            public void onScanCompleted(String path, Uri uri) {
            }
        });
    }

    public void showProgressDialog(Context context) {
        currentProgressDialog = new MaterialDialog.Builder(context).replacedleGravity(GravityEnum.CENTER).typeface(Tool.myType, Tool.myType).cancelable(false).canceledOnTouchOutside(false).replacedle("Painting...").progress(true, 0).progressIndeterminateStyle(true).show();
    }

    public void showExportingDialog(final Context context, final PxerView pxerView, final OnExportConfirmedListenser listenser) {
        showExportingDialog(context, -1, pxerView, listenser);
    }

    public void showExportingDialog(final Context context, int maxSize, final PxerView pxerView, final OnExportConfirmedListenser listenser) {
        final ConstraintLayout l = (ConstraintLayout) LayoutInflater.from(context).inflate(R.layout.dialog_activity_drawing, null);
        final EditText editText = (EditText) l.findViewById(R.id.et1);
        final SeekBar seekBar = (SeekBar) l.findViewById(R.id.sb);
        final TextView textView = (TextView) l.findViewById(R.id.tv2);
        editText.setText(pxerView.getProjectName());
        if (maxSize == -1)
            seekBar.setMax(4096 - pxerView.getPicWidth());
        else
            seekBar.setMax(maxSize - pxerView.getPicWidth());
        textView.setText("Size : " + String.valueOf(pxerView.getPicWidth()) + " x " + String.valueOf(pxerView.getPicHeight()));
        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {

            @Override
            public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
                textView.setText("Size : " + String.valueOf(i + pxerView.getPicWidth()) + " x " + String.valueOf(i + pxerView.getPicHeight()));
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
            }
        });
        new MaterialDialog.Builder(context).replacedleGravity(GravityEnum.CENTER).typeface(Tool.myType, Tool.myType).customView(l, false).replacedle("Export").positiveText("Export").negativeText("Cancel").onPositive(new MaterialDialog.SingleButtonCallback() {

            @Override
            public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                if (editText.getText().toString().isEmpty()) {
                    Tool.toast(context, "The file name cannot be empty!");
                    return;
                }
                listenser.OnExportConfirmed(editText.getText().toString(), seekBar.getProgress() + pxerView.getPicWidth(), seekBar.getProgress() + pxerView.getPicHeight());
            }
        }).show();
    }

    public interface OnExportConfirmedListenser {

        public void OnExportConfirmed(String fileName, int width, int height);
    }
}

19 Source : CommonUtil.java
with Apache License 2.0
from axzae

public static String getDialogInput(final MaterialDialog dialog) {
    EditText editText = dialog.getInputEditText();
    if (editText != null) {
        return dialog.getInputEditText().getText().toString().trim();
    } else {
        throw new IllegalStateException("EditText not found");
    }
}

19 Source : CommonUtil.java
with Apache License 2.0
from axzae

public static void fixDialogKeyboard(final MaterialDialog dialog) {
    // https://github.com/afollestad/material-dialogs/issues/1105
    EditText inputEditText = dialog.getInputEditText();
    if (inputEditText != null) {
        inputEditText.setOnEditorActionListener(new TextView.OnEditorActionListener() {

            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if ((event != null && (event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) || (actionId == EditorInfo.IME_ACTION_DONE) || (actionId == EditorInfo.IME_ACTION_SEARCH)) {
                    View positiveButton = dialog.getActionButton(DialogAction.POSITIVE);
                    if (dialog.getActionButton(DialogAction.POSITIVE).isEnabled()) {
                        positiveButton.callOnClick();
                    } else {
                        return true;
                    }
                }
                return false;
            }
        });
    }
}

19 Source : InputTextFragment.java
with Apache License 2.0
from axzae

@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public clreplaced InputTextFragment extends BaseControlFragment implements View.OnClickListener {

    private EditText mInput;

    private MaterialDialog mDialog;

    public static InputTextFragment newInstance(Enreplacedy enreplacedy) {
        InputTextFragment fragment = new InputTextFragment();
        Bundle args = new Bundle();
        args.putString("enreplacedy", CommonUtil.deflate(enreplacedy));
        fragment.setArguments(args);
        return fragment;
    }

    @NonNull
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        mDialog = new MaterialDialog.Builder(getActivity()).replacedle(mEnreplacedy.getFriendlyName()).autoDismiss(true).cancelable(true).inputRangeRes(mEnreplacedy.attributes.min.intValue(), mEnreplacedy.attributes.max.intValue(), R.color.md_red_500).alwaysCallInputCallback().input("Value", mEnreplacedy.state, new MaterialDialog.InputCallback() {

            @Override
            public void onInput(@NonNull MaterialDialog dialog, CharSequence input) {
                final String inputString = input.toString();
                boolean isValid = true;
                if (mEnreplacedy.attributes.pattern != null) {
                    isValid = inputString.matches(mEnreplacedy.attributes.pattern);
                // Log.d("YouQi", "Pattern: " + mEnreplacedy.attributes.pattern + ", isValid? " + (isValid ? "true" : "false"));
                }
                if (isValid) {
                    isValid = inputString.length() >= mEnreplacedy.attributes.min.intValue() && inputString.length() <= mEnreplacedy.attributes.max.intValue();
                }
                dialog.getActionButton(DialogAction.POSITIVE).setEnabled(isValid);
            }
        }).positiveText(R.string.button_set).negativeText(R.string.button_cancel).onPositive(new MaterialDialog.SingleButtonCallback() {

            @Override
            public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                String input = CommonUtil.getDialogInput(dialog);
                callService(mEnreplacedy.getDomain(), "set_value", new CallServiceRequest(mEnreplacedy.enreplacedyId).setValue(input));
            }
        }).build();
        mInput = mDialog.getInputEditText();
        CommonUtil.fixDialogKeyboard(mDialog);
        return mDialog;
    }

    private void refreshUi() {
        mInput.setText("");
        mInput.append(mEnreplacedy.state);
    }

    @Override
    public void onClick(View view) {
    // switch (view.getId()) {
    // case R.id.button_cancel:
    // dismiss();
    // break;
    // case R.id.button_set:
    // callService(mEnreplacedy.getDomain(), "set_value", new CallServiceRequest(mEnreplacedy.enreplacedyId).setValue(mInput.getText().toString().trim()));
    // dismiss();
    // break;
    // }
    }

    @Override
    public void onChange(Enreplacedy enreplacedy) {
        super.onChange(enreplacedy);
        refreshUi();
    }
}

19 Source : AlarmControlPanelFragment.java
with Apache License 2.0
from axzae

@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public clreplaced AlarmControlPanelFragment extends BaseControlFragment implements View.OnClickListener {

    private EditText mInput;

    private MaterialDialog mDialog;

    public static AlarmControlPanelFragment newInstance(Enreplacedy enreplacedy) {
        AlarmControlPanelFragment fragment = new AlarmControlPanelFragment();
        Bundle args = new Bundle();
        args.putString("enreplacedy", CommonUtil.deflate(enreplacedy));
        fragment.setArguments(args);
        return fragment;
    }

    @NonNull
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        switch(mEnreplacedy.state) {
            case "armed_away":
            case "armed_home":
            case "pending":
                {
                    MaterialDialog.Builder builder = new MaterialDialog.Builder(getActivity()).replacedle(mEnreplacedy.getFriendlyName()).autoDismiss(true).cancelable(true).alwaysCallInputCallback().negativeText(R.string.action_cancel).positiveText("Disarm").onPositive(new MaterialDialog.SingleButtonCallback() {

                        @Override
                        public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                            String input = CommonUtil.getDialogInput(dialog);
                            callService(mEnreplacedy.getDomain(), "alarm_disarm", new CallServiceRequest(mEnreplacedy.enreplacedyId).setCode(input));
                        }
                    });
                    if (true) {
                        builder.input("Code (Optional)", "", new MaterialDialog.InputCallback() {

                            @Override
                            public void onInput(@NonNull MaterialDialog dialog, CharSequence input) {
                                final String inputString = input.toString();
                                boolean isValid = true;
                                if (mEnreplacedy.attributes.codeFormat != null) {
                                    isValid = inputString.matches(mEnreplacedy.attributes.codeFormat);
                                // Log.d("YouQi", "Pattern: " + mEnreplacedy.attributes.pattern + ", isValid? " + (isValid ? "true" : "false"));
                                }
                                dialog.getActionButton(DialogAction.POSITIVE).setEnabled(isValid);
                            }
                        });
                    }
                    mDialog = builder.build();
                }
                break;
            case "disarmed":
                {
                    mDialog = new MaterialDialog.Builder(getActivity()).replacedle(mEnreplacedy.getFriendlyName()).autoDismiss(true).cancelable(true).negativeText("Arm Away").positiveText("Arm Home").alwaysCallInputCallback().input("Code (Optional)", "", new MaterialDialog.InputCallback() {

                        @Override
                        public void onInput(@NonNull MaterialDialog dialog, CharSequence input) {
                            final String inputString = input.toString();
                            boolean isValid = true;
                            if (mEnreplacedy.attributes.codeFormat != null) {
                                isValid = inputString.matches(mEnreplacedy.attributes.codeFormat);
                            }
                            dialog.getActionButton(DialogAction.NEGATIVE).setEnabled(isValid);
                            dialog.getActionButton(DialogAction.POSITIVE).setEnabled(isValid);
                        }
                    }).onNegative(new MaterialDialog.SingleButtonCallback() {

                        @Override
                        public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                            String input = CommonUtil.getDialogInput(dialog);
                            callService(mEnreplacedy.getDomain(), "alarm_arm_away", new CallServiceRequest(mEnreplacedy.enreplacedyId).setCode(input));
                        }
                    }).onPositive(new MaterialDialog.SingleButtonCallback() {

                        @Override
                        public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                            String input = CommonUtil.getDialogInput(dialog);
                            callService(mEnreplacedy.getDomain(), "alarm_arm_home", new CallServiceRequest(mEnreplacedy.enreplacedyId).setCode(input));
                        }
                    }).build();
                }
                break;
        }
        mInput = mDialog.getInputEditText();
        CommonUtil.fixDialogKeyboard(mDialog);
        return mDialog;
    }

    private void refreshUi() {
        mInput.setText("");
        mInput.append(mEnreplacedy.state);
    }

    @Override
    public void onClick(View view) {
    }

    @Override
    public void onChange(Enreplacedy enreplacedy) {
        super.onChange(enreplacedy);
        refreshUi();
    }
}

18 Source : ReportBugsTask.java
with Apache License 2.0
from zixpo

/*
 * CandyBar - Material Dashboard
 *
 * Copyright (c) 2014-2016 Dani Mahardhika
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
public clreplaced ReportBugsTask extends AsyncTask<Void, Void, Boolean> {

    private final WeakReference<Context> mContext;

    private final String mDescription;

    private String mZipPath = null;

    private StringBuilder mStringBuilder;

    private MaterialDialog mDialog;

    private ReportBugsTask(Context context, String description) {
        mContext = new WeakReference<>(context);
        mDescription = description;
    }

    public static AsyncTask<Void, Void, Boolean> start(@NonNull Context context, @NonNull String description) {
        return start(context, description, SERIAL_EXECUTOR);
    }

    public static AsyncTask<Void, Void, Boolean> start(@NonNull Context context, @NonNull String description, @NonNull Executor executor) {
        return new ReportBugsTask(context, description).executeOnExecutor(executor);
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        MaterialDialog.Builder builder = new MaterialDialog.Builder(mContext.get());
        builder.typeface(TypefaceHelper.getMedium(mContext.get()), TypefaceHelper.getRegular(mContext.get())).content(R.string.report_bugs_building).progress(true, 0).progressIndeterminateStyle(true).cancelable(false).canceledOnTouchOutside(false);
        mDialog = builder.build();
        mDialog.show();
        mStringBuilder = new StringBuilder();
    }

    @Override
    protected Boolean doInBackground(Void... voids) {
        if (!isCancelled()) {
            try {
                Thread.sleep(1);
                List<String> files = new ArrayList<>();
                mStringBuilder.append(DeviceHelper.getDeviceInfo(mContext.get())).append("\n").append(mDescription).append("\n");
                File brokenAppFilter = ReportBugsHelper.buildBrokenAppFilter(mContext.get());
                if (brokenAppFilter != null)
                    files.add(brokenAppFilter.toString());
                File brokenDrawables = ReportBugsHelper.buildBrokenDrawables(mContext.get());
                if (brokenDrawables != null)
                    files.add(brokenDrawables.toString());
                File activityList = ReportBugsHelper.buildActivityList(mContext.get());
                if (activityList != null)
                    files.add(activityList.toString());
                String stackTrace = Preferences.get(mContext.get()).getLatestCrashLog();
                File crashLog = ReportBugsHelper.buildCrashLog(mContext.get(), stackTrace);
                if (crashLog != null)
                    files.add(crashLog.toString());
                mZipPath = FileHelper.createZip(files, new File(mContext.get().getCacheDir(), RequestHelper.getGeneratedZipName(ReportBugsHelper.REPORT_BUGS)));
                return true;
            } catch (Exception e) {
                LogUtil.e(Log.getStackTraceString(e));
                return false;
            }
        }
        return false;
    }

    @Override
    protected void onPostExecute(Boolean aBoolean) {
        super.onPostExecute(aBoolean);
        if (mContext.get() == null)
            return;
        if (((AppCompatActivity) mContext.get()).isFinishing())
            return;
        mDialog.dismiss();
        if (aBoolean) {
            String emailAddress = mContext.get().getString(R.string.regular_request_email);
            // Fallback to dev_email
            if (emailAddress.length() == 0)
                emailAddress = mContext.get().getString(R.string.dev_email);
            final Intent intent = new Intent(Intent.ACTION_SEND);
            intent.setType("application/zip");
            intent.putExtra(Intent.EXTRA_EMAIL, new String[] { emailAddress });
            intent.putExtra(Intent.EXTRA_SUBJECT, "Report Bugs " + (mContext.get().getString(R.string.app_name)));
            intent.putExtra(Intent.EXTRA_TEXT, mStringBuilder.toString());
            if (mZipPath != null) {
                File zip = new File(mZipPath);
                if (zip.exists()) {
                    Uri uri = getUriFromFile(mContext.get(), mContext.get().getPackageName(), zip);
                    if (uri == null)
                        uri = Uri.fromFile(zip);
                    intent.putExtra(Intent.EXTRA_STREAM, uri);
                    intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                }
            }
            mContext.get().startActivity(Intent.createChooser(intent, mContext.get().getResources().getString(R.string.app_client)));
        } else {
            Toast.makeText(mContext.get(), R.string.report_bugs_failed, Toast.LENGTH_LONG).show();
        }
        mZipPath = null;
    }
}

18 Source : LicenseCallbackHelper.java
with Apache License 2.0
from zixpo

/*
 * CandyBar - Material Dashboard
 *
 * Copyright (c) 2014-2016 Dani Mahardhika
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
public clreplaced LicenseCallbackHelper implements LicenseCallback {

    private final Context mContext;

    private final MaterialDialog mDialog;

    public LicenseCallbackHelper(@NonNull Context context) {
        mContext = context;
        MaterialDialog.Builder builder = new MaterialDialog.Builder(mContext);
        builder.typeface(TypefaceHelper.getMedium(mContext), TypefaceHelper.getRegular(mContext));
        builder.content(R.string.license_checking).progress(true, 0);
        mDialog = builder.build();
        mDialog.setCancelable(false);
        mDialog.setCanceledOnTouchOutside(false);
    }

    @Override
    public void onLicenseCheckStart() {
        mDialog.show();
    }

    @Override
    public void onLicenseCheckFinished(LicenseHelper.Status status) {
        mDialog.dismiss();
        if (status == LicenseHelper.Status.RETRY) {
            showRetryDialog();
            return;
        }
        showLicenseDialog(status);
    }

    private void showLicenseDialog(LicenseHelper.Status status) {
        int message = status == LicenseHelper.Status.SUCCESS ? R.string.license_check_success : R.string.license_check_failed;
        new MaterialDialog.Builder(mContext).typeface(TypefaceHelper.getMedium(mContext), TypefaceHelper.getRegular(mContext)).replacedle(R.string.license_check).content(message).positiveText(R.string.close).onPositive((dialog, which) -> {
            onLicenseChecked(status);
            dialog.dismiss();
        }).cancelable(false).canceledOnTouchOutside(false).show();
    }

    private void showRetryDialog() {
        new MaterialDialog.Builder(mContext).typeface(TypefaceHelper.getMedium(mContext), TypefaceHelper.getRegular(mContext)).replacedle(R.string.license_check).content(R.string.license_check_retry).positiveText(R.string.close).cancelable(false).canceledOnTouchOutside(false).onPositive((dialog, which) -> ((AppCompatActivity) mContext).finish()).show();
    }

    private void onLicenseChecked(LicenseHelper.Status status) {
        Preferences.get(mContext).setFirstRun(false);
        if (status == LicenseHelper.Status.SUCCESS) {
            Preferences.get(mContext).setLicensed(true);
            if (Preferences.get(mContext).isNewVersion()) {
                ChangelogFragment.showChangelog(((AppCompatActivity) mContext).getSupportFragmentManager());
                File cache = mContext.getCacheDir();
                FileHelper.clearDirectory(cache);
            }
        } else if (status == LicenseHelper.Status.FAILED) {
            Preferences.get(mContext).setLicensed(false);
            ((AppCompatActivity) mContext).finish();
        }
    }
}

18 Source : DialogsBehaviour.java
with Apache License 2.0
from VictorAlbertos

public final clreplaced DialogsBehaviour implements Dialogs {

    private final BaseApp baseApp;

    private MaterialDialog materialDialog;

    @Inject
    public DialogsBehaviour(BaseApp baseApp) {
        this.baseApp = baseApp;
    }

    @Override
    public void showLoading() {
        if (materialDialog == null) {
            materialDialog = builderLoading(null).show();
        }
    }

    @Override
    public void showLoading(String content) {
        if (materialDialog == null) {
            materialDialog = builderLoading(content).show();
        }
    }

    @Override
    public void showNoCancelableLoading() {
        if (materialDialog == null) {
            materialDialog = builderLoading(null).cancelable(false).show();
        }
    }

    @Override
    public void showNoCancelableLoading(String content) {
        if (materialDialog == null) {
            materialDialog = builderLoading(content).cancelable(false).show();
        }
    }

    @Override
    public void hideLoading() {
        if (materialDialog != null) {
            materialDialog.dismiss();
            materialDialog = null;
        }
    }

    private MaterialDialog.Builder builderLoading(String content) {
        return new MaterialDialog.Builder(baseApp.getLiveActivity()).replacedleColorRes(R.color.colorPrimaryDark).contentColor(ContextCompat.getColor(baseApp, R.color.colorPrimaryDark)).widgetColorRes(R.color.colorPrimaryDark).replacedle(baseApp.getString(R.string.app_name)).content(TextUtils.isEmpty(content) ? baseApp.getString(R.string.loading) : content).progress(true, 0);
    }
}

18 Source : AppearanceSettingsFragment.java
with GNU General Public License v3.0
from twireapp

private void onClickThemeColor() {
    MaterialDialog themeChooserDialog = DialogService.getThemeDialog(getActivity());
    themeChooserDialog.show();
}

18 Source : DialogHelper.java
with GNU General Public License v3.0
from tranleduy2000

public static void showFilenameSuggestingDialog(final Context context, final MaterialDialog.SingleButtonCallback callback, final MaterialDialog.InputCallback inputCallback, int replacedleResId) {
    MaterialDialog.Builder builder = new MaterialDialog.Builder(context);
    builder.replacedle(replacedleResId).negativeText(android.R.string.cancel).positiveText(android.R.string.ok).content(R.string.enter_filename).input("", "", inputCallback).onAny(callback);
    MaterialDialog show = builder.show();
    initFilenameInputDialog(show);
}

18 Source : DirectoryInfoDialog.java
with Apache License 2.0
from RuijiePan

public MaterialDialog onCreateDialog(final Bundle savedInstanceState) {
    path = getArguments() != null ? getArguments().getString("path") : Settings.getDefaultDir();
    final Activity activity = this.getActivity();
    mView = activity.getLayoutInflater().inflate(R.layout.dialog_directory_info, null);
    MaterialDialog dialog = new MaterialDialog.Builder(activity).replacedle(R.string.dir_info).customView(mView, true).positiveText(R.string.ok).build();
    return dialog;
}

18 Source : PictureFragment.java
with Apache License 2.0
from RuijiePan

/**
 * Created by panruijie on 17/1/18.
 * Email : [email protected]
 */
public clreplaced PictureFragment extends BaseFragment implements PictureContact.View {

    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;

    private MaterialDialog mDialog;

    private PictureAdapter mAdapter;

    private PicturePresenter mPresenter;

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_category_item;
    }

    @Override
    protected void initViews(View self, Bundle savedInstanceState) {
        mDialog = new MaterialDialog.Builder(getContext()).content(R.string.loading).progress(true, 0).build();
    }

    @Override
    protected void initData() {
        mAdapter = new PictureAdapter();
        recyclerView.setLayoutManager(new GridLayoutManager(getContext(), 2));
        recyclerView.setHasFixedSize(true);
        recyclerView.addItemDecoration(new DividerGridItemDecoration(getContext()));
        recyclerView.setAdapter(mAdapter);
        mPresenter = new PicturePresenter(getContext());
        mPresenter.attachView(this);
        mPresenter.getData();
    }

    @Override
    protected void initListeners() {
        mAdapter.setOnItemClickListener(dir -> {
            mPresenter.onItemClick(dir);
        });
    }

    @Override
    public void showDialog() {
        mDialog.show();
    }

    @Override
    public void dimissDialog() {
        mDialog.dismiss();
    }

    @Override
    public void setData(ArrayList<ImageFolder> list) {
        /*for (ImageFolder folder:list){
            Log.w(TAG,folder.getDir());
        }*/
        mAdapter.setData(list);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mPresenter.detachView();
    }
}

18 Source : PictureDirFragment.java
with Apache License 2.0
from RuijiePan

/**
 * Created by panruijie on 17/1/19.
 * Email : [email protected]
 */
public clreplaced PictureDirFragment extends BaseFragment implements PictureDirContact.View {

    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;

    private MaterialDialog mDialog;

    private PictureDirPresenter mPresenter;

    private PictureDirAdapter mAdapter;

    private String dirPath;

    public static PictureDirFragment newInstance(String dirPath) {
        PictureDirFragment instance = new PictureDirFragment();
        Bundle args = new Bundle();
        args.putString("dirPath", dirPath);
        instance.setArguments(args);
        return instance;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        dirPath = getArguments() != null ? getArguments().getString("dirPath") : Environment.getExternalStorageDirectory().getPath() + File.separator + "DCIM";
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_category_item;
    }

    @Override
    protected void initViews(View self, Bundle savedInstanceState) {
        mDialog = new MaterialDialog.Builder(getContext()).content(R.string.loading).progress(true, 0).build();
    }

    @Override
    protected void initData() {
        mAdapter = new PictureDirAdapter(getContext());
        recyclerView.setLayoutManager(new GridLayoutManager(getContext(), 3));
        recyclerView.setHasFixedSize(true);
        recyclerView.addItemDecoration(new DividerGridItemDecoration(getContext()));
        recyclerView.setAdapter(mAdapter);
        mPresenter = new PictureDirPresenter(getContext(), dirPath);
        mPresenter.attachView(this);
        mPresenter.getData();
    }

    @Override
    protected void initListeners() {
        mAdapter.setOnItemClickListener(position -> {
            mPresenter.onItemClick(position, mAdapter.getData());
        });
    }

    @Override
    public void showDialog() {
        mDialog.show();
    }

    @Override
    public void dimissDialog() {
        mDialog.dismiss();
    }

    @Override
    public void setTotalCount(int count) {
    }

    @Override
    public void setDataUsingObservable(Observable<List<String>> observable) {
        observable.subscribe(list -> {
            mAdapter.setData(list);
        }, Throwable::printStackTrace);
    }
}

18 Source : MusicFragment.java
with Apache License 2.0
from RuijiePan

/**
 * Created by panruijie on 17/1/2.
 * Email : [email protected]
 */
public clreplaced MusicFragment extends BaseFragment implements MusicContact.View {

    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;

    private MaterialDialog mDialog;

    private MusicPresenter mPresenter;

    private MusicAdapter mAdapter;

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_category_item;
    }

    @Override
    protected void initViews(View self, Bundle savedInstanceState) {
        mDialog = new MaterialDialog.Builder(getContext()).content(R.string.loading).progress(true, 0).build();
    }

    @Override
    protected void initData() {
        mAdapter = new MusicAdapter(getContext());
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        recyclerView.setHasFixedSize(true);
        recyclerView.setAdapter(mAdapter);
        mPresenter = new MusicPresenter(getContext());
        mPresenter.attachView(this);
        mPresenter.getData();
    }

    @Override
    protected void initListeners() {
        mAdapter.sereplacedemClickListner(new BaseAdapter.OnRecyclerViewItemClickListener() {

            @Override
            public void onItemClick(int position) {
                mPresenter.onItemClick(mAdapter.getData(position).getUrl());
            }

            @Override
            public void onMultipeChoice(List<String> items) {
                RxBus.getDefault().post(new ActionMutipeChoiceEvent(items));
            }

            @Override
            public void onMultipeChoiceStart() {
            // ToastUtil.showToast(getContext(),"进入多选模式");
            }

            @Override
            public void onMultipeChoiceCancel() {
                ToastUtil.showToast(getContext(), "退出多选模式");
            }
        });
    }

    @Override
    public void showDialog() {
        if (!mDialog.isShowing())
            mDialog.show();
    }

    @Override
    public void dimissDialog() {
        if (mDialog.isShowing())
            mDialog.cancel();
    }

    @Override
    public void setData(ArrayList<Music> list) {
        mAdapter.setData(list);
    }

    @Override
    public void selectAll() {
        if (mAdapter.getSelectedItemCount() == mAdapter.gereplacedemCount()) {
            mAdapter.clearSelections();
            mAdapter.isLongClick(false);
            RxBus.getDefault().post(new ActionMutipeChoiceEvent(mAdapter.getSelectedFilesPath()));
        } else {
            mAdapter.setAllSelections();
        }
    }

    @Override
    public void clearSelect() {
        mAdapter.clearSelections();
    }

    @Override
    public void setDataByObservable(Observable<ArrayList<Music>> observable) {
        observable.subscribe(data -> {
            mAdapter.setData(data);
        });
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mPresenter.detachView();
    }
}

18 Source : CategoryBottomFragment.java
with Apache License 2.0
from RuijiePan

/**
 * Created by panruijie on 17/1/2.
 * Email : [email protected]
 * category底部doc、zip、apk三个fragment总和类
 * viedo模块也包括
 */
public clreplaced CategoryBottomFragment extends BaseFragment implements CategoryBottomContact.View {

    @BindView(R.id.recyclerView)
    RecyclerView mRecyclerView;

    private CategoryBottomPresenter mPresenter;

    private CategoryBottomAdapter mAdapter;

    private MaterialDialog mDialog;

    private int mIndex;

    public static BaseFragment newInstance(int index) {
        BaseFragment instance = new CategoryBottomFragment();
        Bundle args = new Bundle();
        args.putInt(AppConstant.INDEX, index);
        instance.setArguments(args);
        return instance;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mIndex = getArguments() != null ? getArguments().getInt(AppConstant.INDEX) : AppConstant.APK_INDEX;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_category_item;
    }

    @Override
    protected void initViews(View self, Bundle savedInstanceState) {
        mDialog = new MaterialDialog.Builder(getContext()).content(R.string.loading).progress(true, 0).build();
    }

    @Override
    protected void initData() {
        mAdapter = new CategoryBottomAdapter(getContext());
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        mRecyclerView.setHasFixedSize(true);
        mRecyclerView.setAdapter(mAdapter);
        mPresenter = new CategoryBottomPresenter(getContext());
        mPresenter.attachView(this);
        mPresenter.setIndex(mIndex);
    }

    @Override
    protected void initListeners() {
        mAdapter.sereplacedemClickListner(new BaseAdapter.OnRecyclerViewItemClickListener() {

            @Override
            public void onItemClick(int position) {
                mPresenter.onItemClick(mAdapter.getData(position));
            }

            @Override
            public void onMultipeChoice(List<String> items) {
                RxBus.getDefault().post(new ActionMutipeChoiceEvent(items));
            }

            @Override
            public void onMultipeChoiceStart() {
            // ToastUtil.showToast(getContext(),"进入多选模式");
            }

            @Override
            public void onMultipeChoiceCancel() {
                ToastUtil.showToast(getContext(), "退出多选模式");
            }
        });
    }

    @Override
    public void showDialog() {
        if (!mDialog.isShowing()) {
            mDialog.show();
        }
    }

    @Override
    public void dimissDialog() {
        if (mDialog.isShowing()) {
            mDialog.cancel();
        }
    }

    @Override
    public void setData(ArrayList<String> list) {
        mAdapter.setData(list);
    }

    @Override
    public void selectAll() {
        if (mAdapter.getSelectedItemCount() == mAdapter.gereplacedemCount()) {
            mAdapter.clearSelections();
            mAdapter.isLongClick(false);
            RxBus.getDefault().post(new ActionMutipeChoiceEvent(mAdapter.getSelectedFilesPath()));
        } else {
            mAdapter.setAllSelections();
        }
    }

    @Override
    public void clearSelect() {
        mAdapter.clearSelections();
    }

    @Override
    public void setDataByObservable(Observable<ArrayList<String>> observable) {
        observable.subscribe(data -> {
            mAdapter.setData(data);
        });
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mPresenter.detachView();
    }
}

18 Source : ZipTask.java
with Apache License 2.0
from RuijiePan

public final clreplaced ZipTask extends AsyncTask<String, Void, List<String>> {

    private final WeakReference<Activity> activity;

    private MaterialDialog dialog;

    private final String zipname;

    public ZipTask(final Activity activity, String name1) {
        this.activity = new WeakReference<>(activity);
        this.zipname = name1;
    }

    @Override
    protected void onPreExecute() {
        final Activity activity = this.activity.get();
        if (activity != null) {
            this.dialog = new MaterialDialog.Builder(activity).progress(true, 0).content(activity.getString(R.string.packing)).cancelable(true).build();
            if (!activity.isFinishing()) {
                this.dialog.show();
            }
        }
    }

    @Override
    protected List<String> doInBackground(String... files) {
        final List<String> failed = new ArrayList<>();
        try {
            ZipUtils.createZip(files, zipname);
            SqlUtil.insert(zipname);
        } catch (Exception e) {
            failed.add(Arrays.toString(files));
        }
        return failed;
    }

    @Override
    protected void onPostExecute(final List<String> failed) {
        super.onPostExecute(failed);
        this.finish(failed);
    }

    @Override
    protected void onCancelled(final List<String> failed) {
        super.onCancelled(failed);
        this.finish(failed);
    }

    private void finish(final List<String> failed) {
        if (this.dialog != null) {
            this.dialog.dismiss();
        }
        final Activity activity = this.activity.get();
        if (activity != null && !failed.isEmpty()) {
            Toast.makeText(activity, activity.getString(R.string.cantopenfile), Toast.LENGTH_SHORT).show();
            if (!activity.isFinishing()) {
                dialog.show();
            }
        }
        RxBus.getDefault().post(new RefreshEvent());
        RxBus.getDefault().post(new TypeEvent(AppConstant.REFRESH));
    }
}

18 Source : UnzipTask.java
with Apache License 2.0
from RuijiePan

public final clreplaced UnzipTask extends AsyncTask<File, Void, List<String>> {

    private final WeakReference<Activity> activity;

    private MaterialDialog dialog;

    public UnzipTask(final Activity activity) {
        this.activity = new WeakReference<>(activity);
    }

    @Override
    protected void onPreExecute() {
        final Activity activity = this.activity.get();
        if (activity != null) {
            this.dialog = new MaterialDialog.Builder(activity).progress(true, 0).content(activity.getString(R.string.unzipping)).cancelable(true).build();
            if (!activity.isFinishing()) {
                this.dialog.show();
            }
        }
    }

    @Override
    protected List<String> doInBackground(File... files) {
        final Activity activity = this.activity.get();
        final List<String> failed = new ArrayList<>();
        final String ext = FileUtil.getExtension(files[0].getName());
        try {
            if (ext.equals("zip")) {
                ZipUtils.unpackZip(files[0], files[1]);
            }
        } catch (Exception e) {
            failed.add(Arrays.toString(files));
        }
        if (files[1].canRead()) {
            for (File file : files[1].listFiles()) MediaStoreUtils.addFileToMediaStore(file.getPath(), activity);
        }
        return failed;
    }

    @Override
    protected void onPostExecute(final List<String> failed) {
        super.onPostExecute(failed);
        this.finish(failed);
    }

    @Override
    protected void onCancelled(final List<String> failed) {
        super.onCancelled(failed);
        this.finish(failed);
    }

    private void finish(final List<String> failed) {
        if (this.dialog != null) {
            this.dialog.dismiss();
        }
        final Activity activity = this.activity.get();
        if (failed.isEmpty()) {
            Toast.makeText(activity, activity.getString(R.string.extractionsuccess), Toast.LENGTH_SHORT).show();
            RxBus.getDefault().post(new TypeEvent(AppConstant.REFRESH));
        }
        if (activity != null && !failed.isEmpty()) {
            Toast.makeText(activity, activity.getString(R.string.cantopenfile), Toast.LENGTH_SHORT).show();
            if (!activity.isFinishing()) {
                dialog.show();
            }
        }
    }
}

18 Source : RenameTask.java
with Apache License 2.0
from RuijiePan

public final clreplaced RenameTask extends AsyncTask<String, Void, List<String>> {

    private final WeakReference<Activity> activity;

    private MaterialDialog dialog;

    private boolean succes = false;

    private String path;

    public RenameTask(final Activity activity, String path) {
        this.activity = new WeakReference<>(activity);
        this.path = path;
    }

    @Override
    protected void onPreExecute() {
        final Activity activity = this.activity.get();
        if (activity != null) {
            this.dialog = new MaterialDialog.Builder(activity).progress(true, 0).content(activity.getString(R.string.rename)).cancelable(true).negativeText(R.string.cancel).build();
            if (!activity.isFinishing()) {
                this.dialog.show();
            }
        }
    }

    @Override
    protected List<String> doInBackground(String... files) {
        final List<String> failed = new ArrayList<>();
        try {
            if (FileUtil.renameTarget(path + File.separator + files[0], files[1])) {
                succes = true;
                SqlUtil.update(path + File.separator + files[0], path + File.separator + files[1]);
            } else {
                if (Settings.rootAccess()) {
                    RootCommands.renameRootTarget(path, files[0], files[1]);
                    succes = true;
                    SqlUtil.update(path + File.separator + files[0], path + File.separator + files[1]);
                }
            }
        } catch (Exception e) {
            failed.add(files[1]);
            succes = false;
        }
        return failed;
    }

    @Override
    protected void onPostExecute(final List<String> failed) {
        super.onPostExecute(failed);
        this.finish(failed);
        RxBus.getDefault().post(new TypeEvent(AppConstant.REFRESH));
        RxBus.getDefault().post(new TypeEvent(AppConstant.CLEAN_CHOICE));
    }

    @Override
    protected void onCancelled(final List<String> failed) {
        super.onCancelled(failed);
        this.finish(failed);
    }

    private void finish(final List<String> failed) {
        if (this.dialog != null) {
            this.dialog.dismiss();
        }
        final Activity activity = this.activity.get();
        if (succes)
            Toast.makeText(activity, activity.getString(R.string.filewasrenamed), Toast.LENGTH_LONG).show();
        RxBus.getDefault().post(new CleanChoiceEvent());
        RxBus.getDefault().post(new RefreshEvent());
        RxBus.getDefault().post(new TypeEvent(AppConstant.REFRESH));
        if (activity != null && !failed.isEmpty()) {
            Toast.makeText(activity, activity.getString(R.string.cantopenfile), Toast.LENGTH_SHORT).show();
        /*if (!activity.isFinishing()) {
                dialog.show();
            }*/
        }
    }
}

18 Source : PasteTask.java
with Apache License 2.0
from RuijiePan

public final clreplaced PasteTask extends AsyncTask<String, Void, List<String>> {

    private final WeakReference<Activity> activity;

    private MaterialDialog dialog;

    private final File location;

    private boolean success = false;

    public PasteTask(final Activity activity, File currentDir) {
        this.activity = new WeakReference<>(activity);
        this.location = currentDir;
    }

    @Override
    protected void onPreExecute() {
        final Activity activity = this.activity.get();
        if (activity != null) {
            this.dialog = new MaterialDialog.Builder(activity).progress(true, 0).build();
            if (ClipBoard.isMove()) {
                this.dialog.setContent(activity.getString(R.string.moving));
            } else {
                this.dialog.setContent(activity.getString(R.string.copying));
            }
            this.dialog.setCancelable(true);
            this.dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {

                @Override
                public void onCancel(DialogInterface dialog) {
                    cancel(false);
                }
            });
            if (!activity.isFinishing()) {
                this.dialog.show();
            }
        }
    }

    @Override
    protected List<String> doInBackground(String... content) {
        final List<String> failed = new ArrayList<>();
        final Activity activity = this.activity.get();
        ClipBoard.lock();
        for (String s : content) {
            String fileName = s.substring(s.lastIndexOf("/"), s.length());
            if (ClipBoard.isMove()) {
                FileUtil.moveToDirectory(new File(s), new File(location, fileName), activity);
                if (!new File(s).isDirectory()) {
                    SqlUtil.update(s, location + File.separator + fileName);
                }
                success = true;
            } else {
                if (new File(s).isDirectory()) {
                    success = FileUtils.copyDir(s, location + File.separator + fileName);
                } else {
                    success = FileUtils.copyFile(new File(s), new File(location, fileName));
                    SqlUtil.insert(location + File.separator + fileName);
                }
            // FileUtil.copyFile(new File(s), new File(location, fileName), activity);
            }
        }
        if (location.canRead()) {
            for (File file : location.listFiles()) {
                MediaStoreUtils.addFileToMediaStore(file.getPath(), activity);
            }
        }
        return failed;
    }

    @Override
    protected void onPostExecute(final List<String> failed) {
        super.onPostExecute(failed);
        this.finish(failed);
        RxBus.getDefault().post(new RefreshEvent());
        RxBus.getDefault().post(new TypeEvent(AppConstant.REFRESH));
    }

    @Override
    protected void onCancelled(final List<String> failed) {
        super.onCancelled(failed);
        this.finish(failed);
    }

    private void finish(final List<String> failed) {
        if (this.dialog != null) {
            this.dialog.dismiss();
        }
        final Activity activity = this.activity.get();
        if (ClipBoard.isMove()) {
            if (success) {
                Toast.makeText(activity, activity.getString(R.string.movesuccsess), Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(activity, activity.getString(R.string.movefail), Toast.LENGTH_SHORT).show();
            }
        } else {
            if (success) {
                Toast.makeText(activity, activity.getString(R.string.copysuccsess), Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(activity, activity.getString(R.string.copyfail), Toast.LENGTH_SHORT).show();
            }
        }
        ClipBoard.unlock();
        ClipBoard.clear();
        activity.invalidateOptionsMenu();
        if (!failed.isEmpty()) {
            Toast.makeText(activity, activity.getString(R.string.cantopenfile), Toast.LENGTH_SHORT).show();
            if (!activity.isFinishing()) {
                dialog.show();
            }
        }
    }
}

18 Source : DeleteTask.java
with Apache License 2.0
from RuijiePan

public final clreplaced DeleteTask extends AsyncTask<String, Void, List<String>> {

    private final WeakReference<Activity> activity;

    private MaterialDialog dialog;

    public DeleteTask(final Activity activity) {
        this.activity = new WeakReference<>(activity);
    }

    @Override
    protected void onPreExecute() {
        final Activity activity = this.activity.get();
        if (activity != null) {
            this.dialog = new MaterialDialog.Builder(activity).progress(true, 0).content(activity.getString(R.string.deleting)).cancelable(true).build();
            if (!activity.isFinishing()) {
                this.dialog.show();
            }
        }
    }

    @Override
    protected List<String> doInBackground(String... files) {
        final Activity activity = this.activity.get();
        final List<String> failed = new ArrayList<>();
        for (String str : files) {
            FileUtil.deleteTarget(str);
            SqlUtil.delete(str);
        }
        MediaScannerConnection.scanFile(activity, files, null, null);
        return failed;
    }

    @Override
    protected void onPostExecute(final List<String> failed) {
        super.onPostExecute(failed);
        this.finish(failed);
    }

    @Override
    protected void onCancelled(final List<String> failed) {
        super.onCancelled(failed);
        this.finish(failed);
    }

    private void finish(final List<String> failed) {
        if (this.dialog != null) {
            this.dialog.dismiss();
        }
        final Activity activity = this.activity.get();
        if (activity != null && !failed.isEmpty()) {
            Toast.makeText(activity, activity.getString(R.string.cantopenfile), Toast.LENGTH_SHORT).show();
            if (!activity.isFinishing()) {
                dialog.show();
            }
        } else {
            Toast.makeText(activity, activity.getString(R.string.deletesuccess), Toast.LENGTH_SHORT).show();
        }
        RxBus.getDefault().post(new CleanChoiceEvent());
        RxBus.getDefault().post(new RefreshEvent());
        RxBus.getDefault().post(new TypeEvent(AppConstant.CLEAN_CHOICE));
        RxBus.getDefault().post(new TypeEvent(AppConstant.REFRESH));
    }
}

18 Source : FragmentShowAvatars.java
with GNU Affero General Public License v3.0
from RooyeKhat-Media

// ***************************************************************************************
private void showPopupMenu(int r) {
    MaterialDialog dialog = new MaterialDialog.Builder(G.fragmentActivity).items(r).contentColor(Color.BLACK).itemsCallback(new MaterialDialog.ListCallback() {

        @Override
        public void onSelection(MaterialDialog dialog, View view, int which, CharSequence text) {
            if (text.equals(G.fragmentActivity.getResources().getString(R.string.save_to_gallery))) {
                saveToGallery();
            } else if (text.equals(G.fragmentActivity.getResources().getString(array_Delete_photo))) {
                switch(from) {
                    case setting:
                        deletePhotoSetting();
                        break;
                    case group:
                        deletePhotoGroup();
                        break;
                    case channel:
                        deletePhotoChannel();
                        break;
                    case chat:
                        deletePhotoChat();
                        break;
                }
            }
        }
    }).build();
    DialogAnimation.animationUp(dialog);
    dialog.show();
// WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams();
// layoutParams.copyFrom(dialog.getWindow().getAttributes());
// layoutParams.width = (int) G.context.getResources().getDimension(R.dimen.dp200);
// layoutParams.gravity = Gravity.TOP | Gravity.RIGHT;
// dialog.getWindow().setAttributes(layoutParams);
}

18 Source : ShareAdapter.java
with GNU General Public License v3.0
from PowerExplorer

/**
 * Created by Arpit on 01-07-2015.
 */
clreplaced ShareAdapter extends RecyclerArrayAdapter<Intent, ShareAdapter.ViewHolder> {

    private MaterialDialog dialog;

    private ArrayList<String> labels;

    private ArrayList<Drawable> drawables;

    private Context context;

    void updateMatDialog(MaterialDialog b) {
        this.dialog = b;
    }

    ShareAdapter(Context context, ArrayList<Intent> intents, ArrayList<String> labels, ArrayList<Drawable> arrayList1) {
        addAll(intents);
        this.context = context;
        this.labels = labels;
        this.drawables = arrayList1;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.simplerow, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        holder.render(position);
    }

    clreplaced ViewHolder extends RecyclerView.ViewHolder {

        private View rootView;

        private TextView textView;

        private ImageView imageView;

        ViewHolder(View view) {
            super(view);
            rootView = view;
            textView = ((TextView) view.findViewById(R.id.firstline));
            imageView = (ImageView) view.findViewById(R.id.icon);
        }

        void render(final int position) {
            if (drawables.get(position) != null)
                imageView.setImageDrawable(drawables.get(position));
            textView.setVisibility(View.VISIBLE);
            textView.setText(labels.get(position));
            rootView.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    if (dialog != null && dialog.isShowing())
                        dialog.dismiss();
                    context.startActivity(gereplacedem(position));
                }
            });
        }
    }
}

18 Source : FoldersPref.java
with GNU General Public License v3.0
from PowerExplorer

private void disableButtonIfNotPath(EditText path, final MaterialDialog dialog) {
    path.addTextChangedListener(new SimpleTexreplacedcher() {

        @Override
        public void afterTextChanged(Editable s) {
            dialog.getActionButton(DialogAction.POSITIVE).setEnabled(Futils.isPathAccesible(s.toString(), sharedPrefs));
        }
    });
}

18 Source : FoldersPref.java
with GNU General Public License v3.0
from PowerExplorer

private void disableButtonIfreplacedleEmpty(final EditText replacedle, final MaterialDialog dialog) {
    replacedle.addTextChangedListener(new SimpleTexreplacedcher() {

        @Override
        public void afterTextChanged(Editable s) {
            dialog.getActionButton(DialogAction.POSITIVE).setEnabled(replacedle.length() > 0);
        }
    });
}

18 Source : ColorPref.java
with GNU General Public License v3.0
from PowerExplorer

/**
 * Created by Arpit on 21-06-2015.
 */
public clreplaced ColorPref extends PreferenceFragment implements Preference.OnPreferenceClickListener {

    private MaterialDialog dialog;

    SharedPreferences sharedPref;

    PreferencesActivity activity;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // Load the preferences from an XML resource
        addPreferencesFromResource(R.xml.color_prefs);
        activity = (PreferencesActivity) getActivity();
        sharedPref = PreferenceManager.getDefaultSharedPreferences(getActivity());
        final CheckBox checkBoxPreference = (CheckBox) findPreference("random_checkbox");
        checkBoxPreference.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {

            @Override
            public boolean onPreferenceClick(Preference preference) {
                if (activity != null)
                    activity.setChanged();
                Toast.makeText(getActivity(), R.string.setRandom, Toast.LENGTH_LONG).show();
                return true;
            }
        });
        CheckBox preference8 = (CheckBox) findPreference("colorednavigation");
        preference8.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {

            @Override
            public boolean onPreferenceClick(Preference preference) {
                if (activity != null)
                    activity.setChanged();
                return true;
            }
        });
        if (Build.VERSION.SDK_INT >= 21)
            preference8.setEnabled(true);
        findPreference(ColorUsage.PRIMARY.replacedtring()).setOnPreferenceClickListener(this);
        findPreference(ColorUsage.PRIMARY_TWO.replacedtring()).setOnPreferenceClickListener(this);
        findPreference(ColorUsage.ACCENT.replacedtring()).setOnPreferenceClickListener(this);
        findPreference(ColorUsage.ICON_SKIN.replacedtring()).setOnPreferenceClickListener(this);
    }

    @Override
    public void onPause() {
        if (dialog != null) {
            dialog.dismiss();
        }
        super.onPause();
    }

    @Override
    public boolean onPreferenceClick(final Preference preference) {
        if (activity != null)
            activity.setChanged();
        final ColorUsage usage = ColorUsage.fromString(preference.getKey());
        if (usage != null) {
            ColorAdapter adapter = new ColorAdapter(getActivity(), ColorPreference.availableColors, usage);
            GridView v = (GridView) getActivity().getLayoutInflater().inflate(R.layout.dialog_grid, null);
            v.setAdapter(adapter);
            v.setOnItemClickListener(adapter);
            int fab_skin = activity.getColorPreference().getColor(ColorUsage.ACCENT);
            dialog = new MaterialDialog.Builder(getActivity()).positiveText(R.string.cancel).replacedle(R.string.choose_color).theme(activity.getAppTheme().getMaterialDialogTheme()).autoDismiss(true).positiveColor(fab_skin).neutralColor(fab_skin).neutralText(R.string.defualt).callback(new MaterialDialog.ButtonCallback() {

                @Override
                public void onNeutral(MaterialDialog dialog) {
                    super.onNeutral(dialog);
                    activity.getColorPreference().setRes(usage, usage.getDefaultColor()).saveToPreferences(sharedPref);
                }
            }).customView(v, false).build();
            adapter.setDialog(dialog);
            dialog.show();
        }
        return false;
    }

    private clreplaced ColorAdapter extends ArrayAdapter<Integer> implements AdapterView.OnItemClickListener {

        private String prefKey;

        private ColorUsage usage;

        @ColorInt
        private int selectedColor;

        private MaterialDialog dialog;

        public void setDialog(MaterialDialog b) {
            this.dialog = b;
        }

        /**
         * Constructor for adapter that handles the view creation of color chooser dialog in preferences
         *
         * @param context the context
         * @param colors  array list of color hex values in form of string; for the views
         * @param usage   the preference usage for setting new selected color preference value
         */
        ColorAdapter(Context context, List<Integer> colors, ColorUsage usage) {
            super(context, R.layout.rowlayout, colors);
            this.prefKey = usage.replacedtring();
            this.usage = usage;
            this.selectedColor = activity.getColorPreference().getColor(usage);
        }

        @ColorInt
        private int getColor(@ColorRes int colorRes) {
            return Utils.getColor(getContext(), colorRes);
        }

        @ColorRes
        private int getColorResAt(int position) {
            Integer item = gereplacedem(position);
            if (item == null) {
                return usage.getDefaultColor();
            } else {
                return item.intValue();
            }
        }

        @NonNull
        @Override
        public View getView(final int position, View convertView, @NonNull ViewGroup parent) {
            LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            // TODO solve unconditional layout inflation
            View rowView = inflater.inflate(R.layout.dialog_grid_item, parent, false);
            int color = getColor(getColorResAt(position));
            ImageView imageView = (ImageView) rowView.findViewById(R.id.icon);
            if (color == selectedColor)
                imageView.setImageResource(R.drawable.ic_checkmark_selected);
            GradientDrawable gradientDrawable = (GradientDrawable) imageView.getBackground();
            gradientDrawable.setColor(color);
            return rowView;
        }

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            int selectedColorRes = getColorResAt(position);
            activity.getColorPreference().setRes(usage, selectedColorRes).saveToPreferences(sharedPref);
            if (dialog != null)
                dialog.dismiss();
        }
    }
}

18 Source : InputDialog.java
with Apache License 2.0
from PDDStudio

@Override
public void onInput(@NonNull MaterialDialog dialog, CharSequence input) {
    if (callback != null) {
        callback.onInputReceived(input.toString());
    }
}

18 Source : VersionGuard.java
with Mozilla Public License 2.0
from newPersonKing

/**
 * Created by Stardust on 2017/4/12.
 */
public clreplaced VersionGuard {

    private Activity mActivity;

    private MaterialDialog mDeprecatedDialog;

    private VersionService mVersionService = VersionService.getInstance();

    public VersionGuard(Activity activity) {
        mActivity = activity;
    }

    public void checkForDeprecatesAndUpdates() {
        mVersionService.readDeprecatedFromPrefIfNeeded(mActivity);
        if (mVersionService.isCurrentVersionDeprecated()) {
            showDeprecatedDialogIfNeeded();
        } else {
            checkForUpdatesIfNeeded();
        }
    }

    private void checkForUpdatesIfNeeded() {
        mVersionService.checkForUpdatesIfNeededAndUsingWifi(mActivity).subscribe(new SimpleObserver<VersionInfo>() {

            @Override
            public void onNext(@io.reactivex.annotations.NonNull VersionInfo versionInfo) {
                if (mVersionService.isCurrentVersionDeprecated()) {
                    showDeprecatedDialogIfNeeded();
                } else {
                    showUpdateInfoIfNeeded(versionInfo);
                }
            }
        });
    }

    private void showUpdateInfoIfNeeded(org.autojs.autojs.network.enreplacedy.VersionInfo info) {
        if (BuildConfig.VERSION_CODE < info.versionCode) {
            new UpdateInfoDialogBuilder(mActivity, info).showDoNotAskAgain().show();
        }
    }

    private void showDeprecatedDialogIfNeeded() {
        if (mDeprecatedDialog != null && mDeprecatedDialog.isShowing())
            return;
        String content = mActivity.getString(R.string.warning_version_too_old);
        String issues = mVersionService.getCurrentVersionIssues();
        if (issues != null) {
            content += "\n" + issues;
        }
        mDeprecatedDialog = new MaterialDialog.Builder(mActivity).replacedle(R.string.text_version_too_old).content(content).positiveText(R.string.text_update).negativeText(R.string.text_exit).cancelable(false).autoDismiss(false).onAny(new MaterialDialog.SingleButtonCallback() {

            @Override
            public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                if (which == DialogAction.POSITIVE) {
                    new UpdateCheckDialog(mActivity).show();
                } else {
                    mActivity.finish();
                }
            }
        }).dismissListener(new DialogInterface.OnDismissListener() {

            @Override
            public void onDismiss(DialogInterface dialog) {
                mDeprecatedDialog = null;
            }
        }).show();
    }
}

18 Source : UpdateCheckDialog.java
with Mozilla Public License 2.0
from newPersonKing

/**
 * Created by Stardust on 2017/9/20.
 */
public clreplaced UpdateCheckDialog {

    private MaterialDialog mProgress;

    private Context mContext;

    public UpdateCheckDialog(Context context) {
        mProgress = new MaterialDialog.Builder(context).progress(true, 0).content(R.string.text_checking_update).build();
    }

    public void show() {
        mProgress.show();
        VersionService.getInstance().checkForUpdates().observeOn(AndroidSchedulers.mainThread()).subscribe(new SimpleObserver<VersionInfo>() {

            @Override
            public void onNext(@NonNull VersionInfo versionInfo) {
                mProgress.dismiss();
                if (versionInfo.isNewer()) {
                    new UpdateInfoDialogBuilder(mContext, versionInfo).show();
                } else {
                    Toast.makeText(GlobalAppContext.get(), R.string.text_is_latest_version, Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onError(@NonNull Throwable e) {
                e.printStackTrace();
                mProgress.dismiss();
                Toast.makeText(GlobalAppContext.get(), R.string.text_check_update_error, Toast.LENGTH_SHORT).show();
            }
        });
    }
}

18 Source : CodeEditor.java
with Mozilla Public License 2.0
from newPersonKing

/**
 * Copyright 2018 WHO<[email protected]>
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * <p>
 * Modified by project: https://github.com/980008027/JsDroidEditor
 */
public clreplaced CodeEditor extends HVScrollView {

    public interface CursorChangeCallback {

        void onCursorChange(String line, int ch);
    }

    private CodeEditText mCodeEditText;

    private TextViewRedoUndo mTextViewRedoUndo;

    private JavaScriptHighlighter mJavaScriptHighlighter;

    private Theme mTheme;

    private JsBeautifier mJsBeautifier;

    private MaterialDialog mProcessDialog;

    private CharSequence mReplacement = "";

    private String mKeywords;

    private Matcher mMatcher;

    private int mFoundIndex = -1;

    public CodeEditor(Context context) {
        super(context);
        init();
    }

    public CodeEditor(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    private void init() {
        // setFillViewport(true);
        inflate(getContext(), R.layout.code_editor, this);
        mCodeEditText = (CodeEditText) findViewById(R.id.code_edit_text);
        mCodeEditText.addTextChangedListener(new AutoIndent(mCodeEditText));
        mTextViewRedoUndo = new TextViewRedoUndo(mCodeEditText);
        mJavaScriptHighlighter = new JavaScriptHighlighter(mTheme, mCodeEditText);
        setTheme(Theme.getDefault(getContext()));
        mJsBeautifier = new JsBeautifier(this, "js/beautify.js");
    }

    public Observable<Integer> getLineCount() {
        return Observable.just(mCodeEditText.getLayout().getLineCount());
    }

    public void copyLine() {
        int line = LayoutHelper.getLineOfChar(mCodeEditText.getLayout(), mCodeEditText.getSelectionStart());
        if (line < 0 || line >= mCodeEditText.getLayout().getLineCount())
            return;
        CharSequence lineText = mCodeEditText.getText().subSequence(mCodeEditText.getLayout().getLineStart(line), mCodeEditText.getLayout().getLineEnd(line));
        ClipboardUtil.setClip(getContext(), lineText);
        Snackbar.make(this, R.string.text_already_copy_to_clip, Snackbar.LENGTH_SHORT).show();
    }

    public void deleteLine() {
        int line = LayoutHelper.getLineOfChar(mCodeEditText.getLayout(), mCodeEditText.getSelectionStart());
        if (line < 0 || line >= mCodeEditText.getLayout().getLineCount())
            return;
        mCodeEditText.getText().replace(mCodeEditText.getLayout().getLineStart(line), mCodeEditText.getLayout().getLineEnd(line), "");
    }

    public void jumpToStart() {
        mCodeEditText.setSelection(0);
    }

    public void jumpToEnd() {
        mCodeEditText.setSelection(mCodeEditText.getText().length());
    }

    public void jumpToLineStart() {
        int line = LayoutHelper.getLineOfChar(mCodeEditText.getLayout(), mCodeEditText.getSelectionStart());
        if (line < 0 || line >= mCodeEditText.getLayout().getLineCount())
            return;
        mCodeEditText.setSelection(mCodeEditText.getLayout().getLineStart(line));
    }

    public void jumpToLineEnd() {
        int line = LayoutHelper.getLineOfChar(mCodeEditText.getLayout(), mCodeEditText.getSelectionStart());
        if (line < 0 || line >= mCodeEditText.getLayout().getLineCount())
            return;
        mCodeEditText.setSelection(mCodeEditText.getLayout().getLineEnd(line) - 1);
    }

    public void setTheme(Theme theme) {
        mTheme = theme;
        setBackgroundColor(mTheme.getBackgroundColor());
        mJavaScriptHighlighter.setTheme(theme);
        mJavaScriptHighlighter.updateTokens(mCodeEditText.getText().toString());
        mCodeEditText.setTheme(mTheme);
        invalidate();
    }

    public boolean isTextChanged() {
        return mTextViewRedoUndo.isTextChanged();
    }

    public boolean canUndo() {
        return mTextViewRedoUndo.canUndo();
    }

    public boolean canRedo() {
        return mTextViewRedoUndo.canRedo();
    }

    @Override
    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
        super.onScrollChanged(l, t, oldl, oldt);
        mCodeEditText.postInvalidate();
    }

    public CodeEditText getCodeEditText() {
        return mCodeEditText;
    }

    public void setInitialText(String text) {
        mCodeEditText.setText(text);
        mTextViewRedoUndo.setDefaultText(text);
    }

    public void jumpTo(int line, int col) {
        if (line >= mCodeEditText.getLayout().getLineCount() || line < 0) {
            return;
        }
        mCodeEditText.setSelection(mCodeEditText.getLayout().getLineStart(line) + col);
    }

    public void setReadOnly(boolean readOnly) {
        setEnabled(!readOnly);
    }

    public void setProgress(boolean progress) {
        if (progress) {
            if (mProcessDialog != null) {
                mProcessDialog.dismiss();
            }
            mProcessDialog = new MaterialDialog.Builder(getContext()).content(R.string.text_processing).progress(true, 0).cancelable(false).show();
        } else {
            if (mProcessDialog != null) {
                mProcessDialog.dismiss();
                mProcessDialog = null;
            }
        }
    }

    public void setText(String text) {
        mCodeEditText.setText(text);
    }

    public void setCursorChangeCallback(CursorChangeCallback callback) {
        mCodeEditText.setCursorChangeCallback(callback);
    }

    public void undo() {
        mTextViewRedoUndo.undo();
    }

    public void redo() {
        mTextViewRedoUndo.redo();
    }

    public void find(String keywords, boolean usingRegex) {
        if (usingRegex) {
            mMatcher = Pattern.compile(keywords).matcher(mCodeEditText.getText());
            mKeywords = null;
        } else {
            mKeywords = keywords;
            mMatcher = null;
        }
        findNext();
    }

    public void replace(String keywords, String replacement, boolean usingRegex) {
        mReplacement = replacement == null ? "" : replacement;
        find(keywords, usingRegex);
    }

    public void replaceAll(String keywords, String replacement, boolean usingRegex) {
        if (!usingRegex) {
            keywords = Pattern.quote(keywords);
        }
        String text = mCodeEditText.getText().toString();
        text = text.replaceAll(keywords, replacement);
        setText(text);
    }

    public void findNext() {
        int foundIndex;
        if (mMatcher == null) {
            if (mKeywords == null)
                return;
            foundIndex = TextUtils.indexOf(mCodeEditText.getText(), mKeywords, mFoundIndex + 1);
            if (foundIndex >= 0)
                mCodeEditText.setSelection(foundIndex, foundIndex + mKeywords.length());
        } else if (mMatcher.find(mFoundIndex + 1)) {
            foundIndex = mMatcher.start();
            mCodeEditText.setSelection(foundIndex, foundIndex + mMatcher.group().length());
        } else {
            foundIndex = -1;
        }
        if (foundIndex < 0 && mFoundIndex >= 0) {
            mFoundIndex = -1;
            findNext();
        } else {
            mFoundIndex = foundIndex;
        }
    }

    public void findPrev() {
        if (mMatcher != null) {
            Toast.makeText(getContext(), R.string.error_regex_find_prev, Toast.LENGTH_SHORT).show();
            return;
        }
        int len = mCodeEditText.getText().length();
        if (mFoundIndex <= 0) {
            mFoundIndex = len;
        }
        int index = mCodeEditText.getText().toString().lastIndexOf(mKeywords, mFoundIndex - 1);
        if (index < 0) {
            if (mFoundIndex != len) {
                mFoundIndex = len;
                findPrev();
            }
            return;
        }
        mFoundIndex = index;
        mCodeEditText.setSelection(index, index + mKeywords.length());
    }

    public void replaceSelection() {
        mCodeEditText.getText().replace(mCodeEditText.getSelectionStart(), mCodeEditText.getSelectionEnd(), mReplacement);
    }

    public void beautifyCode() {
        setProgress(true);
        mJsBeautifier.beautify(mCodeEditText.getText().toString(), new JsBeautifier.Callback() {

            @Override
            public void onSuccess(String beautifiedCode) {
                setProgress(false);
                mCodeEditText.setText(beautifiedCode);
            }

            @Override
            public void onException(Exception e) {
                setProgress(false);
                e.printStackTrace();
            }
        });
    }

    public void insert(String insertText) {
        int selection = Math.max(mCodeEditText.getSelectionStart(), 0);
        mCodeEditText.getText().insert(selection, insertText);
    }

    public void moveCursor(int dCh) {
        mCodeEditText.setSelection(mCodeEditText.getSelectionStart() + dCh);
    }

    public String getText() {
        return mCodeEditText.getText().toString();
    }

    public Observable<String> getSelection() {
        int s = mCodeEditText.getSelectionStart();
        int e = mCodeEditText.getSelectionEnd();
        if (s == e) {
            return Observable.just("");
        }
        return Observable.just(mCodeEditText.getText().toString().substring(s, e));
    }

    public void markTextreplacedaved() {
        mTextViewRedoUndo.markTextAsUnchanged();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        int codeWidth = getWidth() - getPaddingLeft() - getPaddingRight();
        int codeHeight = getHeight() - getPaddingTop() - getPaddingBottom();
        if (mCodeEditText.getMinWidth() != codeWidth || mCodeEditText.getMinWidth() != codeWidth) {
            mCodeEditText.setMinWidth(codeWidth);
            mCodeEditText.setMinHeight(codeHeight);
            invalidate();
        }
        super.onDraw(canvas);
    }
}

18 Source : ScriptOperations.java
with Mozilla Public License 2.0
from newPersonKing

public Observable<ScriptFile> download(String url, String path, MaterialDialog progressDialog) {
    PublishSubject<ScriptFile> subject = PublishSubject.create();
    DownloadManager.getInstance().download(url, path).observeOn(AndroidSchedulers.mainThread()).doOnNext(progressDialog::setProgress).subscribe(new SimpleObserver<Integer>() {

        @Override
        public void onComplete() {
            progressDialog.dismiss();
            subject.onNext(new ScriptFile(path));
            subject.onComplete();
        }

        @Override
        public void onError(Throwable error) {
            Log.e(LOG_TAG, "Download failed", error);
            progressDialog.dismiss();
            showMessage(R.string.text_download_failed);
            subject.onError(error);
        }
    });
    return subject;
}

See More Examples