如何将导航抽屉放在操作栏顶部?

时间:2019-04-03 20:31:56

标签: android

我有一个以前写过的程序。它没有导航抽屉,我已使用本教程添加了它:enter link description here

它可以正常工作,但是导航栏顶部隐藏在操作栏下方。 这是我的布局代码的一部分:

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/drawer_layout"
    android:theme="@style/AppTheme.NoActionBar"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true">

    <FrameLayout
        android:id="@+id/content_frame"
        android:layout_width="match_parent"
        android:layout_height="match_parent" >

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            android:theme="@style/ThemeOverlay.AppCompat.ActionBar" />

        <android.support.v4.widget.SwipeRefreshLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/refreshLayout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fitsSystemWindows="true"

        tools:openDrawer="start">

这是我的onCreate代码:

setTheme(R.style.AppTheme);
super.onCreate(savedInstanceState);

setContentView(R.layout.activity_control_panel);
drawerLayout = findViewById(R.id.drawer_layout);
ActionBar actionbar = getSupportActionBar();
actionbar.setDisplayHomeAsUpEnabled(true);
actionbar.setHomeAsUpIndicator(R.drawable.ic_cash_100);
getSupportActionBar().setTitle(R.string.app_name);

我的样式文件如下:

<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/pink</item>
</style>

<style name="transparentActivity" parent="Theme.AppCompat.NoActionBar">

    <item name="android:windowContentOverlay">@null</item>

    <item name="windowActionBarOverlay">true</item>
    <item name="colorPrimary">@android:color/transparent</item>

    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/blue</item>

    <item name="android:windowNoTitle">true</item>
    <item name="android:windowBackground">@android:color/transparent</item>
    <item name="android:colorBackgroundCacheHint">@null</item>
    <item name="android:windowIsTranslucent">true</item>
    <item name="android:windowAnimationStyle">@android:style/Animation</item>


</style>

<style name="LinearProgress">
    <item name="lpd_maxLineWidth">75%</item>
    <item name="lpd_minLineWidth">10%</item>
    <item name="lpd_strokeSize">25dp</item>
    <item name="lpd_strokeColor">#bfbfbf</item>
    <item name="lpd_strokeSecondaryColor">@android:color/background_light</item>
    <item name="lpd_reverse">false</item>
    <item name="lpd_travelDuration">1000</item>
    <item name="lpd_transformDuration">600</item>
    <item name="lpd_keepDuration">200</item>
    <item name="lpd_transformInterpolator">@android:anim/decelerate_interpolator</item>
    <item name="pv_progressMode">determinate</item>
    <item name="lpd_inAnimDuration">@android:integer/config_mediumAnimTime</item>
    <item name="lpd_outAnimDuration">@android:integer/config_mediumAnimTime</item>
    <item name="lpd_verticalAlign">bottom</item>
</style>

<style name="AppTheme.NoActionBar">
    <item name="windowActionBar">false</item>
    <item name="windowNoTitle">true</item>
</style>


    <style name="SplashTheme" parent="AppTheme">
        <item name="android:windowBackground">@drawable/splash</item>

    </style>


<style name="AppTheme.AppBarOverlay" parent="ThemeOverlay.AppCompat.Dark.ActionBar" />

<style name="AppTheme.PopupOverlay" parent="ThemeOverlay.AppCompat.Light" />

最后应该注意,我的所有活动都是从baseActivity类扩展的:

public class BaseActivity extends AppCompatActivity {

    protected Toolbar toolbar = null;
    private boolean usesDefaultWrap = false;
    private ViewGroup contentContainer = null;
    private ProgressDialog pleaseWaitProgressDialog = null;
    private String lastUserAuthToken = "";
    private String lastUserJson = "";
    private boolean isAuthBroadcastReceiverRegistered = false;
    private boolean onResumeCalledAfterOnCreate = true;

    /**
     * Prevents redundant authentication requests while an authentication action is in progress.
     */
    private boolean userIsAuthenticating = false;

    /**
     * Keeps all controllers that started on this baseActivity.
     */
    private CopyOnWriteArrayList<BaseController> controllers = new CopyOnWriteArrayList<>();

// ____________________________________________________________________

    public void registerController(BaseController controller) {

        controllers.add(controller);
    }

// ____________________________________________________________________

    public void unregisterController(BaseController controller) {

        controllers.remove(controller);
    }

// ____________________________________________________________________

    public void cancelAllControllers() {

        for (BaseController controller : controllers) {

            controller.cancel();
        }

        controllers.clear();
    }

// ____________________________________________________________________

    public void notifyControllersForAuthenticationStatus(BaseController.AuthStatus authStatus) {

        for (BaseController controller : controllers) {

            if (authStatus == BaseController.AuthStatus.logged_in)
                controller.onLogin();
            else if (authStatus == BaseController.AuthStatus.logged_out)
                controller.onLogout();
            else if (authStatus == BaseController.AuthStatus.authenticationCanceled)
                controller.onAuthenticationCanceled();
        }
    }

// ____________________________________________________________________

    protected void onLoggedIn() {
    }

    protected void onLoggedOut() {
    }

    protected void onAuthenticationCanceled() {
    }

    protected void onUserInfoChanged() {
    }

// ____________________________________________________________________

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == C.ActivityCodes.AuthenticationActivity) {

            userIsAuthenticating = false;

            if (resultCode == Activity.RESULT_CANCELED) {

                onAuthenticationCanceled();
                notifyControllersForAuthenticationStatus(BaseController.AuthStatus.authenticationCanceled);
            }
        }
    }

// ____________________________________________________________________

    @Override
    protected void onPause() {

        unregisterAuthBroadcastReceiver();
        super.onPause();
    }

// ____________________________________________________________________

    @Override
    protected void onResume() {
        super.onResume();

        checkAndNotifyUserStatus();
        registerBroadcastReceiver();


        onResumeCalledAfterOnCreate = false;
    }

// ____________________________________________________________________

    @Override
    public void finish() {

        cancelAllControllers();
        super.finish();
    }


// ____________________________________________________________________

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        captureCurrentUserStatus();
        onResumeCalledAfterOnCreate = true;
    }

// ____________________________________________________________________

    private void captureCurrentUserStatus() {

        lastUserAuthToken = SettingsManager.getCurrentToken();
        if (lastUserAuthToken == null)
            lastUserAuthToken = "";

        User currentUser = SettingsManager.getCurrentUser();
        if (currentUser != null)
            lastUserJson = currentUser.toJson().toString();
        else
            lastUserJson = "";
    }

// ____________________________________________________________________

    /**
     * Checks if user's model content is changed since last session this activity was on top.
     * If the user's content is changed, this method will invoke {@link #onUserInfoChanged()}
     * method.
     */
    private void checkAndNotifyUserStatus() {

        String currentAuthToken = SettingsManager.getCurrentToken();
        if (currentAuthToken == null)
            currentAuthToken = "";

        if (!lastUserAuthToken.equals(currentAuthToken)) {

            if (currentAuthToken.length() > 1) {

                onLoggedIn();
                notifyControllersForAuthenticationStatus(BaseController.AuthStatus.logged_in);
            } else {

                onLoggedOut();
                notifyControllersForAuthenticationStatus(BaseController.AuthStatus.logged_out);
            }
        } else {

            User currentUser = SettingsManager.getCurrentUser();
            if (currentUser != null && !lastUserJson.equals(currentUser.toJson())) {

                onUserInfoChanged();
            }
        }

        captureCurrentUserStatus();
    }

// ____________________________________________________________________

    private void registerBroadcastReceiver() {

        if (isAuthBroadcastReceiverRegistered)
            return;
        isAuthBroadcastReceiverRegistered = true;

        try {

            IntentFilter filters = new IntentFilter(UserRegistrationController.ACTION_LOGIN);
            filters.addAction(UserLogoutController.ACTION_LOGOUT);

            registerReceiver(authBroadcastReceiver, filters);
        } catch (Exception e) {

            isAuthBroadcastReceiverRegistered = false;
            Log.e("Brodcast registration", this.toString());
            e.printStackTrace();
        }

    }

// ____________________________________________________________________

    private void unregisterAuthBroadcastReceiver() {

        if (!isAuthBroadcastReceiverRegistered)
            return;

        try {

            unregisterReceiver(authBroadcastReceiver);
            isAuthBroadcastReceiverRegistered = false;
        } catch (Exception e) {

            e.printStackTrace();
        }
    }


// ____________________________________________________________________

    public void requestUserAuthentication(boolean needsToAskUser) {

        Logger.debugLog("Authentication", "userIsAuthenticating: " + userIsAuthenticating);

        if (userIsAuthenticating)
            return;

        Logger.debugLog("Authentication", "STARTED");

        userIsAuthenticating = true;


        Set<Class> classes = Reflection.getClassesAnnotatedWith(this, ir.afe.spotbaselib.Annotations.AuthenticationActivity.class, "ir.afe", 1);

        if (classes == null || classes.size() == 0) {
            Logger.debugLog("Authentication Request", "No class annotated with @AuthenticationActivity is found.");
            userIsAuthenticating = false;
            return;
        }

        Class foundClass = (Class) classes.toArray()[0];
        if (!Reflection.isClassOfType(foundClass, AuthenticationActivity.class)) {

            Logger.debugLog("Authentication Request", "The authentication annotated class must be type of " + AuthenticationActivity.class.getName());
            userIsAuthenticating = false;
            return;
        }

        //Starts authentication activity

        new Handler(Looper.getMainLooper()).post(new Runnable() {
            @Override
            public void run() {

                AuthenticationActivity authenticationActivity = null;
                try {
                    authenticationActivity = (AuthenticationActivity) foundClass.newInstance();
                } catch (Exception e) {

                    e.printStackTrace();
                    Logger.debugLog("Authentication Request", "Couldn't make instance of " + foundClass.getName());
                    userIsAuthenticating = false;
                    return;
                }


                authenticationActivity.onAutomatedAuthenticationRequest(BaseActivity.this, needsToAskUser, new DialogInterface.OnCancelListener() {
                    @Override
                    public void onCancel(DialogInterface dialogInterface) {

                        userIsAuthenticating = false;
                        notifyControllersForAuthenticationStatus(BaseController.AuthStatus.authenticationCanceled);
                    }
                });
            }
        });


    }

// ____________________________________________________________________

    /**
     * @param viewId The id of toolbar view in the activity's hierarchy
     * @see #initActionbar(Toolbar)
     */
    protected void initActionbar(@IdRes int viewId) {

        View toolbar = findViewById(viewId);
        if (toolbar != null && toolbar instanceof Toolbar) {

            initActionbar(((Toolbar) toolbar));
        }
    }

// ____________________________________________________________________

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        super.onOptionsItemSelected(item);

        if (item.getItemId() == android.R.id.home) {

            finish();
            return true;
        }
        return false;
    }


// ____________________________________________________________________

    /**
     * Initializes the actionbar using the given toolbar.
     *
     * @param toolbar The toolbar view to initialize the support actionbar with.
     */
    protected void initActionbar(Toolbar toolbar) {

        if (toolbar != null) {

            this.toolbar = toolbar;
            setSupportActionBar(toolbar);

            new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
                @Override
                public void run() {

                    TextView title = (TextView) findTitle(BaseActivity.this.toolbar);

                    if (title != null)
                        title.setTypeface(Typeface.createFromAsset(getAssets(), "Fonts/Regular.ttf"));
                }
            }, 200);

        }
    }

// ____________________________________________________________________

    private View findTitle(ViewGroup container) {

        View txt_title = null;

        for (int i = 0; i < container.getChildCount(); i++) {

            View child = container.getChildAt(i);

            if (child instanceof TextView) {

                txt_title = child;
                break;
            } else if (child instanceof ViewGroup) {

                txt_title = findTitle((ViewGroup) child);
                if (txt_title != null) {

                    break;
                }
            }
        }

        return txt_title;
    }

    // ____________________________________________________________________
    protected void makeRtl() {

        Configuration configuration = getResources().getConfiguration();
        configuration.setLayoutDirection(new Locale("fa"));
        getResources().updateConfiguration(configuration, getResources().getDisplayMetrics());
    }

//_________________________________________________________________________

    protected void makePersian() {

        LocaleHelper.setLocale(this, "fa");
        makeRtl();
    }

    // ____________________________________________________________________
    protected ViewGroup getContentContainer() {

        if (contentContainer != null)
            return contentContainer;
        else {

            return (ViewGroup) getWindow().getDecorView();
        }
    }
// ____________________________________________________________________

    protected void hideKeyboard() {

        try {

            InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);

        } catch (Exception e) {

            e.printStackTrace();
        }
    }

// ____________________________________________________________________

    @Override
    protected void attachBaseContext(Context newBase) {
        super.attachBaseContext(CalligraphyContextWrapper.wrap(newBase));
    }

// ____________________________________________________________________

    //region Dialogs and snackbars
    protected void showPleaseWaitProgressDialog(final DialogInterface.OnClickListener onCancelClicked) {


        runOnUiThread(new Runnable() {
            @Override
            public void run() {

                if (isDestroyed() || isFinishing())
                    return;
                if (pleaseWaitProgressDialog != null)
                    pleaseWaitProgressDialog.dismiss();

                ProgressDialog progressDialog = new ProgressDialog(BaseActivity.this);
                progressDialog.setMessage(getString(R.string.JustAMoment));
                progressDialog.setCancelable(false);

                if (onCancelClicked != null) {

                    progressDialog.setButton(ProgressDialog.BUTTON_NEGATIVE, getString(R.string.Cancel), onCancelClicked);
                }

                progressDialog.show();

                pleaseWaitProgressDialog = progressDialog;
            }
        });
    }

// ____________________________________________________________________

    protected void dismissPleaseWaitProgressDialog() {

        runOnUiThread(new Runnable() {
            @Override
            public void run() {

                if (isDestroyed() || isFinishing())
                    return;

                if (pleaseWaitProgressDialog != null)
                    pleaseWaitProgressDialog.dismiss();
                pleaseWaitProgressDialog = null;
            }
        });
    }

// ____________________________________________________________________

    protected void showSnack(String message, boolean longDuration) {

        showSnack(message, null, null, longDuration);
    }

// ____________________________________________________________________

    protected void showRetrySnack(String message, boolean longDuration, OnSnackActionClicked onRetryClicked) {

        showSnack(message, getString(R.string.Retry), onRetryClicked, longDuration);
    }

// ____________________________________________________________________

    protected void showSnack(final String message, final String action, final OnSnackActionClicked onSnackActionClicked, final boolean longDuration) {

        runOnUiThread(new Runnable() {
            @Override
            public void run() {

                Snackbar snackbar = Snackbar.make(getContentContainer(),
                        message, longDuration ? Snackbar.LENGTH_LONG : Snackbar.LENGTH_SHORT);

                if (onSnackActionClicked != null) {
                    snackbar.setAction(action, new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {

                            onSnackActionClicked.onClick();
                        }
                    });
                }
                snackbar.show();
            }
        });
    }

// ____________________________________________________________________

    protected interface OnSnackActionClicked {

        void onClick();
    }

    //endregion

// ____________________________________________________________________

    private BroadcastReceiver authBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {

            if (intent.getAction() == UserRegistrationController.ACTION_LOGIN || intent.getAction() == UserLogoutController.ACTION_LOGOUT) {

                checkAndNotifyUserStatus();
            }
        }
    };
// ____________________________________________________________________
}

0 个答案:

没有答案