ASCII

안드로이드 스튜디오 버튼 사용/ 토스트 메시지 출력 본문

Android Studio

안드로이드 스튜디오 버튼 사용/ 토스트 메시지 출력

규바보 2017. 8. 30. 14:17

버튼은 사용자가 버튼을 터치하는 것으로 그에 따라 특정한 기능(동작)을 수행하는 것이다.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
//Activity.xml
 
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">
 
        <Button
            android:id="@+id/button2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Button"
            android:onClick="clickButton"
            android:layout_centerVertical="true"
            android:layout_centerHorizontal="true" />
    </RelativeLayout>
cs


Layout에 Button(버튼)을 추가하고 onClick 속성을 추가하고 클릭되었을 때 사용되는 

함수명을 적어주면 된다.


onClick 함수는 버튼 이외에도 다른 뷰(사진, 텍스트...)에 적용할 수 있다.

(예를 들어 이미지를 클릭한다던지, 글자를 클릭했다던지..)


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
//MainActivity.java
 
public class MainActivity extends AppCompatActivity {
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
 
    public void clickButton(View v)
    {
        Toast.makeText(this"Hello, World", Toast.LENGTH_LONG).show();
    }
 
}
cs


onClick 함수의 속성으로 추가했던 clickButton을 정의하고 있다.

다시 말해 버튼을 클릭하면 clickButton 함수가 실행되는 것이다.

clickButton 함수를 살펴보면 토스트 메시지를 띄워 주고 있다. 

토스트 메시지는 화면 하단 중앙에 원하는 메시지를 잠시 출력해준다.


실행결과 : 


Comments