Как перейти к чипу при нажатии в режиме горизонтальной прокрутки? - PullRequest
2 голосов
/ 14 июля 2020

У меня есть HorizontalScrollView с ChipGroup и некоторыми чипами. Когда я проверяю Чип, который вырезан из экрана, я хочу, чтобы ScrollView привязался и полностью отобразил его.

Вот как он выглядит, когда я его выбираю.

Мой файл макета выглядит так:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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"
    android:background="@color/colorWhite"
    android:theme="@style/Theme.MaterialComponents">

    <FrameLayout
        android:id="@+id/fragment_container"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginTop="165dp" />

    <LinearLayout
        android:id="@+id/linear_layout"
        android:layout_width="match_parent"
        android:layout_height="45dp"
        android:layout_marginTop="120dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <HorizontalScrollView
            android:id="@+id/scroll_view"
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <com.google.android.material.chip.ChipGroup
                android:id="@+id/chip_group"
                android:layout_width="wrap_content"
                android:layout_height="match_parent"
                app:chipSpacingHorizontal="10dp"
                app:singleLine="true"
                app:singleSelection="true"
                app:selectionRequired="true">

                <com.google.android.material.chip.Chip
                    android:id="@+id/chip_all"
                    android:layout_width="wrap_content"
                    android:layout_height="44dp"
                    android:layout_marginLeft="15dp"
                    android:backgroundTint="@color/indicator_chips"
                    android:checkable="true"
                    app:chipCornerRadius="10dp"
                    android:text="ALL"
                    android:textColor="@color/indicator_text"
                    app:checkedIconEnabled="false"
                    app:chipStrokeColor="@color/indicator_stroke"
                    app:chipStrokeWidth="1dp" />

                <com.google.android.material.chip.Chip
                    android:id="@+id/chip_watching"
                    android:layout_width="wrap_content"
                    android:layout_height="44dp"
                    android:checkable="true"
                    android:text="WATCHING"
                    android:textColor="@color/indicator_text"
                    app:chipCornerRadius="10dp"
                    app:checkedIconEnabled="false"
                    android:backgroundTint="@color/indicator_chips"
                    app:chipStrokeColor="@color/indicator_stroke"
                    app:chipStrokeWidth="1dp" />

                <com.google.android.material.chip.Chip
                    android:id="@+id/chip_completed"
                    android:layout_width="wrap_content"
                    android:layout_height="44dp"
                    android:checkable="true"
                    android:text="COMPLETED"
                    android:textColor="@color/indicator_text"
                    app:chipCornerRadius="10dp"
                    app:checkedIconEnabled="false"
                    android:backgroundTint="@color/indicator_chips"
                    app:chipStrokeColor="@color/indicator_stroke"
                    app:chipStrokeWidth="1dp" />

                <com.google.android.material.chip.Chip
                    android:id="@+id/chip_onhold"
                    android:layout_width="wrap_content"
                    android:layout_height="44dp"
                    android:checkable="true"
                    android:text="ON HOLD"
                    android:textColor="@color/indicator_text"
                    app:chipCornerRadius="10dp"
                    app:checkedIconEnabled="false"
                    android:backgroundTint="@color/indicator_chips"
                    app:chipStrokeColor="@color/indicator_stroke"
                    app:chipStrokeWidth="1dp" />

                <com.google.android.material.chip.Chip
                    android:id="@+id/chip_dropped"
                    android:layout_width="wrap_content"
                    android:layout_height="44dp"
                    android:checkable="true"
                    android:text="DROPPED"
                    android:textColor="@color/indicator_text"
                    app:chipCornerRadius="10dp"
                    app:checkedIconEnabled="false"
                    android:backgroundTint="@color/indicator_chips"
                    app:chipStrokeColor="@color/indicator_stroke"
                    app:chipStrokeWidth="1dp" />

                <com.google.android.material.chip.Chip
                    android:id="@+id/chip_plantowatch"
                    android:layout_width="wrap_content"
                    android:layout_height="44dp"
                    android:layout_marginRight="15dp"
                    android:checkable="true"
                    android:text="PLAN TO WATCH"
                    android:textColor="@color/indicator_text"
                    app:chipCornerRadius="10dp"
                    app:checkedIconEnabled="false"
                    android:backgroundTint="@color/indicator_chips"
                    app:chipStrokeColor="@color/indicator_stroke"
                    app:chipStrokeWidth="1dp" />

            </com.google.android.material.chip.ChipGroup>

        </HorizontalScrollView>

    </LinearLayout>

</androidx.constraintlayout.widget.ConstraintLayout>

И мой файл класса:

public class LibraryFragment extends Fragment {

    private HorizontalScrollView scrollView;
    Chip chip_dropped;
    ChipGroup chipGroup;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_library_anime, container, false);
        return view;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {

        scrollView = view.findViewById(R.id.scroll_view);
        chipGroup = view.findViewById(R.id.chip_group);

        chipGroup.setOnCheckedChangeListener(checkedListener);
    }

    ChipGroup.OnCheckedChangeListener checkedListener = new ChipGroup.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(ChipGroup group, int checkedId) {
            FragmentTransaction fragmentTransaction = getActivity().getSupportFragmentManager().beginTransaction();
            switch (group.getCheckedChipId()) {
                case R.id.chip_all:
                    fragmentTransaction.replace(R.id.fragment_container, new ListALL()).commit();
                    break;
                case R.id.chip_watching:
                    fragmentTransaction.replace(R.id.fragment_container, new ListWATCHING()).commit();
                    break;
                case R.id.chip_completed:
                    fragmentTransaction.replace(R.id.fragment_container, new ListCOMPLETED()).commit();
                    break;
                case R.id.chip_onhold:
                    fragmentTransaction.replace(R.id.fragment_container, new ListONHOLD()).commit();
                    break;
                case R.id.chip_dropped:
                    fragmentTransaction.replace(R.id.fragment_container, new ListDROPPED()).commit();
                    break;
                case R.id.chip_plantowatch:
                    fragmentTransaction.replace(R.id.fragment_container, new ListPLANTOWATCH()).commit();
                    break;
            }

        }
    };
}

Итак, повторюсь, я пытаюсь заставить свой ScrollView прокручивать до чипа, когда по нему щелкают, как в магазине игр с его. Я пробовал .scroolTo и .smoothScrollTo, но ничего из этого не работает.

Ответы [ 2 ]

3 голосов
/ 14 июля 2020

Я сделал для Вас образец проекта. Думаю, вы можете легко преобразовать его в свое приложение.

MainActivity. java

public class MainActivity extends AppCompatActivity
{
    HorizontalScrollView scroll;
    int widthScreen;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        DisplayMetrics displayMetrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
        widthScreen = displayMetrics.widthPixels;

        scroll = findViewById(R.id.scroll);

        LinearLayout linearLayout = findViewById(R.id.linLay);
        for (int index = 0; index <= linearLayout.getChildCount() - 1; index++)
        {
            linearLayout.getChildAt(index).setOnClickListener(new View.OnClickListener()
            {
                @Override
                public void onClick(View v)
                {
                    Rect r = new Rect();
                    v.getGlobalVisibleRect(r);

                    if (r.right == widthScreen)
                    {
                        Rect rr = new Rect();
                        v.getDrawingRect(rr);
                        scroll.smoothScrollBy(rr.right - (widthScreen - r.left), 0);
                    }
                    else if (r.left == 0)
                    {
                        Rect rr = new Rect();
                        v.getDrawingRect(rr);
                        scroll.smoothScrollBy(rr.right - (widthScreen - r.right), 0);
                    }
                }
            });
        }
    }
}

MainActivity. XML (только кнопки в ScrollView )

<HorizontalScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/scroll"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <LinearLayout
        android:id="@+id/linLay"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="1" />

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="2" />

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="3" />

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="4" />

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="5" />

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="6" />

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="7" />

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="8" />

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="9" />

    </LinearLayout>

</HorizontalScrollView>

Когда вы нажимаете кнопку, которая не полностью отображается на экране, ScrollView будет прокручен до нужного положения, чтобы отобразить полную кнопку.

1 голос
/ 14 июля 2020

Используя код, который опубликовал @iknow, я изменяю его, чтобы он работал точно так же, как игровой магазин с его фишками

 @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {

        chipGroup = view.findViewById(R.id.chip_group);

        final Chip chip_all = view.findViewById(R.id.chip_all);
        final Chip chip_watching = view.findViewById(R.id.chip_watching);
        final Chip chip_completed = view.findViewById(R.id.chip_completed);
        final Chip chip_onhold = view.findViewById(R.id.chip_onhold);
        final Chip chip_dropped = view.findViewById(R.id.chip_dropped);
        final Chip chip_plantowatch = view.findViewById(R.id.chip_plantowatch);

        DisplayMetrics displayMetrics = new DisplayMetrics();
        getActivity().getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
        widthScreen = displayMetrics.widthPixels;

        scrollView = view.findViewById(R.id.scroll_view);
        chipGroup = view.findViewById(R.id.chip_group_anime);
        for (int index = 0; index <= chipGroup.getChildCount() - 1; index++) {
            chipGroup.getChildAt(index).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Rect r = new Rect();
                    view.getGlobalVisibleRect(r);

                    if(chip_all.isChecked()) {
                        Rect rr = new Rect();
                        view.getDrawingRect(rr);
                        scrollView.smoothScrollBy(rr.right - (widthScreen - r.right), 0);
                    }

                    if(chip_watching.isChecked()) {
                        Rect rr = new Rect();
                        view.getDrawingRect(rr);
                        scrollView.smoothScrollBy(rr.right - (widthScreen - r.right), 0);
                    }


                    if(chip_completed.isChecked()) {
                        scrollView.smoothScrollTo(chip_completed.getLeft() - (widthScreen / 2) + (chip_completed.getWidth() / 2), 0);
                    }

                    if(chip_onhold.isChecked()) {
                        scrollView.smoothScrollTo(chip_onhold.getLeft() - (widthScreen / 2) + (chip_onhold.getWidth() / 2), 0);
                    }


                    if(chip_dropped.isChecked()) {
                        Rect rr = new Rect();
                        view.getDrawingRect(rr);
                        scrollView.smoothScrollBy(r.right, 0);
                    }

                    if(chip_plantowatch.isChecked()) {
                        Rect rr = new Rect();
                        view.getDrawingRect(rr);
                        scrollView.smoothScrollBy(r.right, 0);
                    }
                }
            });
        }

    }

Конечный продукт выглядит так.

Конечный продукт выглядит как на гифке выше, и еще раз спасибо @iknow, предоставившему код!

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...