当前位置: 首页 > 知识库问答 >
问题:

隐藏底部导航栏,而键盘是存在的-Android

卜鹏
2023-03-14

我有一个小的演示聊天UI应用程序。此应用程序有一个底部导航栏。我需要在键盘出现时隐藏底部导航栏。

下面是一个聊天UI的例子

当您单击EditText元素时,可以看到键盘出现,但底部导航栏仍然可见。我尝试过这种测量方法,但是UI元素像这样闪烁。

当键盘可见时,是否有适当的方法隐藏底部导航栏?

编辑:在下面的活动中,您可以看到当键盘被确定为可见时,我将键盘监听器设置为调整用户界面元素的位置。

这是我的活动代码,从上面的链接使用setKeyboardListener方法,并在onCreateView中设置它:

package uk.cal.codename.projectnedry.TeamChatFragment;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Rect;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Layout;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.roughike.bottombar.BottomBar;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import uk.cal.codename.projectnedry.R;
import uk.cal.codename.projectnedry.TeamChatFragment.ListAdapter.TeamChatListAdapter;
import uk.demo.cal.genericmodelviewpresenter.GenericMvp.GenericMvpFragment;

import static android.view.View.GONE;

/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link TeamChatView.OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link TeamChatView#newInstance} factory method to
 * create an instance of this fragment.
 */
public class TeamChatView extends GenericMvpFragment implements TeamChatContract.RequiredViewOps {

    private OnFragmentInteractionListener mListener;
    @BindView(R.id.teamChatList)
    RecyclerView mTeamChatRecyclerView;
    @BindView(R.id.teamChatSendButton)
    ImageButton mTeamChatSendButton;
    @BindView(R.id.messageTextInput)
    EditText mMessageTextInput;
    TeamChatListAdapter mTeamChatListAdapter;
    TeamChatListAdapter.ClickListener mTeamChatListClickListener;
    private ArrayList<String> mTestMessageList;

    public interface OnKeyboardVisibilityListener {
        void onVisibilityChanged(boolean visible);
    }

    public final void setKeyboardListener(final OnKeyboardVisibilityListener listener) {
        final View activityRootView = ((ViewGroup) getActivity().findViewById(android.R.id.content)).getChildAt(0);

        activityRootView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {

            private boolean wasOpened;

            private final int DefaultKeyboardDP = 100;

            // From @nathanielwolf answer...  Lollipop includes button bar in the root. Add height of button bar (48dp) to maxDiff
            private final int EstimatedKeyboardDP = DefaultKeyboardDP + (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP ? 48 : 0);

            private final Rect r = new Rect();

            @Override
            public void onGlobalLayout() {
                // Convert the dp to pixels.
                int estimatedKeyboardHeight = (int) TypedValue
                        .applyDimension(TypedValue.COMPLEX_UNIT_DIP, EstimatedKeyboardDP, activityRootView.getResources().getDisplayMetrics());

                // Conclude whether the keyboard is shown or not.
                activityRootView.getWindowVisibleDisplayFrame(r);
                int heightDiff = activityRootView.getRootView().getHeight() - (r.bottom - r.top);
                boolean isShown = heightDiff >= estimatedKeyboardHeight;

                if (isShown == wasOpened) {
                    Log.d("Keyboard state", "Ignoring global layout change...");
                    return;
                }

                wasOpened = isShown;
                listener.onVisibilityChanged(isShown);
            }
        });
    }

    public TeamChatView() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @return A new instance of fragment TeamChatView.
     */
    public static TeamChatView newInstance() {
        TeamChatView fragment = new TeamChatView();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    @SuppressLint("MissingSuperCall")
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(TeamChatPresenter.class, TeamChatModel.class, savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        final View view = inflater.inflate(R.layout.fragment_team_chat_view, container, false);
        this.mUnbinder = ButterKnife.bind(this, view);

        mTestMessageList = new ArrayList<>();
        this.mTeamChatListAdapter = new TeamChatListAdapter(mTestMessageList);
        this.mTeamChatRecyclerView.setAdapter(this.mTeamChatListAdapter);
        final LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
        this.mTeamChatRecyclerView.setLayoutManager(linearLayoutManager);

        this.mTeamChatSendButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(!String.valueOf(mMessageTextInput.getText()).equals("")) {
                    getSpecificImpOfGenericPresenter().sendMessage(String.valueOf(mMessageTextInput.getText()));
                    mMessageTextInput.setText("");
                    mTeamChatRecyclerView.smoothScrollToPosition(mTestMessageList.size());
                }
            }
        });

        setKeyboardListener(new OnKeyboardVisibilityListener(){
            @Override
            public void onVisibilityChanged(boolean visible) {
                RelativeLayout contentFrame = (RelativeLayout) getActivity().findViewById(R.id.content_company_navigation);
                BottomBar lowerNavigationBar = (BottomBar) getActivity().findViewById(R.id.bottomBar);
                if (visible) { // if more than 100 pixels, its probably a keyboard...
                    lowerNavigationBar.setVisibility(GONE);
                    contentFrame.setPadding(0, 0, 0, 0);
                    mTeamChatRecyclerView.smoothScrollToPosition(mTestMessageList.size());
                } else {
                    contentFrame.setPadding(0, 0, 0, convertDpToPixel(60, getContext()));
                    mTeamChatRecyclerView.smoothScrollToPosition(mTestMessageList.size());
                    lowerNavigationBar.setVisibility(View.VISIBLE);
                }
            }
        });
        return view;
    }

    /**
     * This method converts dp unit to equivalent pixels, depending on device density.
     *
     * @param dp A value in dp (density independent pixels) unit. Which we need to convert into pixels
     * @param context Context to get resources and device specific display metrics
     * @return A float value to represent px equivalent to dp depending on device density
     */
    public static int convertDpToPixel(float dp, Context context){
        Resources resources = context.getResources();
        DisplayMetrics metrics = resources.getDisplayMetrics();
        int px = (int) (dp * ((float)metrics.densityDpi / DisplayMetrics.DENSITY_DEFAULT));
        return px;
    }

    public void addToTestMessageList(String str){
        this.mTestMessageList.add(str);
        this.mTeamChatListAdapter.notifyDataSetChanged();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
       // getView().getViewTreeObserver().removeGlobalOnLayoutListener(test);
    }

    @Override
    public TeamChatPresenter getSpecificImpOfGenericPresenter() {
        return (TeamChatPresenter) this.mPresenter;
    }
}

这是我的XML布局:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="uk.cal.codename.projectnedry.TeamChatFragment.TeamChatView">

    <android.support.v7.widget.RecyclerView
        android:layout_above="@+id/chatViewMessageEntryLayout"
        android:id="@+id/teamChatList"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_alignParentTop="true"
        android:isScrollContainer="false"
        android:paddingTop="10dp"
        android:scrollbars="vertical" />    

    <RelativeLayout
        android:id="@+id/chatViewMessageEntryLayout"
        android:layout_width="match_parent"
        android:layout_height="60dp"
        android:layout_alignParentBottom="true"
        android:orientation="horizontal">

        <View
            android:id="@+id/chatViewMessageEntrySeperator"
            android:layout_width="match_parent"
            android:layout_height="1dp"
            android:background="#e3e3e8" />

        <EditText
            android:id="@+id/messageTextInput"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_gravity="center_vertical"
            android:layout_below="@+id/chatViewMessageEntrySeperator"
            android:layout_toLeftOf="@+id/teamChatSendButton"
            android:background="@android:color/transparent"
            android:hint="Enter message"
            android:inputType="textCapSentences|textMultiLine"
            android:maxLength="1000"
            android:maxLines="4"
            android:paddingLeft="10dp" />

        <ImageButton
            android:id="@+id/teamChatSendButton"
            android:layout_width="50dp"
            android:layout_height="match_parent"
            android:layout_alignParentRight="true"
            android:layout_gravity="center"
            android:background="#00B9EF"
            android:src="@drawable/ic_send_white_24dp" />

    </RelativeLayout>

</RelativeLayout>

共有3个答案

孔茂
2023-03-14

我最终使用了高度测量方法,这似乎是软键盘检测的标准方法,在这个答案中有所描述。但是,我使用了这个库对它的实现,因为它仍然是相同的ViewTree观察员。OnGlobalLayoutListener方法,实现得很好,并允许我从应用程序主代码库中抽象代码。

当这个键盘可见性监听器被触发时,我会隐藏/显示底部的导航栏(我在这里已经解释过了)。

终子昂
2023-03-14

您只需像这样在清单中添加此代码。。

 <activity android:name=".MainActivity"
        android:windowSoftInputMode="adjustPan">

这对我有用。。快乐编码

岑彬炳
2023-03-14

最简单的实现是添加AndroidManifest。xml在

<activity android:windowSoftInputMode="adjustPan"/>

希望这能帮到别人。享受

 类似资料:
  • 我的应用程序有问题。我有一个底部导航视图,包含3个不同的片段,尽管目前只有主要的内容。当我试图从左侧的两个片段中的一个移动到主视图时,问题就出现了,即当底部导航视图被隐藏时。我附上了主代码。 PD:我有25.3.1版本的所有库(如果有用的话)。 感谢您的关注。 activity\u main。xml 主要活动。Java语言 我也给你添加了两张图片。 Ofertas片段 主片段

  • 问题内容: 我可以使我的应用程序通过SFSafariViewController自动加载此帖子的网址,并且效果很好,唯一的缺点是导航栏。 以这种方式使用SFSafariViewController导航栏时,它是无用的,因为url是只读的,并且“ done”链接除了重新加载页面外不执行任何操作。因此,我想完全隐藏导航栏。 根据已接受答案的注释,建议将我的根视图控制器设置为SFSafariViewCo

  • 本文向大家介绍Android 弹出Dialog时隐藏状态栏和底部导航栏的方法,包括了Android 弹出Dialog时隐藏状态栏和底部导航栏的方法的使用技巧和注意事项,需要的朋友参考一下  上代码 ps:下面看下Android Dialog弹出时不显示导航栏(沉浸式) 我们的app是全屏沉浸式的,发现activity在设置了全屏后,弹出dialog底部会跳出导航栏虚拟键。具体原因是因为Dialog

  • Tabbar 底部导航栏 1.4.8 优点: 此组件一般用于应用的底部导航,具有如下特点: 可以设置凸起的按钮,且是全端通用的 图标可以使用字体图标(内置图标和扩展图标)或者图片 可以动态切换菜单的数量以及配置 切换菜单之前,可以进行回调鉴权 可以设置角标 有效防止组件区域高度塌陷,无需给父元素额外的内边距或者外边距来避开导航的区域 缺点: 虽然优点很多,但是如果用此组件模拟tabbar页面的话依

  • 我正在使用自定义底部导航栏。因此,每当我关注编辑文本字段时,底部视图就会与键盘一起出现。 我已尝试更改清单中的和。它可以工作,但使用时滚动不起作用。 下面是java代码,这是底部导航的单击操作。它与其他三项相似。 }

  • 这就是我要开始的。所选项目应为主页(中间) 我在OnCreate下有这个 而这个外部Oncreate