淺談BaseActivity寫法,促使我們更高效開發(fā)

抓住人生中的一分一秒,勝過(guò)虛度中的一月一年!

前言

在Android開發(fā)中,activity再常用不過(guò)了,為了高效開發(fā),我們會(huì)將一些常用的功能和頁(yè)面統(tǒng)一實(shí)現(xiàn)的效果放在基類,這樣就不用寫每個(gè)頁(yè)面時(shí)再重新實(shí)現(xiàn)這些功能,下面是我總結(jié)了些內(nèi)容與大家共享一下,有不足的地方希望大家提出我將進(jìn)行再次完善。

實(shí)現(xiàn)目標(biāo)

1、屏幕橫豎屏切換,AndroidManifest中將不用再寫android:screenOrientation="portrait"
2、ButterKnife綁定頁(yè)面
3、沉浸式實(shí)現(xiàn)
4、攜帶數(shù)據(jù)的頁(yè)面跳轉(zhuǎn)
5、應(yīng)用被強(qiáng)殺檢測(cè)
6、標(biāo)題欄統(tǒng)一實(shí)現(xiàn)
7、仿IOS側(cè)滑finish頁(yè)面實(shí)現(xiàn)
8、Loading頁(yè)面統(tǒng)一實(shí)現(xiàn)(可替換成骨架圖)
9、點(diǎn)擊Edittext彈出軟鍵盤,點(diǎn)擊空白區(qū)域讓軟鍵盤消失
10、結(jié)合MVP模式下的BaseActivity


1、屏幕橫豎屏切換,AndroidManifest中將不用再寫android:screenOrientation="portrait"

我們經(jīng)常開發(fā)的app,一般情況下都是手機(jī)上的應(yīng)用,我想大家已經(jīng)設(shè)置了強(qiáng)制豎屏,因?yàn)闄M屏沒(méi)有特殊要求沒(méi)有必要去設(shè)置,設(shè)置了反而會(huì)出現(xiàn)更多問(wèn)題,其次說(shuō)一下8.0更新問(wèn)題,頁(yè)面同時(shí)設(shè)置了android:screenOrientation="portrait"和透明屬性,8.0運(yùn)行會(huì)出現(xiàn)Only fullscreen opaque activities can request orientation異常,大概意思為“只有不透明的全屏activity可以自主設(shè)置界面方向”,我們或許會(huì)引用一些第三方SDK到項(xiàng)目中,也許第三方會(huì)用到透明屬性,我們可能在AndroidManifest中會(huì)申明android:screenOrientation="portrait"后導(dǎo)致莫名其妙的奔潰(小概率事件,但不排除),所以建議在BaseActivity設(shè)置比較優(yōu)(當(dāng)你做側(cè)滑返回以后就不會(huì)覺(jué)得我說(shuō)這么啰嗦了)

 /**
     * 設(shè)置屏幕橫豎屏切換
     *
     * @param screenRoate true  豎屏     false  橫屏
     */
    private void setScreenRoate(Boolean screenRoate) {
        if (screenRoate) {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);//設(shè)置豎屏模式
        } else {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        }
    }

 @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setScreenRoate(true);
    }
2、ButterKnife綁定頁(yè)面

ButterKnife這個(gè)快速申明控件省了我們多少findViewById的時(shí)間,推薦使用,詳細(xì)寫一寫可能有人沒(méi)用過(guò)此控件
1、依賴

compile 'com.jakewharton:butterknife:8.8.1'
annotationProcessor 'com.jakewharton:butterknife-compiler:8.8.1'

2、onCreate綁定頁(yè)面 onDestroy取消綁定

  @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ButterKnife.bind(this);
    }
  @Override
    protected void onDestroy() {
        super.onDestroy();
        ButterKnife.bind(this).unbind();
    }
3、沉浸式實(shí)現(xiàn)

為了讓用戶感受更好的體驗(yàn)效果,所以我們會(huì)選擇設(shè)置沉浸式,每個(gè)頁(yè)面大多數(shù)都會(huì)設(shè)置一種效果,所以直接在BaseActivity設(shè)置即可

 /**
     * 沉浸式實(shí)現(xiàn)
     */
    protected void setStatusBar() {
        StatusBarUtil.setColor(this, getResources().getColor(R.color.colorWhite), 0);
//        StatusBarUtil.setTranslucentForImageViewInFragment(this, 0, null);
    }
   @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setStatusBar();
    }

問(wèn):如果有頁(yè)面不想設(shè)置此效果
答:在對(duì)應(yīng)Activity重寫setStatusBar(),做自定義操作

4、攜帶數(shù)據(jù)的頁(yè)面跳轉(zhuǎn)

跳轉(zhuǎn)頁(yè)面 startActivity(new Intent(this, MainActivity.class));不改裝這已經(jīng)是最簡(jiǎn)潔了,你要記住,程序員是比較懶的,能少寫就少寫

 /**
     * [頁(yè)面跳轉(zhuǎn)]
     *
     * @param clz
     */
    public void startActivity(Class<?> clz) {
        startActivity(clz, null);
    }
    /**
     * [攜帶數(shù)據(jù)的頁(yè)面跳轉(zhuǎn)]
     *
     * @param clz
     * @param bundle
     */
    public void startActivity(Class<?> clz, Bundle bundle) {
        Intent intent = new Intent();
        intent.setClass(this, clz);
        if (bundle != null) {
            intent.putExtras(bundle);
        }
        startActivity(intent);
    }

    /**
     * [含有Bundle通過(guò)Class打開編輯界面]
     *
     * @param cls
     * @param bundle
     * @param requestCode
     */
    public void startActivityForResult(Class<?> cls, Bundle bundle, int requestCode) {
        Intent intent = new Intent();
        intent.setClass(this, cls);
        if (bundle != null) {
            intent.putExtras(bundle);
        }
        startActivityForResult(intent, requestCode);
    }

跳轉(zhuǎn)頁(yè)面startActivity(MainActivity.class);嗯。。。少寫了幾個(gè)字母

5、應(yīng)用被強(qiáng)殺檢測(cè)

手機(jī)開了N多個(gè)應(yīng)用,可能導(dǎo)致內(nèi)存不足,所以GC就出來(lái)工作了,也許你的App就是被殺的對(duì)象(保活處理移步其他文章),我們需要檢測(cè)到APP是否被殺
思路:
(1)APP被殺,可以跳轉(zhuǎn)到閃屏頁(yè),再跳轉(zhuǎn)到MainActivity,但可能MainActivity還存在,我想讓MainActivity徹底消失,所以我的思路是跳轉(zhuǎn)到MainActivity,將MainActivity finish再跳轉(zhuǎn)到閃屏頁(yè),再往其他頁(yè)面跳轉(zhuǎn)
(2)那怎么樣檢測(cè)APP是否被殺呢,我進(jìn)入到APP后將一個(gè)參數(shù)設(shè)置個(gè)值,如果APP被殺,也就是說(shuō)我們當(dāng)時(shí)設(shè)置的值已經(jīng)不存在了,當(dāng)我們檢測(cè)到這個(gè)值和我們當(dāng)時(shí)設(shè)置的值不匹配說(shuō)明APP被殺了
1、新建個(gè)常量類AppStatusConstant

/**
 * File descripition:   APP狀態(tài)跟蹤器常量碼
 *
 * @author lp
 * @date 2018/9/29
 */

public class AppStatusConstant {
    public static final int STATUS_FORCE_KILLED=-1; //應(yīng)用放在后臺(tái)被強(qiáng)殺了
    public static final int STATUS_NORMAL=2;  //APP正常態(tài)
    //intent到MainActivity 區(qū)分跳轉(zhuǎn)目的
    public static final String KEY_HOME_ACTION="key_home_action";//返回到主頁(yè)面
    public static final int ACTION_BACK_TO_HOME=6; //默認(rèn)值
    public static final int ACTION_RESTART_APP=9;//被強(qiáng)殺
}

2、新建個(gè)單例模式,用來(lái)保存值

/**
 * File descripition:
 *
 * @author lp
 * @date 2018/9/29
 */

public class AppStatusManager {
    public int appStatus= AppStatusConstant.STATUS_FORCE_KILLED;        //APP狀態(tài) 初始值為沒(méi)啟動(dòng) 不在前臺(tái)狀態(tài)

    public static AppStatusManager appStatusManager;

    private AppStatusManager() {

    }

    public static AppStatusManager getInstance() {
        if (appStatusManager == null) {
            appStatusManager = new AppStatusManager();
        }
        return appStatusManager;
    }

    public int getAppStatus() {
        return appStatus;
    }

    public void setAppStatus(int appStatus) {
        this.appStatus = appStatus;
    }
}

3、進(jìn)入到閃屏頁(yè)我便給appStatus賦值

/**
 * File descripition:   閃屏頁(yè)
 *
 * @author lp
 * @date 2018/10/16
 */

public class SplashActivity extends AppCompatActivity {
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        AppStatusManager.getInstance().setAppStatus(AppStatusConstant.STATUS_NORMAL); //進(jìn)入應(yīng)用初始化設(shè)置成未登錄狀態(tài)
        super.onCreate(savedInstanceState);
    }
}

4、在BaseActivity的onCreate中去檢測(cè)這個(gè)值是否是我們?cè)O(shè)置過(guò)的值

 private void initAppStatus() {
        switch (AppStatusManager.getInstance().getAppStatus()) {
            /**
             * 應(yīng)用被強(qiáng)殺
             */
            case AppStatusConstant.STATUS_FORCE_KILLED:
                //跳到主頁(yè),主頁(yè)lauchmode SINGLETASK
                protectApp();
                break;
        }
    }
 protected void protectApp() {
        Intent intent = new Intent(this, MainActivity.class);
        intent.putExtra(AppStatusConstant.KEY_HOME_ACTION, AppStatusConstant.ACTION_RESTART_APP);
        startActivity(intent);
    }
  @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initAppStatus();
    }

5、MainActivity中接收傳過(guò)來(lái)的信息,然后調(diào)整到閃屏頁(yè)

  @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        int action = intent.getIntExtra(AppStatusConstant.KEY_HOME_ACTION, AppStatusConstant.ACTION_BACK_TO_HOME);
        switch (action) {
            case AppStatusConstant.ACTION_RESTART_APP:
                protectApp();
                break;
        }
    }
 @Override
    protected void protectApp() {
        Toast.makeText(getApplicationContext(), "應(yīng)用被回收重新啟動(dòng)", Toast.LENGTH_LONG).show();
        startActivity(new Intent(this, SplashActivity.class));
        finish();
    }
6、標(biāo)題欄統(tǒng)一實(shí)現(xiàn)

每個(gè)頁(yè)面大多數(shù)都會(huì)有個(gè)標(biāo)題欄,實(shí)現(xiàn)方式我們都會(huì),下面我介紹另一種方式,我把標(biāo)題欄寫到BaseActivity布局中,這樣在對(duì)應(yīng)的Activity就不用一遍一遍的寫了,但是弊端是多了一層嵌套
思路:我們?cè)贐aseActivity申明一個(gè)布局,其子Activity的xml塞入到父布局的一個(gè)控件中,這樣就每個(gè)子Activity都會(huì)有統(tǒng)一的控件了(標(biāo)題欄)
1、首先新建個(gè)關(guān)于title的xml,app_title.xml(供參考)

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/rlt_base"
    android:layout_width="match_parent"
    android:layout_height="44dp"
    android:background="@color/colorWhite">
    <LinearLayout
        android:id="@+id/back"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:gravity="center_vertical"
        android:orientation="horizontal"
        android:paddingLeft="@dimen/padding_12"
        android:paddingRight="@dimen/padding_12">
        <TextView
            android:id="@+id/back_name"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginRight="@dimen/margin_8"
            android:drawableLeft="@mipmap/zuojiantou"
            android:drawablePadding="@dimen/padding_8"
            android:gravity="center"
            android:textColor="@color/colorBlack"
            android:visibility="visible" />
    </LinearLayout>
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_centerHorizontal="true"
        android:layout_marginLeft="80dp"
        android:layout_marginRight="80dp">
        <TextView
            android:id="@+id/tv_title"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_centerHorizontal="true"
            android:layout_centerInParent="true"
            android:ellipsize="end"
            android:gravity="center"
            android:lines="1"
            android:textColor="@color/colorBlack"
            android:textSize="@dimen/text_18" />
    </RelativeLayout>
    <TextView
        android:id="@+id/tv_right"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_alignParentRight="true"
        android:drawablePadding="@dimen/padding_6"
        android:ellipsize="end"
        android:gravity="center"
        android:lines="1"
        android:paddingLeft="14dp"
        android:paddingRight="14dp"
        android:textColor="@color/colorBlack"
        android:textSize="@dimen/text_16"
        android:visibility="visible" />
    <View
        style="@style/View_o_5"
        android:layout_alignParentBottom="true" />
</RelativeLayout>

2、創(chuàng)建父布局的xml,activity.xml

<?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="match_parent"
    android:orientation="vertical">
    <include layout="@layout/app_title" />
    <FrameLayout
        android:id="@+id/fl_content"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</LinearLayout>

3、都創(chuàng)建好了就該給BaseActivity設(shè)置布局了

public abstract class BaseActivityNall extends AppCompatActivity {
    public TextView mBackName;
    public LinearLayout mBack;
    public TextView mTvTitle;
    public TextView mTvRight;
    public RelativeLayout mRltBase;

    protected View rootView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        rootView = View.inflate(this, R.layout.activity_title, null);
        setContentView(getLayoutId());
        addContent();
        setContentView(rootView);
    }
    private void addContent() {
        mBackName = (TextView) rootView.findViewById(R.id.back_name);
        mBack = (LinearLayout) rootView.findViewById(R.id.back);
        mTvTitle = (TextView) rootView.findViewById(R.id.tv_title);
        mTvRight = (TextView) rootView.findViewById(R.id.tv_right);
        mRltBase = (RelativeLayout) rootView.findViewById(R.id.rlt_base);
        FrameLayout flContent = (FrameLayout) rootView.findViewById(R.id.fl_content);

        mTvTitle.setText(getContentTitle() == null ? "" : getContentTitle());
        mBack.setOnClickListener(v -> finish());//java8寫法,特此備注一下

        View content = View.inflate(this, getLayoutId(), null);
        if (content != null) {
            FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT,
                    FrameLayout.LayoutParams.MATCH_PARENT);
            flContent.addView(content, params);
            ButterKnife.bind(this, rootView);
        }
    }
    /**
     * 獲取布局ID
     *
     * @return
     */
    protected abstract int getLayoutId();
    /**
     * title賦值
     *
     * @return
     */
    protected abstract String getContentTitle();
}
7、仿IOS側(cè)滑finish頁(yè)面實(shí)現(xiàn)

實(shí)現(xiàn)側(cè)滑會(huì)有很多弊端,在此就不細(xì)講實(shí)現(xiàn)方式了,給大家演示一種,但是想完美實(shí)現(xiàn)還需進(jìn)一步完善,第三方庫(kù)實(shí)現(xiàn),方法在BaseActivity寫

implementation 'com.r0adkll:slidableactivity:2.0.6'

/**
     * 初始化滑動(dòng)返回
     */
    protected void initSlidable() {
        int isSlidable = SettingUtil.getInstance().getSlidable();
        if (isSlidable != Constants.SLIDABLE_DISABLE) {
            SlidrConfig config = new SlidrConfig.Builder()
                    .edge(isSlidable == Constants.SLIDABLE_EDGE)
                    .build();
            slidrInterface = Slidr.attach(this, config);
        }
    }
  @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initSlidable();
    }

// Base application theme. 
    <style name="MyAppTheme" parent="Theme.AppCompat.Light.NoActionBar">
        <!-- Customize your theme here. -->
       // <item name="android:windowAnimationStyle">@style/activityAnimation</item>

        <item name="android:windowIsTranslucent">true</item>
        <!--<item name="android:windowDisablePreview">true</item>-->
        <item name="android:windowBackground">@android:color/transparent</item>
    </style>

有很多類似的開源框架 暫舉四個(gè)
  1. SwipeBackLayout
  2. Slidr
  3. Snake
  4. and_swipeback
8、Loading頁(yè)面統(tǒng)一實(shí)現(xiàn)(可替換成骨架圖)

看了一個(gè)大神寫的一個(gè)框架,超級(jí)來(lái)感覺(jué)呀 spruce-android,在BaseActivity封裝簡(jiǎn)單的給大家演示下,具體封裝大家去實(shí)現(xiàn)

/**
 * File descripition: activity基類
 * <p>
 *
 * @author lp
 * @date 2018/5/16
 */
public abstract class BaseActivityNall extends AppCompatActivity implements BaseView {
    public TextView mBackName;
    public LinearLayout mBack;
    public TextView mTvTitle;
    public TextView mTvRight;
    public RelativeLayout mRltBase;

    public int mIndex = BaseContent.baseIndex;

    protected View rootView;
    protected LoadService mBaseLoadService;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        rootView = View.inflate(this, R.layout.activity_title, null);
        setContentView(getLayoutId());
        addContent();
        setContentView(rootView);

        this.initData();
        this.getData();

    }

    private void addContent() {
        mBackName = (TextView) rootView.findViewById(R.id.back_name);
        mBack = (LinearLayout) rootView.findViewById(R.id.back);
        mTvTitle = (TextView) rootView.findViewById(R.id.tv_title);
        mTvRight = (TextView) rootView.findViewById(R.id.tv_right);
        mRltBase = (RelativeLayout) rootView.findViewById(R.id.rlt_base);
        FrameLayout flContent = (FrameLayout) rootView.findViewById(R.id.fl_content);

        mTvTitle.setText(getContentTitle() == null ? "" : getContentTitle());
        mBack.setOnClickListener(v -> finish());//java8寫法,特此備注一下

        View content = View.inflate(this, getLayoutId(), null);
        if (content != null) {
            FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT,
                    FrameLayout.LayoutParams.MATCH_PARENT);
            flContent.addView(content, params);
            ButterKnife.bind(this, rootView);
            mBaseLoadService = LoadSir.getDefault().register(content, new Callback.OnReloadListener() {
                @Override
                public void onReload(View v) {
                    onNetReload(v);
                }
            });
        }
    }
    protected void onNetReload(View v) {
        mBaseLoadService.showCallback(LoadingCallback.class);
        mIndex = BaseContent.baseIndex;
        getData();
    }
    /**
     * 獲取布局ID
     *
     * @return
     */
    protected abstract int getLayoutId();
    /**
     * title賦值
     *
     * @return
     */
    protected abstract String getContentTitle();
    /**
     * 數(shù)據(jù)初始化操作
     */
    protected abstract void initData();
    /**
     * 請(qǐng)求數(shù)據(jù)
     */
    protected abstract void getData();
}
9、點(diǎn)擊Edittext彈出軟鍵盤,點(diǎn)擊空白區(qū)域讓軟鍵盤消失

在我們使用Edittext時(shí),軟鍵盤彈出了,寫完字之后,想讓它消失,不去處理想讓軟鍵盤消失需要點(diǎn)擊軟鍵盤中的消失按鈕,顯然不是很方便的方法,我們想點(diǎn)擊非Edittext任何地方都讓軟鍵盤(也可以點(diǎn)擊Edittext讓軟鍵盤消失),請(qǐng)往下看,有倆種實(shí)現(xiàn)方法
(1)、第一種實(shí)現(xiàn)方法,擴(kuò)展性差

@Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            if (isShouldHideKeyboard(v, ev)) {
                hideKeyboard(v.getWindowToken());
            }
        }
        return super.dispatchTouchEvent(ev);
    }

    /**
     * 根據(jù)EditText所在坐標(biāo)和用戶點(diǎn)擊的坐標(biāo)相對(duì)比,來(lái)判斷是否隱藏鍵盤,因?yàn)楫?dāng)用戶點(diǎn)擊EditText時(shí)則不能隱藏
     *
     * @param v
     * @param event
     * @return
     */
    private boolean isShouldHideKeyboard(View v, MotionEvent event) {
        if (v != null && (v instanceof EditText)) {
            int[] l = {0, 0};
            v.getLocationInWindow(l);
            int left = l[0],
                    top = l[1],
                    bottom = top + v.getHeight(),
                    right = left + v.getWidth();
            if (event.getX() > left && event.getX() < right
                    && event.getY() > top && event.getY() < bottom) {
                // 點(diǎn)擊EditText的事件,忽略它。
                return false;
            } else {
                return true;
            }
        }
        // 如果焦點(diǎn)不是EditText則忽略,這個(gè)發(fā)生在視圖剛繪制完,第一個(gè)焦點(diǎn)不在EditText上,和用戶用軌跡球選擇其他的焦點(diǎn)
        return false;
    }

    /**
     * 獲取InputMethodManager,隱藏軟鍵盤
     *
     * @param token
     */
    private void hideKeyboard(IBinder token) {
        if (token != null) {
            InputMethodManager im = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            im.hideSoftInputFromWindow(token, InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

(2)、第二種實(shí)現(xiàn)方法(推薦使用)


    /**
     * 以下是關(guān)于軟鍵盤的處理
     */

    /**
     * 清除editText的焦點(diǎn)
     *
     * @param v   焦點(diǎn)所在View
     * @param ids 輸入框
     */
    public void clearViewFocus(View v, int... ids) {
        if (null != v && null != ids && ids.length > 0) {
            for (int id : ids) {
                if (v.getId() == id) {
                    v.clearFocus();
                    break;
                }
            }
        }
    }

    /**
     * 隱藏鍵盤
     *
     * @param v   焦點(diǎn)所在View
     * @param ids 輸入框
     * @return true代表焦點(diǎn)在edit上
     */
    public boolean isFocusEditText(View v, int... ids) {
        if (v instanceof EditText) {
            EditText et = (EditText) v;
            for (int id : ids) {
                if (et.getId() == id) {
                    return true;
                }
            }
        }
        return false;
    }

    //是否觸摸在指定view上面,對(duì)某個(gè)控件過(guò)濾
    public boolean isTouchView(View[] views, MotionEvent ev) {
        if (views == null || views.length == 0) {
            return false;
        }
        int[] location = new int[2];
        for (View view : views) {
            view.getLocationOnScreen(location);
            int x = location[0];
            int y = location[1];
            if (ev.getX() > x && ev.getX() < (x + view.getWidth())
                    && ev.getY() > y && ev.getY() < (y + view.getHeight())) {
                return true;
            }
        }
        return false;
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            if (isTouchView(filterViewByIds(), ev)) {
                return super.dispatchTouchEvent(ev);
            }
            if (hideSoftByEditViewIds() == null || hideSoftByEditViewIds().length == 0) {
                return super.dispatchTouchEvent(ev);
            }
            View v = getCurrentFocus();
            if (isFocusEditText(v, hideSoftByEditViewIds())) {
                KeyBoardUtils.hideInputForce(this);
                clearViewFocus(v, hideSoftByEditViewIds());
            }
        }
        return super.dispatchTouchEvent(ev);
    }


    /**
     * 傳入EditText的Id
     * 沒(méi)有傳入的EditText不做處理
     *
     * @return id 數(shù)組
     */
    public int[] hideSoftByEditViewIds() {
        return null;
    }

    /**
     * 傳入要過(guò)濾的View
     * 過(guò)濾之后點(diǎn)擊將不會(huì)有隱藏軟鍵盤的操作
     *
     * @return id 數(shù)組
     */
    public View[] filterViewByIds() {
        return null;
    }

使用方法:在對(duì)應(yīng)的Activity重寫hideSoftByEditViewIds()和filterViewByIds(),傳入需要彈出的軟鍵盤的ID

 /*實(shí)現(xiàn)案例===============================================================================================*/

    @Override
    public int[] hideSoftByEditViewIds() {
        int[] ids = {R.id.et_company_name, R.id.et_address};
        return ids;
    }

    @Override
    public View[] filterViewByIds() {
        View[] views = {mEtCompanyName, mEtAddress};
        return views;
    }

10、結(jié)合MVP模式下的BaseActivity,傳送地址
/**
 * File descripition: activity基類
 * <p>
 *
 * @author lp
 * @date 2018/5/16
 */
public abstract class BaseActivity<P extends BasePresenter> extends AppCompatActivity implements BaseView {
    protected final String TAG = this.getClass().getSimpleName();
    public View mViewStatusBar;
    public TextView mBackName;
    public LinearLayout mBack;
    public TextView mTvTitle;
    public TextView mTvRight;
    public RelativeLayout mRltBase;

    public Activity mContext;
    protected P mPresenter;

    private LoadingDialog mLodingDialog;

    protected abstract P createPresenter();

    //錯(cuò)誤提示框  警告框  成功提示框
    private PromptDialog promptDialog;

    public int mIndex = BaseContent.baseIndex;

    protected View rootView;
    protected LoadService mBaseLoadService;

    /**
     * 是否顯示初始Loading
     */
    private Boolean isShow = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);//設(shè)置豎屏模式
        mContext = this;
        rootView = View.inflate(this, R.layout.activity_title, null);
        setContentView(getLayoutId());
        addContent();
        setContentView(rootView);
        mPresenter = createPresenter();
        AppManager.getAppManager().addActivity(this);
        setStatusBar();
        initAppStatus();
        ButterKnife.bind(this);

        this.initData();

    }

    private void initAppStatus() {
        switch (AppStatusManager.getInstance().getAppStatus()) {
            /**
             * 應(yīng)用被強(qiáng)殺
             */
            case AppStatusConstant.STATUS_FORCE_KILLED:
                //跳到主頁(yè),主頁(yè)lauchmode SINGLETASK
                protectApp();
                break;
        }
    }

    private void addContent() {
        mViewStatusBar = (View) rootView.findViewById(R.id.view_status_bar);
        mBackName = (TextView) rootView.findViewById(R.id.back_name);
        mBack = (LinearLayout) rootView.findViewById(R.id.back);
        mTvTitle = (TextView) rootView.findViewById(R.id.tv_title);
        mTvRight = (TextView) rootView.findViewById(R.id.tv_right);
        mRltBase = (RelativeLayout) rootView.findViewById(R.id.rlt_base);
        FrameLayout flContent = (FrameLayout) rootView.findViewById(R.id.fl_content);

        mTvTitle.setText(getContentTitle() == null ? "" : getContentTitle());
        mBack.setOnClickListener(v -> finish());

        View content = View.inflate(this, getLayoutId(), null);
        if (content != null) {
            FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT,
                    FrameLayout.LayoutParams.MATCH_PARENT);
            flContent.addView(content, params);
            ButterKnife.bind(this, rootView);
            mBaseLoadService = LoadSir.getDefault().register(content, new Callback.OnReloadListener() {
                @Override
                public void onReload(View v) {
                    showLoadingLayout();
                    mIndex = BaseContent.baseIndex;
                    getData();
                }
            });
            if (isShow) {
                showLoadingLayout();
            } else {
                PostUtil.postSuccessDelayed(mBaseLoadService, 0);
            }
        }
    }

    protected void protectApp() {
        Intent intent = new Intent(this, MainActivity.class);
        intent.putExtra(AppStatusConstant.KEY_HOME_ACTION, AppStatusConstant.ACTION_RESTART_APP);
        startActivity(intent);
    }

    private void showLoadingLayout() {
        mBaseLoadService.showCallback(LoadingCallback.class);
    }

    public void showLoadingLayout(boolean isShow) {
        this.isShow = isShow;
    }

    /**
     * 獲取布局ID
     *
     * @return
     */
    protected abstract int getLayoutId();

    /**
     * title賦值
     *
     * @return
     */

    protected abstract String getContentTitle();

    /**
     * 數(shù)據(jù)初始化操作
     */
    protected abstract void initData();

    /**
     * 請(qǐng)求數(shù)據(jù)
     */
    protected abstract void getData();

    /**
     * 沉浸式實(shí)現(xiàn)
     */
    protected void setStatusBar() {
        StatusBarUtil.setColor(this, getResources().getColor(R.color.colorWhite), 0);
//        StatusBarUtil.setTranslucentForImageViewInFragment(this, 0, null);
    }

    public void showToast(String str) {
        showToast(str, Toast.LENGTH_SHORT);
    }

    public void showLongToast(String str) {
        showToast(str, Toast.LENGTH_LONG);
    }

    /**
     * 封裝toast方法
     *
     * @param str
     * @param dur
     */
    void showToast(String str, int dur) {
        ToastUtils.showToastS(this, str, dur);
    }

    @Override
    public void showError(String msg) {
        showToast(msg);
    }

    @Override
    public void onErrorCode(BaseModel model) {
        if (model.getErrcode() == BaseObserver.NETWORK_ERROR) {//網(wǎng)絡(luò)連接失敗  無(wú)網(wǎng)
            PostUtil.postCallbackDelayed(mBaseLoadService, NetWorkErrorCallback.class);
        } else if (model.getErrcode() == BaseObserver.CONNECT_ERROR ||//連接錯(cuò)誤
                model.getErrcode() == BaseObserver.CONNECT_TIMEOUT ||//連接超時(shí)
                model.getErrcode() == BaseObserver.BAD_NETWORK ||//網(wǎng)絡(luò)超時(shí)
                model.getErrcode() == BaseObserver.CONNECT_NULL//數(shù)據(jù)為空,顯示異常
                ) {
            PostUtil.postCallbackDelayed(mBaseLoadService, ErrorCallback.class);
        } else if (model.getErrcode() == BaseObserver.CONNECT_NOT_LOGIN) {//沒(méi)有登錄,去登錄
            startLogin();
        }
    }

    private void startLogin() {
        AppUMS.mIsLogin = false;
        AppUMS.setToken("");
        startActivity(LoginActivity.class);
    }
    @Override
    public void showLoading() {
        showLoadingDialog();
    }
    @Override
    public void hideLoading() {
        closeLoadingDialog();
    }
    public void closeLoadingDialog() {
        if (mLodingDialog != null && mLodingDialog.isShowing()) {
            mLodingDialog.dismiss();
        }
    }
    /**
     * 加載...
     */
    public void showLoadingDialog() {
        if (mLodingDialog == null) {
            mLodingDialog = new LoadingDialog(this).setMessage(getString(R.string.app_loding));
        }
        mLodingDialog.show();
    }
    /**
     * 警告框
     */
    public void showInfoDialog(String msg) {
        if (promptDialog == null) {
            promptDialog = new PromptDialog(this);
        }
        promptDialog.showInfo(msg);
    }
    /**
     * 錯(cuò)誤提示框
     */
    public void showErrorDialog(String msg) {
        if (promptDialog == null) {
            promptDialog = new PromptDialog(this);
        }
        promptDialog.showError(msg);
    }
    /**
     * 成功提示框
     */
    public void showSuccessDialog(String msg) {
        if (promptDialog == null) {
            promptDialog = new PromptDialog(this);
        }
        promptDialog.showSuccess(msg);
    }
    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        ButterKnife.bind(this).unbind();
        AppManager.getAppManager().finishActivity(this);
        if (mPresenter != null) {
            mPresenter.detachView();
        }
    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (event.getKeyCode() == KeyEvent.KEYCODE_BACK
                && event.getAction() == KeyEvent.ACTION_DOWN) {
            finishActivity();
            return false;
        }
        return super.dispatchKeyEvent(event);
    }
    public void finishActivity() {
        finish();
    }
    /**
     * [頁(yè)面跳轉(zhuǎn)]
     *
     * @param clz
     */
    public void startActivity(Class<?> clz) {
        startActivity(clz, null);
    }
    /**
     * [攜帶數(shù)據(jù)的頁(yè)面跳轉(zhuǎn)]
     *
     * @param clz
     * @param bundle
     */
    public void startActivity(Class<?> clz, Bundle bundle) {
        Intent intent = new Intent();
        intent.setClass(this, clz);
        if (bundle != null) {
            intent.putExtras(bundle);
        }
        startActivity(intent);
    }
    /**
     * [含有Bundle通過(guò)Class打開編輯界面]
     *
     * @param cls
     * @param bundle
     * @param requestCode
     */
    public void startActivityForResult(Class<?> cls, Bundle bundle, int requestCode) {
        Intent intent = new Intent();
        intent.setClass(this, cls);
        if (bundle != null) {
            intent.putExtras(bundle);
        }
        startActivityForResult(intent, requestCode);
    }
    /**
     * 以下是關(guān)于軟鍵盤的處理
     */
    /**
     * 清除editText的焦點(diǎn)
     *
     * @param v   焦點(diǎn)所在View
     * @param ids 輸入框
     */
    public void clearViewFocus(View v, int... ids) {
        if (null != v && null != ids && ids.length > 0) {
            for (int id : ids) {
                if (v.getId() == id) {
                    v.clearFocus();
                    break;
                }
            }
        }
    }

    /**
     * 隱藏鍵盤
     *
     * @param v   焦點(diǎn)所在View
     * @param ids 輸入框
     * @return true代表焦點(diǎn)在edit上
     */
    public boolean isFocusEditText(View v, int... ids) {
        if (v instanceof EditText) {
            EditText et = (EditText) v;
            for (int id : ids) {
                if (et.getId() == id) {
                    return true;
                }
            }
        }
        return false;
    }
    //是否觸摸在指定view上面,對(duì)某個(gè)控件過(guò)濾
    public boolean isTouchView(View[] views, MotionEvent ev) {
        if (views == null || views.length == 0) {
            return false;
        }
        int[] location = new int[2];
        for (View view : views) {
            view.getLocationOnScreen(location);
            int x = location[0];
            int y = location[1];
            if (ev.getX() > x && ev.getX() < (x + view.getWidth())
                    && ev.getY() > y && ev.getY() < (y + view.getHeight())) {
                return true;
            }
        }
        return false;
    }
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            if (isTouchView(filterViewByIds(), ev)) {
                return super.dispatchTouchEvent(ev);
            }
            if (hideSoftByEditViewIds() == null || hideSoftByEditViewIds().length == 0) {
                return super.dispatchTouchEvent(ev);
            }
            View v = getCurrentFocus();
            if (isFocusEditText(v, hideSoftByEditViewIds())) {
                KeyBoardUtils.hideInputForce(this);
                clearViewFocus(v, hideSoftByEditViewIds());
            }
        }
        return super.dispatchTouchEvent(ev);
    }
    /**
     * 傳入EditText的Id
     * 沒(méi)有傳入的EditText不做處理
     *
     * @return id 數(shù)組
     */
    public int[] hideSoftByEditViewIds() {
        return null;
    }
    /**
     * 傳入要過(guò)濾的View
     * 過(guò)濾之后點(diǎn)擊將不會(huì)有隱藏軟鍵盤的操作
     *
     * @return id 數(shù)組
     */
    public View[] filterViewByIds() {
        return null;
    }
    /*實(shí)現(xiàn)案例===============================================================================================*/
    /*
    @Override
    public int[] hideSoftByEditViewIds() {
        int[] ids = {R.id.et_company_name, R.id.et_address};
        return ids;
    }
    @Override
    public View[] filterViewByIds() {
        View[] views = {mEtCompanyName, mEtAddress};
        return views;
    }
    */
}

最后,祝大家開發(fā)順利!

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容