오늘이라도
[Android] 19. 바텀 네비게이션 / 리스트 뷰 ① : 리스트 뷰로 리스트 출력, 선택한 항목 하이라이트 본문
취업성공패키지 SW 개발자 교육/Android
[Android] 19. 바텀 네비게이션 / 리스트 뷰 ① : 리스트 뷰로 리스트 출력, 선택한 항목 하이라이트
upcake_ 2020. 6. 1. 09:24반응형
https://github.com/upcake/Class_Examples
교육 중에 작성한 예제들은 깃허브에 올려두고 있습니다.
gif 파일은 클릭해서 보는 것이 정확합니다.
- 바텀 네비게이션(Bottom Navigation) -
▼activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<FrameLayout
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="@string/appbar_scrolling_view_behavior"/>
<com.google.android.material.bottomnavigation.BottomNavigationView
android:id="@+id/bottom_navigation"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentBottom="true"
app:itemBackground="@color/colorPrimary"
app:menu="@menu/menu_bottom"
app:itemIconTint="@drawable/item_color"
app:itemTextColor="@drawable/item_color"/>
</RelativeLayout>
▼MainActivity.java
package com.example.my25_bottomnavigation;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MenuItem;
import android.widget.Toast;
import com.google.android.material.bottomnavigation.BottomNavigationView;
public class MainActivity extends AppCompatActivity {
//프래그먼트 객체 선언
Fragment1 fragment1;
Fragment2 fragment2;
Fragment3 fragment3;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//프래그먼트 객체 초기화
fragment1 = new Fragment1();
fragment2 = new Fragment2();
fragment3 = new Fragment3();
//화면에 프래그먼트1 출력
getSupportFragmentManager().beginTransaction().replace(R.id.container, fragment1).commit();
//바텀 네비게이션 객체 초기화
BottomNavigationView bottomNavigationView = findViewById(R.id.bottom_navigation);
//바텀 네비게이션에 이벤트 추가
bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
//바텀 네비게이션 버튼에 눌렀을때 화면 바뀌는 기능 추가
//item.getItemId() 아이템의 아이디를 바로 가져옴
switch (item.getItemId()) {
case R.id.tab1:
Toast.makeText(MainActivity.this, "첫 번째 탭", Toast.LENGTH_SHORT).show();
getSupportFragmentManager().beginTransaction().replace(R.id.container, fragment1).commit();
return true; //return true 밑으로는 작동이 되지 않는다.
case R.id.tab2:
Toast.makeText(MainActivity.this, "두 번째 탭", Toast.LENGTH_SHORT).show();
getSupportFragmentManager().beginTransaction().replace(R.id.container, fragment2).commit();
return true;
case R.id.tab3:
Toast.makeText(MainActivity.this, "세 번째 탭", Toast.LENGTH_SHORT).show();
getSupportFragmentManager().beginTransaction().replace(R.id.container, fragment3).commit();
return true;
}
return false;
}
});
}
}
▼menu_bottom.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<!--showAsAction="ifRoom" 공간이 있으면 보이게 설정-->
<!--enabled="true" 클릭 가능 여부 설정-->
<item
android:id="@+id/tab1"
app:showAsAction="ifRoom"
android:enabled="true"
android:icon="@android:drawable/ic_dialog_email"
android:title="이메일" />
<item
android:id="@+id/tab2"
app:showAsAction="ifRoom"
android:enabled="true"
android:icon="@android:drawable/ic_dialog_info"
android:title="정보" />
<item
android:id="@+id/tab3"
app:showAsAction="ifRoom"
android:enabled="true"
android:icon="@android:drawable/ic_dialog_map"
android:title="위치" />
</menu>
▼item_color.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<!--선택 되면 색깔 변경-->
<item
android:state_checked="true"
android:color = "#51032D" />
<item android:color = "#CFD8DC"/>
</selector>
▼fragment1.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"
android:background="#00BCD4">
<Button
android:id="@+id/button2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="첫 번째"/>
<TextView
android:id="@+id/textView1"
android:layout_width="match_parent"
android:layout_height="312dp"
android:textColor="#FFFFFF"
android:textSize="24sp" />
</LinearLayout>
▼Fragment1.java
package com.example.my25_bottomnavigation;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import com.google.android.material.tabs.TabLayout;
public class Fragment1 extends Fragment {
//객체 선언
Button button2;
TextView textView1;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
//XML, java 연결
//XML이 메인에 직접 붙으면 true, 프래그먼트에 붙으면 false
ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.fragment1, container, false);
//객체 초기화
textView1 = rootView.findViewById(R.id.textView1);
button2 = rootView.findViewById(R.id.button2);
return rootView;
}
}
▼fragment2.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"
android:background="#2196F3">
<Button
android:id="@+id/button3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="두 번째"/>
<TextView
android:id="@+id/textView2"
android:layout_width="match_parent"
android:layout_height="324dp"
android:textColor="#FFFFFF"
android:textSize="24sp" />
</LinearLayout>
▼Fragment2.java
package com.example.my25_bottomnavigation;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import com.google.android.material.tabs.TabLayout;
public class Fragment2 extends Fragment {
//객체 선언
Button button3;
TextView textView2;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
//XML, java 연결
//XML이 메인에 직접 붙으면 true, 프래그먼트에 붙으면 false
ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.fragment2, container, false);
//객체 초기화
textView2 = rootView.findViewById(R.id.textView2);
button3 = rootView.findViewById(R.id.button3);
return rootView;
}
}
▼fragment3.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"
android:background="#673AB7">
<Button
android:id="@+id/button4"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="세 번째"/>
<TextView
android:id="@+id/textView3"
android:layout_width="match_parent"
android:layout_height="321dp"
android:textColor="#FFFFFF"
android:textSize="24sp" />
</LinearLayout>
▼Fragment3.java
package com.example.my25_bottomnavigation;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import com.google.android.material.tabs.TabLayout;
public class Fragment3 extends Fragment {
//객체 선언
Button button4;
TextView textView3;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.fragment3, container, false);
//객체 초기화
textView3 = rootView.findViewById(R.id.textView3);
button4 = rootView.findViewById(R.id.button4);
return rootView;
}
}
- 리스트 뷰(List View) ① : 리스트 뷰로 리스트 출력, 선택한 항목 하이라이트 -
▼activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="@+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@android:color/holo_blue_bright"
android:gravity="center"
android:text="아래 목록에서 선택하세요"
android:textSize="24sp" />
<ListView
android:id="@+id/listView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:listSelector="@android:color/holo_green_light"/>
</LinearLayout>
▼MainActivity.java
package com.example.my26_listview;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import java.util.ArrayList;
/*
ListView : 클릭 이벤트를 제공해줘서 편리함.
메모리 활용이 비효율적
RecyclerView : 클릭 이벤트를 제공해주지않아서 불편함
메모리 활용이 효율적
*/
public class MainActivity extends AppCompatActivity {
//객체 선언
TextView textView;
ListView listView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//객체 초기화
textView = findViewById(R.id.textView);
listView = findViewById(R.id.listView);
//데이터를 담을 리스트와 어댑터 설정
ArrayList<String> list = new ArrayList<>();
//어댑터 : 보여지는 View와 View에 올려질 Data를 연결하는 일종의 Bridge
//android.R.layout.simple.list_item_1 : 단 하나의 String 타입 데이터를 표시하게끔 만들어진 일종의 기본 레이아웃 양식
ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, list);
listView.setAdapter(adapter);
//어댑터에 출력된 아이템에 클릭시 기능 추가
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String selectedItem = (String) parent.getItemAtPosition(position);
textView.setText(selectedItem);
}
});
//리스트에 데이터 추가
list.add("바나나");
list.add("딸기");
list.add("수박");
list.add("사과");
list.add("오렌지");
list.add("망고");
list.add("키위");
list.add("포도");
list.add("멜론");
list.add("두리안");
}
}
반응형