1. TextView - Java 코드로 XML 속성 설정
- activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView 연습1"
android:id="@+id/textView1" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView 연습2"
android:id="@+id/textView2"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView 연습3"
android:id="@+id/textView3"
android:singleLine="true"/>
</LinearLayout>
- MainActivitiy.java
package com.cookandroid.prj4_;
import androidx.appcompat.app.AppCompatActivity;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView tv1, tv2, tv3;
tv1 = findViewById(R.id.textView1);
tv2 = findViewById(R.id.textView2);
tv3 = findViewById(R.id.textView3);
//XML 속성을 자바 메소드로 지정
tv1.setText("안녕하세요?"); //text 내용 지정
tv1.setTextColor(Color.RED); //색상 지정
tv2.setTextSize(30); //글자 크기 지정
tv2.setTypeface(Typeface.SANS_SERIF, Typeface.BOLD_ITALIC); //글꼴 지정
tv3.setText("가나다라마바사아자차카타파하가나다라마바사아자차카타파하가나다라마바사아자차카타파하");
tv3.setSingleLine(); //한줄만 출력하고 나머지는 ...으로 보이게 설정
}
}
2. Button, EditText
- Button
//변수 선언
Button myButton;
//변수에 버튼 위젯 삽입
myButton = (Button) findViewById(R.id.button1);
//버튼 클릭 시 동작하는 클래스 정의
myButton.setOnClickListener(new View.OnClickListener() {
public void onClickView v) {
//동작 내용
}
});
- EditText
//변수 선언
EditText myEdit;
//변수에 위젯 삽입
myEdit = (EditText) findViewById(R.id.edittext1);
//에디트텍스트에 입력된 값 가져오기 -> 주로 버튼 클릭 이벤트 리스너 안에 삽입
String myStr = myEdit.getText().toString();
'Android > 2. 기본 위젯' 카테고리의 다른 글
Day 108 : 애완동물 사진 보기 앱 만들기 (0) | 2022.03.24 |
---|---|
Day 108 : 기본 위젯 활용하기 (0) | 2022.03.24 |
Day 108 : 초간단 계산기 앱 만들기 (0) | 2022.03.24 |
Day 108 : 뷰의 개요 (0) | 2022.03.24 |