0
1

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 3 years have passed since last update.

【Android】Snackbarを任意の位置から表示させる

Last updated at Posted at 2020-03-10

#概要
Snackbarを画面の下部から出すのではなく、任意の位置から表示させる

#レイアウトファイルでCoordinatorLayoutを入れる

fragment_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"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <androidx.coordinatorlayout.widget.CoordinatorLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <Button
            android:id="@+id/button"
            android:layout_width="match_parent"
            android:layout_height="100dp"
            android:layout_marginTop="200dp"
            android:gravity="center" />

     </androidx.coordinatorlayout.widget.CoordinatorLayout>

</LinearLayout>

Snackbarを表示させたいViewをCoordinatorLayoutでラップする

#Snackbarの実装

build.gradle
dependencies {
    implementation 'com.google.android.material:material:1.1.0'
}

Snackbarを使うためにbuild.gradlecom.google.android.materialimplementationする
※バージョンはよしなに変えてください

MainFragment.java

import com.google.android.material.snackbar.Snackbar;

@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
    Button button = view.findViewById(R.id.button);
    button.setText("button");
    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            showSnackbar("test");
        }
    });
    super.onViewCreated(view, savedInstanceState);
}

private void showSnackbar(String message) {
    View view = getView();
    if (view == null) return;

    Snackbar snackbar = Snackbar.make(view.findViewById(R.id.button), message, Snackbar.LENGTH_SHORT);
    snackbar.show();
}

Snackbar表示用のメソッドを作成
Snackbar.makeの第一引数を表示させたい位置のViewのidにする(今回はButton
ボタンを押した時にボタンのViewの下からSnackbarを出すようにする

余分な記載が多いし、もうちょっと良い方法があると思うけど備忘録なので一旦これでいいかな。。

0
1
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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?