1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

ModalBottomSheet の使い方 - kotlin

Posted at

できるもの

Material Design の Modal Bottom Sheets
ボトムシート20181231.png

やること

  1. ライブラリの読み込み
  2. ボトムシートのレイアウト追加
  3. ボトムシートを呼び出すボタン追加
  4. ボトムシートの呼び出し

1. ライブラリの読み込み

build.gradle
implementation 'com.google.android.material:material:1.0.0'

2. ボトムシートのレイアウト追加

fragment_bottom_sheet.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">

    <androidx.appcompat.widget.AppCompatTextView
            android:layout_width="wrap_content"
            android:layout_height="200dp"
            android:layout_gravity="center"
            android:text="ボトムシート"/>
</LinearLayout>

3.ボトムシートを呼び出すボタン追加

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.appcompat.widget.LinearLayoutCompat
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="horizontal"
        android:gravity="center"
        tools:context=".MainActivity">

    <androidx.appcompat.widget.AppCompatButton
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="TEST" android:id="@+id/btn"/>

</androidx.appcompat.widget.LinearLayoutCompat>

4. ボトムシートの呼び出し

  • BottomSheetDialogFragment を継承したクラスを作る
  • onCreateView でレイアウトと紐づける
  • タップで呼び出す
BottomSheetFragment.kt
class MyBottomSheet():BottomSheetDialogFragment() {
    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        var view = inflater.inflate(R.layout.fragment_bottom_sheet,container,false)
        return view
    }
}
MainActivity.kt
class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        btn.setOnClickListener {
            val myBottomSheet = MyBottomSheet()
            myBottomSheet.show(supportFragmentManager,"navigation_bottom_sheet")
        }
    }
}

おわり

1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?