[이전]
[설명]
이번에는 fragment와 bottomnavigationview를 이용하여, 즐겨찾기화면과 지역검색 화면을 구현하겠습니다.
하단에 선택을 할수있는 탭을 만들기위해 navi_bottom_menu.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">
<item
android:id="@+id/first"
app:showAsAction="ifRoom"
android:enabled="true"
android:icon="@drawable/icon_star"
android:title="즐겨찾기" />
<item
android:id="@+id/second"
app:showAsAction="ifRoom"
android:icon="@drawable/icon_earth"
android:title="지역검색" />
</menu>
activity_main을 작성합니다.
<?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"
android:orientation="vertical"
tools:context=".MainActivity">
<FrameLayout
android:layout_weight="1"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<com.google.android.material.bottomnavigation.BottomNavigationView
android:id="@+id/bnv_menu"
android:background="@color/white"
app:menu="@menu/navi_bottom_menu"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
즐겨찾기 fragment와 , 지역검색 fragment를 생성해줍니다.
[FavoritesFragment]
class FavoritesFragment : Fragment() {
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_favorites, container, false)
}
}
[SearchFragment]
class SearchFragment : Fragment() {
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_search, container, false)
}
}
[MainActivity]
class MainActivity : AppCompatActivity() {
private val FavoritesFragment by lazy { FavoritesFragment() }
private val SearchFragment by lazy { SearchFragment() }
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
setBottomNavigatioBar()
}
private fun setBottomNavigatioBar()
{
val bnv_menu = findViewById<BottomNavigationView>(R.id.bnv_menu)
bnv_menu.run {
setOnItemSelectedListener {
when(it.itemId)
{
R.id.favorites -> {moveFragment(FavoritesFragment)}
R.id.search -> {moveFragment(SearchFragment)}
}
true
}
selectedItemId = R.id.favorites
}
}
private fun moveFragment(f : Fragment)
{
supportFragmentManager.beginTransaction().replace(R.id.fl,f).commit()
}
}
'안드로이드 > 날씨 앱 만들기' 카테고리의 다른 글
[날씨 앱 만들기] 1. 시작하기 - Lottie 사용해보기 (0) | 2023.01.16 |
---|