itsource

프래그먼트 안에 소프트 키보드를 숨기는 방법

mycopycode 2022. 12. 4. 22:37
반응형

프래그먼트 안에 소프트 키보드를 숨기는 방법

는 나나 a a a가 있다FragmentActivity, 「」의ViewPager몇 개의 파편을 제공합니다. 「」입니다.ListFragment하다

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <LinearLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:padding="8dp">
        <ListView android:id="@id/android:list"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent" />

        <EditText android:id="@+id/entertext"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content" />
    </LinearLayout>
</LinearLayout>

액티비티를 시작하면 소프트 키보드가 표시됩니다.이것을 해결하기 위해서, fragment내에서 다음의 조작을 실시했습니다.

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    //Save the container view so we can access the window token
    viewContainer = container;
    //get the input method manager service
    imm = (InputMethodManager)getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
    . . .
}

@Override
public void onStart() {
    super.onStart();

    //Hide the soft keyboard
    imm.hideSoftInputFromWindow(viewContainer.getWindowToken(), 0);
}

수신한 것을 보존합니다.ViewGroup container의 파라미터onCreateView메인 액티비티의 윈도 토큰에 액세스 할 수 있습니다. 조작은 실행되지만 hideSoftInputFromWindowonStart.

, 는, 는, 는, 나, 나, layout, layout, layout, layout, layout, layout, layout, layout, layout, layout, layout, layout, layout, layout, layout, layout, layout, layout, layout, layout,container (예:)

imm.hideSoftInputFromWindow(myInflatedLayout.getWindowToken(), 0);

...NullPointerException프래그먼트 자체가 액티비티가 아니고, 독자적인 윈도 토큰이 없기 때문일까요?

에서 소프트 수 있는 fragment 가 있습니까?'프래그먼트' '메서드' '메서드' '메서드'?FragmentActivity편편안 에러 ?러? 러??? ???

fragment가 뷰를 생성하기만 하면 IBinder(윈도우 토큰)가 연결된 후 해당 에서 IBinder(윈도우 토큰)를 사용할 수 있습니다.예를 들어 fragment에서 onActivityCreated를 덮어쓸 수 있습니다.

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    final InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
    imm.hideSoftInputFromWindow(getView().getWindowToken(), 0);
}

다음 코드 줄 외에는 아무 것도 통하지 않았다.

getActivity().getWindow().setSoftInputMode(
            WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

활동의 매니페스트 정의에 다음 속성을 추가하면 활동이 열릴 때 키보드가 완전히 표시되지 않습니다.이것이 도움이 되기를 바랍니다.

(활동의 매니페스트 정의에 추가):

android:windowSoftInputMode="stateHidden"
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_my, container,
                false);
        someClass.onCreate(rootView);
        return rootView;
    }

내 클래스에 내 루트 뷰 인스턴스 유지

View view;

public void onCreate(View rootView) {
    view = rootView;

보기를 사용하여 키보드 숨기기

 public void removePhoneKeypad() {
    InputMethodManager inputManager = (InputMethodManager) view
            .getContext()
            .getSystemService(Context.INPUT_METHOD_SERVICE);

    IBinder binder = view.getWindowToken();
    inputManager.hideSoftInputFromWindow(binder,
            InputMethodManager.HIDE_NOT_ALWAYS);
}

의 :DialogFragment,Dialog 하고, 첫 숨겨야 합니다.대신 첫 번째만EditText되어 있는 「」내Dialog

this.getDialog().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);

이 코드는 fragment에 대해 기능합니다.

getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

임의의 장소(액티비티/프래그먼트)에서 이 정적 방법을 사용합니다.

public static void hideKeyboard(Activity activity) {
    try{
        InputMethodManager inputManager = (InputMethodManager) activity
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        View currentFocusedView = activity.getCurrentFocus();
        if (currentFocusedView != null) {
            inputManager.hideSoftInputFromWindow(currentFocusedView.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }catch (Exception e){
        e.printStackTrace();
    }
}

는, 「」콜 fragment에 대해서만 합니다.hideKeyboard(((Activity) getActivity())).

이것은, 탭내에서 fragment를 다른 fragment로 전환하는 경우에 유효합니다.

@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
    super.setUserVisibleHint(isVisibleToUser);
    if (isVisibleToUser) {
        try {
            InputMethodManager mImm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
            mImm.hideSoftInputFromWindow(getView().getWindowToken(), 0);
            mImm.hideSoftInputFromWindow(getActivity().getCurrentFocus().getWindowToken(), 0);
        } catch (Exception e) {
            Log.e(TAG, "setUserVisibleHint: ", e);
        }
    }
}

단편적으로 나에게 효과가 있었던 솔루션:

fun hideKeyboard(){
    val imm = requireActivity().getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
    imm.hideSoftInputFromWindow(view?.windowToken, 0)
}

액티비티에서 다음을 수행합니다.

fun hideKeyboard(){
    val inputManager: InputMethodManager = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
    inputManager.hideSoftInputFromWindow(currentFocus?.windowToken, InputMethodManager.SHOW_FORCED)
}

API27에서는 아무것도 동작하지 않았습니다.레이아웃의 컨테이너에 이것을 추가해야 했습니다.저에게는 ConstraintLayout이었습니다.

<android.support.constraint.ConstraintLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:focusable="true"
            android:focusableInTouchMode="true"
            android:focusedByDefault="true">

//Your layout

</android.support.constraint.ConstraintLayout>

이것은 코틀린 수업에서 나에게 효과가 있었다.

fun hideKeyboard(activity: Activity) {
    try {
        val inputManager = activity
            .getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        val currentFocusedView = activity.currentFocus
        if (currentFocusedView != null) {
            inputManager.hideSoftInputFromWindow(currentFocusedView.windowToken, InputMethodManager.HIDE_NOT_ALWAYS)
        }
    } catch (e: Exception) {
        e.printStackTrace()
    }

}

fragment 버튼청취기에서 다음 코드를 사용합니다.

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

코틀린 코드

val imm = requireActivity().getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
imm.hideSoftInputFromWindow(requireActivity().currentFocus?.windowToken, 0)

코드에 다음 행을 추가합니다.

getActivity().getWindow().setSoftInputMode(
                WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

Kotlin의 경우:

(activity?.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager).hideSoftInputFromWindow(view?.windowToken,0)

사용방법:

Button loginBtn = view.findViewById(R.id.loginBtn);
loginBtn.setOnClickListener(new View.OnClickListener() {
   public void onClick(View v) {
      InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(getActivity().INPUT_METHOD_SERVICE);
      imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
   }
});

처음에

fragment로, 다음의 코드(onActivityCreated 로 사용)는, 처음에 키보드를 강제적으로 숨깁니다.

@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    Objects.requireNonNull(getActivity()).getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
}

프래그먼트 실행 중(필요한 경우)

또, 편집 텍스트나 다른 요구를 가지는 키보드가 있는 경우는, 키보드 외부를 누를 때에 키보드를 숨기고 싶은 경우는, 우선 레이아웃을 초기화합니다(내 경우는, xml 의 LinearLayout 클래스가 있습니다.

LinearLayout linearLayout;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    
    View view = inflater.inflate(R.layout.<your fragment xml>, container, false);

    linearLayout= view.findViewById(R.id.linearLayout);
    ...
    return view;
}

그런 다음 아래 코드를 입력해야 합니다(onViewCreated에서 사용).

@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {

    linearLayout.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view12) {
            try {
                InputMethodManager inputMethodManager = (InputMethodManager) Objects.requireNonNull(VideoFragment.this.getActivity()).getSystemService(INPUT_METHOD_SERVICE);
                assert inputMethodManager != null;
                inputMethodManager.hideSoftInputFromWindow(VideoFragment.this.getActivity().getCurrentFocus().getWindowToken(), 0);

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });

}

다음 두 가지 방법을 사용할 수 있습니다.

fragment 내부에 메서드를 작성할 수 있지만 먼저 View 속성을 만들고 인플레이터 결과를 내부에 삽입한 후 onCreateView로 반환해야 합니다.

1° 프래그먼트 클래스를 엽니다.속성 생성

private View view;

2° onCreateView에서 인플레이터의 'view' 속성을 할당합니다.

@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
                view = inflater.inflate(R.layout.your_activity_main, container, false);
                return view;
}

3° 'hideKeyboard' 메서드를 만듭니다.

public void hideKeyboard(Activity activity) {
        try{
            InputMethodManager inputManager = (InputMethodManager) activity
                    .getSystemService(view.getContext().INPUT_METHOD_SERVICE);
            View currentFocusedView = activity.getCurrentFocus();
            if (currentFocusedView != null) {
                inputManager.hideSoftInputFromWindow(currentFocusedView.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

5° 이제 메서드를 호출합니다.

    hideKeyboard(getActivity());

그래도 문제가 해결되지 않으면 MainActivity 클래스를 개체로 전달하여 Frament 클래스 내에서 키보드를 닫아 보십시오.

1° YourClassActivity에서 fragment를 인스턴스화한 'hideKeyboard' 메서드를 만듭니다.

public class YourClassActivity extends AppCompatActivity {
    public static void hideKeyboard(Activity activity) {
            InputMethodManager imm = (InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
            //Find the currently focused view, so we can grab the correct window token from it.
            View view = activity.getCurrentFocus();
            //If no view currently has focus, create a new one, just so we can grab a window token from it
            if (view == null) {
                view = new View(activity);
            }
            imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
        }
}

2° 액티비티에서 단편화를 인스턴스화하는 '시리얼화 가능' 인터페이스를 구현합니다.

public class YourClassActivity extends AppCompatActivity implements Serializable {
...
}

3° 액티비티에서 프래멘트를 인스턴스화할 때 해당 프래그먼트(액티비티 클래스 자체)에 인수를 전달해야 합니다.

Bundle bundle = new Bundle();
bundle.putSerializable("activity", this);
YourClassFragment fragment = new YourClassFragment();
fragment.setArguments(bundle);

4° 이제 fragment 클래스로 이동하겠습니다.속성 뷰 및 액티비티를 만듭니다.

private View view;  
private Activity activity;

5° onCreateView에서 인플레이터의 'view' 속성을 할당합니다.이 프래그먼트(Fragment)의 파라미터로 전달된 Activity 객체를 가져옵니다.

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
            view = inflater.inflate(R.layout.your_activity_main, container, false);
            activity = (Activity) getArguments().getSerializable("obj");
    
            return view;
    }

6° 이제 메서드를 호출합니다.

hideKeyboard(activity);

모든 순서를 실행했지만, 뭔가 부족한 것이 있어, 그 방법으로 키보드를 조각조각 숨깁니다.

fun hideKeyBoard(view: View) {
        val inputManager =
            requireActivity().getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        inputManager.hideSoftInputFromWindow(
            view.windowToken,
            SOFT_INPUT_STATE_ALWAYS_HIDDEN
        )
    }

그러나 내가 fragment를 열었을 때 키보드는 또한 많은 검색 후에 나는 문제를 발견했다. 나는 그 코드를 나의 xml 레이아웃 루트에 넣어야 한다.

android:focusable="true"
android:focusableInTouchMode="true" 

주의: 위의 메서드를 삭제하고 루트 레이아웃에 Atribute만 넣으면 정상적으로 동작합니다.

언급URL : https://stackoverflow.com/questions/7940765/how-to-hide-the-soft-keyboard-inside-a-fragment

반응형