안녕하세요:) 주니어 개발자 Hellow:)입니다.
이번에 간단한 전화번호부를 만들면서 기본적인 Intent와 addVIew 사용법을 익혀보려고 합니다.
현재 addView는 사용하지 않고 recyclerView를 사용하는데 학습 목적으로 쉽게 addView를 사용해서 ListView를 만들어보려고 합니다.:)
[결과 화면]
전화번호부 리스트 중 목록을 클릭하면 상세페이지가 나오게 합니다 :)
[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">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#1E7AC3"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0dp"
android:layout_height="60dp"
android:layout_weight="5"
android:padding="15dp"
android:text="Contacts"
android:textColor="@color/white"
android:textSize="20sp"/>
<ImageButton
android:layout_width="0dp"
android:layout_height="60dp"
android:layout_weight="1"
android:scaleType="fitCenter"
android:src="@drawable/loupe"/>
<ImageButton
android:layout_width="0dp"
android:layout_height="60dp"
android:layout_weight="1"
android:scaleType="fitCenter"
android:src="@drawable/menu"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:backgroundTint="#1E7AC3"
android:textColor="@color/white"
android:text="FAVORITES"
android:padding="15dp"
android:textSize="15sp"/>
<Button
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:backgroundTint="#1E7AC3"
android:textColor="@color/white"
android:text="ALL CONTACTS"
android:padding="15dp"
android:textSize="15sp"/>
</LinearLayout>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="15dp"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:text="ME"
android:textColor="#5C5B5B"
android:textSize="15sp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:text="Set up my profile"
android:padding="10dp"
android:textSize="15sp"/>
</LinearLayout>
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="true">
<LinearLayout
android:id="@+id/containerView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
</LinearLayout>
</ScrollView>
</LinearLayout>
[activity_detail_phone_book.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=".DetailPhoneBook"
android:orientation="vertical"
android:id="@+id/detailPhoneBoook">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="400dp"
android:background="#6A6868">
<ImageButton
android:id="@+id/back"
android:layout_width="50dp"
android:layout_height="50dp"
android:src="@drawable/back"
android:scaleType="fitXY"/>
<ImageView
android:layout_width="200dp"
android:layout_height="200dp"
android:src="@drawable/user"
android:layout_gravity="center"/>
<TextView
android:id="@+id/detailName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:textSize="30sp"
android:layout_margin="20dp"
android:textColor="@color/white"/>
</FrameLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="60dp"
android:layout_margin="10dp">
<ImageView
android:layout_width="0dp"
android:layout_height="20dp"
android:layout_weight="1"
android:layout_gravity="center"
android:src="@drawable/phone"/>
<LinearLayout
android:layout_width="0dp"
android:layout_height="60dp"
android:layout_weight="5"
android:paddingLeft="10dp"
android:gravity="center|left"
android:orientation="vertical">
<TextView
android:id="@+id/detailNumber"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="15dp"
android:textColor="@color/black"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Mobile"
android:textColor="#4E4E4E"
android:textSize="13dp"/>
</LinearLayout>
<ImageView
android:layout_width="0dp"
android:layout_height="20dp"
android:layout_weight="1"
android:src="@drawable/comment"
android:layout_gravity="center"/>
</LinearLayout>
</LinearLayout>
[numberlist_view.xml]
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:id="@+id/txHeadName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:textSize="15sp"/>
<TextView
android:id="@+id/txFullName"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:gravity="center"
android:padding="10dp"
android:textSize="15sp" />
</LinearLayout>
</LinearLayout>
[MainActivity.kt]
package com.hellow.phonebook
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.widget.LinearLayout
import android.widget.TextView
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// list생성 및 phoneBook생성
val phoneBook = createFakePhoneBook(20)
createPhoneBookList(phoneBook)
}
// 생성 할 Person의 갯수를 입력하면 해당 갯수만큼 Person 인스턴스를 List에 추가 전화번호부를 return
fun createFakePhoneBook(fakeNumber: Int = 10, phoneBook: PhoneBook = PhoneBook()): PhoneBook {
for (i in 0 until fakeNumber) {
phoneBook.addPerson(
Person("${i}번째 사람", "010-1234-567,${i}")
)
}
return phoneBook
}
fun createPhoneBookList(phoneBook: PhoneBook) {
// 인플레이터와 아이템 뷰를 붙일 컨테이너 생성
val inflaterLayout = LayoutInflater.from(this@MainActivity)
val container = findViewById<LinearLayout>(R.id.containerView)
// headName과 phoneNumber 변수 생성 및 데이터 저장
for (i in 0 until phoneBook.personList.size) {
val itemView = layoutInflater.inflate(R.layout.numberlist_view, null)
val headName = itemView.findViewById<TextView>(R.id.txHeadName)
val phoneNumber = itemView.findViewById<TextView>(R.id.txHeadName)
headName.text = phoneBook.personList[i].name
phoneNumber.text = phoneBook.personList[i].number
// 생성한 itemView를 container에 addView
container.addView(itemView)
// 리스트 클릭 시 상세페이지 이동
detailPageOpen(phoneBook.personList[i], itemView)
}
}
// 상세 페이지 생성 및 리스트 클릭 시 액티비티 전환
fun detailPageOpen(person: Person, view: View) {
view.setOnClickListener {
// 인텐트 생성 및 서브 액티비티 실행
val intent = Intent(this@MainActivity, Detail_PhoneBook::class.java)
intent.putExtra("Name", person.name)
intent.putExtra("Number", person.number)
startActivity(intent)
}
}
}
// Person인스턴스 List를 가진 PhoneBook 클래스 선언
class PhoneBook() {
val personList = ArrayList<Person>()
fun addPerson(person: Person) {
personList.add(person)
}
}
// 이름과 전화번호를 가진 Person클래스 선언
class Person(val name: String, val number: String) {
}
[Detail_phoneBook.kt]
package com.hellow.phonebook
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.ImageButton
import android.widget.TextView
class Detail_PhoneBook : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_detail__phone_book)
getPersonInfo()
// back클릭시 MainActivity로 이동
val btnBack : ImageButton = findViewById<ImageButton>(R.id.back)
btnBack.setOnClickListener{
onBackPressed()
}
}
fun getPersonInfo() {
// TextView Name, Phone 변수
val strName = findViewById<TextView>(R.id.detailName)
val strPhone = findViewById<TextView>(R.id.detailNumber)
// 인텐트로 받아온 이름, 전화번호 값을 name, phone에 저장
strName.text = intent.getStringExtra("Name")
strPhone.text = intent.getStringExtra("Number")
}
}
이상 마치겠습니다 :)
+추가 (위와 동일한 자바 코드)
[MainActivity]
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// list생성 및 phoneBook생성
PhoneBook phoneBook = createFakePhoneBook(20, new PhoneBook());
createPhoneBookList(phoneBook);
}
private PhoneBook createFakePhoneBook(int fakeNumber, PhoneBook phoneBook) {
for (int i = 0; i < fakeNumber; i++) {
phoneBook.addPerson(new Person(i + "번째 사람", "010-1234-5678" + i));
}
return phoneBook;
}
@SuppressLint("WrongConstant")
private void createPhoneBookList(PhoneBook phoneBook) {
// 인플레이터와 아이템 뷰를 붙일 컨테이너 생성
LayoutInflater inflateLayout = LayoutInflater.from(this);
RecyclerView container = findViewById(R.id.containerView);
// headName과 phoneNumber 변수 생성 및 데이터 저장
for (int i = 0; i < phoneBook.getPersonListSize(); i++) {
View itemView = getLayoutInflater().inflate(R.layout.numberlist_view, null);
TextView headName = itemView.findViewById(R.id.txHeadName);
TextView phoneNumber = itemView.findViewById(R.id.txPhoneNumber);
headName.setText(phoneBook.getPerson(i).getName());
phoneNumber.setText(phoneBook.getPerson(i).getNumber());
// layoutManager 설정
container.setLayoutManager(new LinearLayoutManager(this, LinearLayout.HORIZONTAL, false));
// 생성한 itemView를 container에 addView
container.addView(itemView);
// 리스트 클릭 시 상세페이지 이동
detailPageOpen(phoneBook.getPerson(i), itemView);
}
}
private void detailPageOpen(Person person, View view) {
view.setOnClickListener(v -> {
// 인텐트 생성 및 서브 액티비티 실행
Intent intent = new Intent(getApplicationContext(), Detail_PhoneBook.class);
intent.putExtra("Name", person.getName());
intent.putExtra("Number", person.getNumber());
startActivity(intent);
});
}
}
class Person {
private String name;
private String number;
public Person(String name, String number) {
this.name = name;
this.number = number;
}
public void setName(String name) {
this.name = name;
}
public void setNumber(String number) {
this.number = number;
}
public String getName() {
return name;
}
public String getNumber() {
return number;
}
}
class PhoneBook {
private ArrayList<Person> personList = new ArrayList<Person>();
public Person getPerson(int index) { return personList.get(index); }
public int getPersonListSize() { return personList.size(); }
public void addPerson(Person person) { personList.add(person); }
}
[Detail_PhoneBook]
public class Detail_PhoneBook extends AppCompatActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail__phone_book);
getPersonInfo();
// back클릭 시 MainActivity로 이동
ImageButton btnBack = findViewById(R.id.back);
btnBack.setOnClickListener(v -> {
onBackPressed();
});
}
private void getPersonInfo() {
// TextView, Name, Phone 변수
TextView strName = findViewById(R.id.detailName);
TextView strPhone = findViewById(R.id.detailNumber);
// 인텐트로 받아온 이름, 전화번호 값을 name, phone에 저장
strName.setText(getIntent().getStringExtra("Name"));
strPhone.setText(getIntent().getStringExtra("Number"));
}
}
https://github.com/znzldh1234/Android_PhoneBook_Study