program story

레이아웃 내의 모든보기를 비활성화하려면 어떻게해야합니까?

inputbox 2020. 11. 9. 08:06
반응형

레이아웃 내의 모든보기를 비활성화하려면 어떻게해야합니까?


예를 들면 다음과 같습니다.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
        android:layout_height="fill_parent">
     <Button 
        android:id="@+id/backbutton"
        android:text="Back"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    <LinearLayout
        android:id="@+id/my_layout"
        android:orientation="horizontal"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content">
        <TextView
            android:id="@+id/my_text_view"
            android:text="First Name"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
        <EditText
            android:id="@+id/my_edit_view"
            android:width="100px"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" /> 
        <View .../>
        <View .../>
        ...
        <View .../>
    </LinearLayout>

</LinearLayout>

LinearLayout 내부의 모든 요소를 ​​비활성화 (setEnable (false))하는 방법이 my_layout있습니까?


또 다른 방법은 각 자식에 대해 setEnabled ()를 호출하는 것입니다 (예를 들어 비활성화하기 전에 자식에 대해 추가 검사를 수행하려는 경우).

LinearLayout layout = (LinearLayout) findViewById(R.id.my_layout);
for (int i = 0; i < layout.getChildCount(); i++) {
    View child = layout.getChildAt(i);
    child.setEnabled(false);
}

이것은 ViewGroups에 대해 재귀 적입니다.

private void disableEnableControls(boolean enable, ViewGroup vg){
    for (int i = 0; i < vg.getChildCount(); i++){
       View child = vg.getChildAt(i);
       child.setEnabled(enable);
       if (child instanceof ViewGroup){ 
          disableEnableControls(enable, (ViewGroup)child);
       }
    }
}

tutu의 대답은 올바른 방향이지만 그의 재귀는 약간 어색합니다. 나는 이것이 더 깨끗하다고 ​​생각한다.

private static void setViewAndChildrenEnabled(View view, boolean enabled) {
    view.setEnabled(enabled);
    if (view instanceof ViewGroup) {
        ViewGroup viewGroup = (ViewGroup) view;
        for (int i = 0; i < viewGroup.getChildCount(); i++) {
            View child = viewGroup.getChildAt(i);
            setViewAndChildrenEnabled(child, enabled);
        }
    }
}

실제로 나를 위해 일하는 것은 :

getWindow().setFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE, WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);

실행 취소하려면 :

getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);

tütü의 코드를 변경합시다

private void disableEnableControls(boolean enable, ViewGroup vg){
for (int i = 0; i < vg.getChildCount(); i++){
   View child = vg.getChildAt(i);
   if (child instanceof ViewGroup){ 
      disableEnableControls(enable, (ViewGroup)child);
   } else {
     child.setEnabled(enable);
   }
 }
}

뷰 그룹을 비활성화하는 데는 의미가 없다고 생각합니다. 당신이 그것을하고 싶다면, 정확히 같은 목적으로 사용한 또 다른 방법이 있습니다. groupview의 형제로보기 만들기 :

<View
    android:visibility="gone"
    android:id="@+id/reservation_second_screen"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_gravity="bottom"
    android:background="#66ffffff"
    android:clickable="false" />

런타임에 표시되도록합니다. 참고 : 그룹보기의 상위 레이아웃은 상대 레이아웃이거나 프레임 레이아웃이어야합니다. 이것이 도움이되기를 바랍니다.


필사적 인 개발자가 여기 아래로 스크롤하면 다른 옵션이 있습니다. 또한 내가 실험 한 한 스크롤링을 비활성화합니다. 아이디어는 모든 UI 요소 아래의 RelativeLayout에서 이와 같은 View 요소를 사용하는 것입니다.

<View
                android:id="@+id/shade"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:background="@color/primaryShadow"
                android:visibility="gone"/>

따라서 어떤 조건 전에 "사라짐"으로 설정됩니다. 그런 다음 UI를 비활성화하고 싶을 때 가시성을 VISIBLE로 설정합니다. 또한 OnClickListener이보기 를 구현해야합니다 . 이것은 onClickListener클릭 이벤트를 포착하고 기본 요소로 전달하지 않습니다.


특정 ViewGroup에서 뷰를 비활성화하는 데 관심이 있다면 흥미롭고 약간 모호한을 사용할 수 있습니다 duplicateParentState. 보기 상태는 눌림, 활성화, 활성화 등의 부울 속성 집합입니다. 부모 ViewGroup에 동기화하려는 각 자식에서 사용하십시오.

android:duplicateParentState="true"

활성화 된 상태뿐만 아니라 전체 상태를 복제합니다. 이것은 당신이 원하는 것일 수 있습니다! 물론이 방법은 레이아웃 XML을로드하는 경우 가장 좋습니다.


  private void disableLL(ViewGroup layout){
    for (int i = 0; i < layout.getChildCount(); i++) {
        View child = layout.getChildAt(i);
        child.setClickable(false);
        if (child instanceof ViewGroup)
            disableLL((ViewGroup) child);
    }
}

다음과 같은 메서드를 호출하십시오.

RelativeLayout rl_root = (RelativeLayout) findViewById(R.id.rl_root);
disableLL(rl_root);

세부

  • Android 스튜디오 3.1.4
  • Kotlin 1.2.70
  • minSdkVersion 19에서 확인했습니다.

해결책

fun View.forEachChildView(closure: (View) -> Unit) {
    closure(this)
    val groupView = this as? ViewGroup ?: return
    val size = groupView.childCount - 1
    for (i in 0..size) {
        groupView.getChildAt(i).forEachChildView(closure)
    }
}

용법

val layout = LinearLayout(context!!)
layout.forEachChildView {  it.isEnabled = false  }

val view = View(context!!)
view.forEachChildView {  it.isEnabled = false  }

val fragment = Fragment.instantiate(context, "fragment_id")
fragment.view?.forEachChildView {  it.isEnabled = false  }

아래의 재귀 함수를 사용하여 자식보기를 표시 하거나 사라 집니다. 첫 번째 인수는 부모보기이고 두 번째 인수는 부모보기의 자식을 표시할지 여부를 결정합니다. true = 표시됨 false = 사라짐

private void layoutElemanlarininGorunumunuDegistir(View view, boolean gorunur_mu_olsun) {
    ViewGroup view_group;
    try {
        view_group = (ViewGroup) view;
        Sabitler.konsolaYazdir(TAG, "View ViewGroup imiş!" + view.getId());
    } catch (ClassCastException e) {
        Sabitler.konsolaYazdir(TAG, "View ViewGroup değilmiş!" + view.getId());
        return;
    }

    int view_eleman_sayisi = view_group.getChildCount();
    for (int i = 0; i < view_eleman_sayisi; i++) {
        View view_group_eleman = view_group.getChildAt(i);
        if (gorunur_mu_olsun) {
            view_group_eleman.setVisibility(View.VISIBLE);
        } else {
            view_group_eleman.setVisibility(View.GONE);
        }
        layoutElemanlarininGorunumunuDegistir(view_group_eleman, gorunur_mu_olsun);
    }
}

레이아웃 내에서 뷰 비활성화 하는 것과 완전히 같지는 않지만 ViewGroup # onInterceptTouchEvent (MotionEvent) 메서드 를 재정 의하여 모든 자식이 터치를 수신 하지 못하도록 (레이아웃 계층 구조를 반복 할 필요없이) 방지 할 수 있습니다 .

public class InterceptTouchEventFrameLayout extends FrameLayout {

    private boolean interceptTouchEvents;

    // ...

    public void setInterceptTouchEvents(boolean interceptTouchEvents) {
        this.interceptTouchEvents = interceptTouchEvents;
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        return interceptTouchEvents || super.onInterceptTouchEvent(ev);
    }

}

그런 다음 자녀가 터치 이벤트를받지 못하도록 할 수 있습니다.

InterceptTouchEventFrameLayout layout = (InterceptTouchEventFrameLayout) findViewById(R.id.layout);
layout.setInterceptTouchEvents(true);

에 클릭 리스너가 설정되어있는 경우 layout에도 계속 트리거됩니다.


특정 유형의보기를 비활성화하거나 특정 유형의보기를 말하고 싶다면 특정 텍스트가 있거나 텍스트가없는 고정 된 수의 버튼을 비활성화하고 싶다면 해당 유형의 배열을 사용하고 배열 요소를 반복 할 수 있습니다. setEnabled (false) 속성을 사용하여 버튼을 비활성화하는 동안 다음과 같은 함수 호출에서 수행 할 수 있습니다.

public void disable(){
        for(int i=0;i<9;i++){
                if(bt[i].getText().equals("")){//Button Text condition
                    bt[i].setEnabled(false);
            }
        }
}

EditText 및 RadioButton 구성 요소를 제대로 비활성화하기 위해 tütü 응답을 개선했습니다 . 게다가, 뷰 가시성을 변경하고 비활성화 된 뷰에 투명성을 추가하는 방법을 공유하고 있습니다.

private static void disableEnableControls(ViewGroup view, boolean enable){
    for (int i = 0; i < view.getChildCount(); i++) {
        View child = view.getChildAt(i);
        child.setEnabled(enable);
        if (child instanceof ViewGroup){
            disableEnableControls((ViewGroup)child, enable);
        }
        else if (child instanceof EditText) {
            EditText editText = (EditText) child;
            editText.setEnabled(enable);
            editText.setFocusable(enable);
            editText.setFocusableInTouchMode(enable);
        }
        else if (child instanceof RadioButton) {
            RadioButton radioButton = (RadioButton) child;
            radioButton.setEnabled(enable);
            radioButton.setFocusable(enable);
            radioButton.setFocusableInTouchMode(enable);
        }
    }
}

public static void setLayoutEnabled(ViewGroup view, boolean enable) {
    disableEnableControls(view, enable);
    view.setEnabled(enable);
    view.setAlpha(enable? 1f: 0.3f);
}

public static void setLayoutEnabled(ViewGroup view, boolean enable, boolean visibility) {
    disableEnableControls(view, enable);
    view.setEnabled(enable);
    view.setAlpha(enable? 1f: 0.3f);
    view.setVisibility(visibility? View.VISIBLE: View.GONE);
}

이것은 꽤 지연된 답변이지만 누군가에게 도움이 될 수 있습니다. 위에서 언급 한 많은 답변이 좋은 것 같습니다. 그러나 layout.xml에 중첩 된 뷰 그룹이있는 경우. 그러면 위의 답변이 완전한 결과를 제공하지 못할 수 있습니다. 따라서 나는 내 의견을 스 니펫으로 게시했습니다. 아래 코드를 사용하면 모든 뷰를 비활성화 할 수 있습니다 (중첩 된 뷰 그룹 포함).

참고 : 중첩 된 ViewGroup은 권장되지 않으므로 피하십시오.

 private void setEnableView(boolean b) {
    LinearLayout layout = (LinearLayout)findViewById(R.id.parent_container);
    ArrayList<ViewGroup> arrVg = new ArrayList<>();
    for (int i = 0; i < layout.getChildCount(); i++) {
        View child = layout.getChildAt(i);
        if (child instanceof ViewGroup) {
            ViewGroup vg = (ViewGroup) child;
            arrVg.add(vg);
        }
        child.setEnabled(b);
    }

    for (int j=0;j< arrVg.size();j++){
        ViewGroup vg = arrVg.get(j);
        for (int k = 0; k < vg.getChildCount(); k++) {
         vg.getChildAt(k).setEnabled(b);
        }
    }
}

코 틀린에서는 사용할 수 isDuplicateParentStateEnabled = true가되기 전에 View받는 사람에 추가됩니다 ViewGroup.

As documented in the setDuplicateParentStateEnabled method, if the child view has additional states (like checked state for a checkbox), these won't be affected by the parent.

The xml analogue is android:duplicateParentState="true".


I personally use something like this (vertical tree traversal using recursion)

fun ViewGroup.deepForEach(function: View.() -> Unit) {
    this.forEach { child ->
        child.function()
        if (child is ViewGroup) {
            child.deepForEach(function)
        }
    }
}

usage :

   viewGroup.deepForEach { isEnabled = false }

For me RelativeLayout or any other layout at the end of the xml file with width and height set to match_parent with attribute focusable and clickable set to true.

 <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:clickable="true"
            android:focusable="true">

        <ProgressBar
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerInParent="true" />

    </RelativeLayout>

to disable a view, you must call the method setEnabled with false for argument. ex:

Button btn = ...
btn.setEnabled(false);

Set

android:descendantFocusability="blocksDescendants"

for yor ViewGroup view. All descendants will not take focus.

참고URL : https://stackoverflow.com/questions/7068873/how-can-i-disable-all-views-inside-the-layout

반응형