반응형
xml 파일에서 Button 에 onClick 이벤트를 설정해준다
setEnabled(false); 를 이용할 것이므로 "disabled"로 설정해주었다
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
// onClick 이벤트를 설정해준다
android:onClick="disabled"
android:text="Button"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
tools:layout_editor_absoluteY="262dp" />
그리고 나서
페이지에 맞는 .java 파일에서 disabled 이벤트를 수행할 함수를 생성한다.
// onCreate 함수 바로 밑에 만들면 된다
// View를 import 해서 매개변수에 View를 쓸 수 있게 한다
public void disabled(View view1) {
// disabled 함수 발생시 setEnabled 메소드를 false가 되도록 한다
view1.setEnabled(false);
// Button 을 import 해서 Button 을 쓸 수 있게 하고 view1을 Button 으로 캐스팅한다
// 그래야 button의 메소드인 setText를 이용할 수 있다
Button button1 = (Button) view1;
// setText를 이용하여 글자가 변경되도록 한다
button1.setText("Disabled!");
}
이렇게 하면
이렇게 변경된다
다른 방법도 있다.
이번에는 findViewById 라는 메소드를 이용할텐데
resource에 있는 id 값을 가지고 있는 view를 찾는 메소드이다.
함수를 지니고 있는 동일한 view의 id값을 찾는건 차이가 없어보이기 때문에
다른 button을 하나 더 만들고 @+id/ button2로 설정했다
public void disabled(View view1) {
// myview라는 View 객체를 하나 만들고 findViewById로 id가 button2인 view를 할당한다
View myview = findViewById(R.id.button2);
// 위의 코드와 동일하게 myview를 disabled로 변경하는 코드
myview.setEnabled(false);
Button button1 = (Button) myview;
button1.setText("Disabled!");
}
이렇게 하면
이렇게 변경할 수 있다
event로 건드릴 View가 Button 인걸 안다면 처음부터 button 객체로 만들어도 된다
public void disabled(View view1) {
//이렇게 바로 Button 객체로 만든다
Button myview = findViewById(R.id.button2);
myview.setEnabled(false);
myview.setText("button disabled");
}
혹은 굳이 객체를 만들 필요 없이 findViewById 에다가 메소드를 이용해주면 된다
public void disabled(View view1) {
findViewById(R.id.button2).setEnabled(false);
/* 그래도 아직 Button 객체가 아니라서 setText메소드를 이용할 수 없기 때문에
캐스팅을 해준 후 괄호로 다시 감싸서 setText를 이용하면 된다 */
((Button)findViewById(R.id.button2)).setText("New Disabled");
}
짠
반응형