development

안드로이드 버튼을 비활성화하는 방법?

big-blog 2020. 3. 2. 13:11
반응형

안드로이드 버튼을 비활성화하는 방법?


다음과 이전의 두 버튼이 포함 된 레이아웃을 만들었습니다. 버튼 사이에서 동적 뷰를 생성하고 있습니다. 따라서 응용 프로그램을 처음 시작할 때 이전보기가 없으므로 "이전"단추를 비활성화하려고합니다. 표시 할보기가 더 없을 때 "다음"버튼을 비활성화하고 싶습니다. 어쨌든 버튼을 비활성화 할 수 있습니까?

샘플 레이아웃의 스크린 샷


이것을 시도 했습니까?

myButton.setEnabled(false); 

업데이트 : 그웬에게 감사합니다. android:clickable버튼을 클릭 할 수 있는지 여부를 결정하기 위해 XML 레이아웃에서 설정할 수있는 것을 거의 잊었습니다 .


레이아웃이 런타임에 설정되어 있기 때문에 XML에서 활성화하거나 비활성화 할 수 없지만로 액티비티를 시작할 때 클릭 할 수 있는지 설정할 수 있습니다 android:clickable.


당신은 당신의 활동에 한 줄의 코드를 작성합니다.

Button btn = (Button) findViewById(R.id.button1);
btn.setEnabled(false);

같은 버튼을 사용하려면 그냥 쓰십시오.

Button btn = (Button) findViewById(R.id.button1);
btn.setEnabled(true);

예, 다음을 사용하여 XML에서 비활성화 할 수 있습니다.

<Button
android:enabled="false"
/>

Java에서는 버튼에 대한 참조가 있으면 다음을 수행하십시오.

Button button = (Button) findviewById(R.id.button);

버튼을 활성화 / 비활성화하려면 다음 중 하나를 사용할 수 있습니다.

button.setEnabled(false);
button.setEnabled(true);

또는:

button.setClickable(false);
button.setClickable(true);

버튼을 처음부터 비활성화하려면 button.setEnabled (false); onCreate 메소드에서. 그렇지 않으면 XML에서 직접 사용할 수 있습니다.

android:clickable = "false"

그래서:

<Button
        android:id="@+id/button"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:text="@string/button_text"
        android:clickable = "false" />

나의 경우에는,

myButton.setEnabled(false);
myButton.setEnabled(true);

제대로 작동하고 버튼을 정상적으로 활성화 및 비활성화합니다. 그러나 일단 버튼 상태가 비활성화되면 클릭 할 수 있지만 다시 활성화 상태로 돌아 가지 않습니다. 드로어 블 상태를 무효화하고 새로 고치려고했지만 운이 없습니다.

myButton.invalidate();
myButton.refreshDrawableState();

당신이나 비슷한 문제가있는 사람이라면 저에게 효과적인 것은 백그라운드 드로어 블을 다시 설정하는 것입니다. 모든 API 레벨에서 작동합니다.

myButton.setEnabled(true);
myButton.setBackgroundDrawable(activity.getResources().getDrawable(R.drawable.myButtonDrawable));

Kotlin에서 버튼으로 id를 참조하면 버튼을 다음과 같이 활성화 / 비활성화하십시오

layout.xml

<Button
   android:id="@+id/btn_start"
   android:layout_width="100dp"
   android:layout_height="50dp"
   android:text="@string/start"
   android:layout_alignParentBottom="true"/>

activity.kt

  btn_start.isEnabled = true   //to enable button
  btn_start.isEnabled = false  //to disable button

xml에서 처음으로 버튼을 android:clickable="false"

<Button
        android:id="@+id/btn_send"
        android:clickable="false"/>

그런 다음 코드에서 oncreate()메소드 내부 에서 button 속성을

btn.setClickable(true);

그런 다음 버튼 클릭으로 코드를

btn.setClickable(false);

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    btnSend = (Button) findViewById(R.id.btn_send);
    btnSend.setClickable(true);
    btnSend.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            btnSend.setClickable(false);

        }
    });
}

변수 매개 변수를 사용하는 LISTENER의 잘못된 방법 !!!

btnSend.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View v) {
        btnSend.setClickable(false);

    }
});

올바른 방법 :

btnSend.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View v) {

        /** check given view  by assertion or cast as u wish */
        if(v instance of Button) {

            /** cast */
            Button button = (Button) v;

            /** we can perform some check up */
            if(button.getId() == EXPECTED_ID) {

                /** disable view */
                button.setEnabled(false)            
                button.setClickable(false); 
            }

        } else {

             /** you can for example find desired view by root view  */
             Button bt = (Button) v.getRootView().findViewById(R.id.btId);

             /*check for button */
             if(bt!=null) {

                 /** disable button view */
                 ...
             } else {
                 /** according to @jeroen-bollen remark
                   * we made assumption that we expected a view
                   * of type button here in other any case  
                   */
                  throw new IllegalArgumentException("Wrong argument: " +
                         "View passed to method is not a Button type!");
             }
          }
       }
    });

편집 : @ jeroen-bollen에 대한 회신

 View.OnClickListener 

인터페이스 정의 뷰를 클릭했을 때 콜백을 호출하기위한이.

메소드 정의

void onClick(View v);

뷰를 클릭하면 View 클래스 객체가 onClick () 메소드를 콜백하여 매개 변수 자체로 전송하므로 Assertion Error 인 경우 null 뷰 매개 변수가 발생하지 않아야합니다 ( 예 : View 객체 클래스가 파괴 된 경우) GC에 의해 수집 된 예) 또는 방법이 해킹으로 인해 변조 된 경우

instanceof & null 에 대해 조금

JLS / 15.20.2. 유형 비교 연산자 instanceof

런타임시 RelationalExpression의 값이 널이 아니고 ClassCastException을 발생시키지 않고 Reference를 ReferenceType으로 캐스트 할 수있는 경우 instanceof 연산자의 결과는 true입니다.

그렇지 않으면 결과는 false 입니다.


저자의 세 단어

왜 물어?

NullPointerException을 피하는 것이 좋습니다

코드를 조금만 추가하면 나중에 코드에서 버그를 추적하는 데 시간이 절약되고 수백만의 발생이 줄어 듭니다.

다음 예제를 고려하십시오.

View.OnClickListener listener = new OnClickListener() {

    @Override
    public void onClick(View v) {
        btnSend.setClickable(false);

    }
});

btnSend.setOnClickListener(listener)
btnCancel.setOnClickListener(listener)  

참고 URL : https://stackoverflow.com/questions/4384890/how-to-disable-an-android-button



반응형