React-Native 自定义Android原生组件--弹出提示框

特别说明:本文仅适合未接触过或不熟悉Android原生开发的React-Native新手开发者!

背景:使用React-Native开发Android APP时,虽然React-Native已经自带弹出提示框组件Alert,但由于各大手机厂商系统风格各异,在使用React-Native自带的弹出提示组件时也风格不一,并且大部分机型的弹出框样式比较难看,或者和APP的整体风格设计不协调,当然也可以使用Modal来实现弹出框,但是又得在所有需要的View添加Modal相应标签,较为繁琐,所以本文介绍一个简单的自定义弹出框的基本步骤。

效果预览:
android-confirm.jpg

一、设计布局文件

弹出框多为提示框(alert),确认框(confirm)本实例展示一个简单的确认框(即包含“确认”和“取消”按钮)。具体的文字,颜色,背景色等按需修改为和UI设计风格较为统一的即可(可在Android Studio 中可视化设计)!

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:background="#fff"
    android:paddingBottom="15dp">
    <TextView
        android:id="@+id/title"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#fff"
        android:gravity="center"
        android:padding="5dp"
        android:text="温馨提示"
        android:textSize="16sp"
        android:textColor="#f18518" />
    <View
        android:layout_width="match_parent"
        android:layout_height="0.5dp"
        android:background="#f18518">
    </View>
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceSmall"
        android:text="您的提示信息,后期从js端传入!"
        android:id="@+id/text_msg"
        android:textSize="15sp"
        android:textColor="#000"
        android:layout_gravity="center_horizontal"
        android:layout_marginLeft="25dp"
        android:layout_marginTop="12dp"
        android:layout_marginRight="25dp"
        android:layout_marginBottom="15dp" />
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="30dp"
        android:orientation="horizontal">
        <Button
            android:id="@+id/btn_cancel"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:background="#FDEEDF"
            android:text="取消"
            android:textColor="#f08519"
            android:topRightRadius="20dp"
            android:textSize="15sp"
            android:layout_marginLeft="25dp"
            android:layout_marginRight="5dp" />
        <View
            android:layout_width="10dp"
            android:layout_height="match_parent"
            android:background="#fff">
        </View>
        <Button
            android:id="@+id/btn_comfirm"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:background="#f08519"
            android:textColor="#fff"
            android:text="确定"
            android:textSize="15sp"
            android:layout_marginLeft="5dp"
            android:layout_marginRight="25dp" />
    </LinearLayout>
</LinearLayout>

二、添加Moudle类

该类为已设计的弹出框提供提供React-Native调用入口。

package com.xxx.xxx;//您的包名
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.TextView;
import com.facebook.react.bridge.Callback;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.modules.core.DeviceEventManagerModule;

public class xxxModule extends ReactContextBaseJavaModule {
    private AlertDialog dialog=null;
    private static ReactApplicationContext mRAC;
    public  xxxModule(ReactApplicationContext reactContext) {
        super(reactContext);
        mRAC=reactContext;
    }

    @Override
    public String getName() {
        return "xxxModule";
    }

    @Override
    public boolean canOverrideExistingModule() {
        return true;
    }

    //弹出确认取消按钮框
    @ReactMethod
    public void openConfirm(String message,String title, final Callback okBtnBack,final Callback cancelBack) {
        if (message == null || message.equals("")) return;
        Activity activity=getCurrentActivity();
        AlertDialog.Builder builder = new AlertDialog.Builder(activity);
        View view = View.inflate(activity, R.layout.my_dialog, null);
        builder.setView(view);
        builder.setCancelable(true);
        if (title != null && !title.equals("")) {
            TextView tit= (TextView) view.findViewById(R.id.title);//设置标题
            tit.setText(title);
        }
        TextView input_edt= (TextView) view.findViewById(R.id.text_msg);//显示内容
        input_edt.setText(message);
        //取消按钮点击事件
        Button btn_cancel=(Button)view.findViewById(R.id.btn_cancel);//取消按钮
        btn_cancel.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                if(dialog!=null) dialog.dismiss();
                if(cancelBack!=null ) cancelBack.invoke();
            }
        });
        //确定按钮点击事件
        Button btn_comfirm=(Button)view.findViewById(R.id.btn_comfirm);//确定按钮
        btn_comfirm.setOnClickListener(
                new View.OnClickListener(){
                    @Override
                    public void onClick(View v) {
                        if(dialog!=null) dialog.dismiss();
                        if(okBtnBack!=null ) okBtnBack.invoke();
                    }
                }
        );
        dialog = builder.create();
        dialog.setCancelable(false);
        dialog.show();
        //设置弹出框宽度
        Window dialogWindow = dialog.getWindow();
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        WindowManager m =activity.getWindowManager();
        DisplayMetrics metrics = new DisplayMetrics();
        m.getDefaultDisplay().getMetrics(metrics);
        lp.width = (int) (metrics.widthPixels * 0.8);//宽度
        //lp.height = (int) (metrics.heightPixels * 0.8);//高度
        dialogWindow.setAttributes(lp);
    }

    //关闭确认取消按钮框
    @ReactMethod
    public void  closeConfirm(){
        if(dialog!=null) dialog.dismiss();
    }
}

三、通过Package类注册Moudle方法

如果没有则创建xxxPackage类

Package可用于管理所有的原生模块的注册。

package com.xxxxx.xxxx;//您的包名
import com.facebook.react.ReactPackage;
import com.facebook.react.bridge.JavaScriptModule;
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.uimanager.ViewManager;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

class  xxxPackage implements ReactPackage {

    @Override
    public List<Class<? extends JavaScriptModule>> createJSModules() {
        return Collections.emptyList();
    }

    @Override
    public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {
        return Collections.emptyList();
    }

    @Override
    public List<NativeModule> createNativeModules(
            ReactApplicationContext reactContext) {
        List<NativeModule> modules = new ArrayList<>();
        ...//其他Module
        modules.add(new xxxModule(reactContext));//您的Moudle
        return modules;
    }
}

四、在MainApplication中注册

 protected List<ReactPackage> getPackages() {
      return Arrays.<ReactPackage>asList(
            ...,//其他包
            new xxxPackage() //您在第三步中创建或使用的Package类
      );
    }

五、前端(React-Native)调用

 var xxxModule = NativeModules.xxxModule;//xxxModule为第二步中的Moudle类中的getName方法的返回值

 xxxModule .openConfirm("提示信息","标题",()=>{
    //“确认”按钮点击回调方法
  },()=>{
   //“取消”按钮点击回调方法
 });

个人博客:有恒则成

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,390评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,821评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,632评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,170评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,033评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,098评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,511评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,204评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,479评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,572评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,341评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,213评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,576评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,893评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,171评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,486评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,676评论 2 335

推荐阅读更多精彩内容