RecyclerView не заменяет панель сведений фрагментом при щелчке элемента - PullRequest
0 голосов
/ 26 октября 2018

Каждый раз, когда я щелкаю элемент просмотра рециркулятора на планшете, он открывает действие, а не заменяет панель сведений фрагментом.

Следующая строка кода используется для определения, где находится панель сведений.настоящее время:

mTwoPane = Objects.requireNonNull(getActivity()).findViewById(R.id.detail_container) != null;

Есть какие-нибудь идеи о правильном расположении, чтобы поместить эту строку кода?

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.widget.Toolbar
        android:id="@+id/masterToolbar"
        android:layout_width="match_parent"
        android:layout_height="?actionBarSize"
        >


        <LinearLayout
            android:id="@+id/singleline_text_layout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center_vertical"
            android:orientation="vertical">

            <TextView
                android:id="@+id/md_toolbar_title"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                style="@android:style/TextAppearance.Material.Widget.ActionBar.Title"/>
        </LinearLayout>

    </android.widget.Toolbar>


    <RelativeLayout
        android:id="@+id/master_container"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        />

</LinearLayout>

sw600dp активность XML

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.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.widget.Toolbar
        android:id="@+id/masterToolbar"
        android:layout_width="0dp"
        android:layout_height="?actionBarSize"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toStartOf="@+id/detailBackgroundToolbar"
        app:layout_constraintHorizontal_weight="2"
        app:layout_constraintTop_toTopOf="parent">


        <LinearLayout
            android:id="@+id/singleline_text_layout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center_vertical"
            android:orientation="vertical">

            <TextView
                android:id="@+id/md_toolbar_title"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                style="@android:style/TextAppearance.Material.Widget.ActionBar.Title"/>
        </LinearLayout>

    </android.widget.Toolbar>


    <RelativeLayout
        android:id="@+id/master_container"
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:layout_constraintHorizontal_weight="2"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toStartOf="@+id/divider"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/masterToolbar" />

    <View
        android:id="@+id/divider"
        android:layout_width="1dp"
        android:layout_height="0dp"
        android:background="?attr/dividerColor"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toEndOf="@+id/masterToolbar"
        app:layout_constraintTop_toBottomOf="@+id/masterToolbar" />

    <android.widget.Toolbar
        android:id="@+id/detailBackgroundToolbar"
        android:layout_width="0dp"
        android:layout_height="?actionBarSize"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_weight="3"
        app:layout_constraintStart_toEndOf="@+id/masterToolbar"
        app:layout_constraintTop_toTopOf="parent" />

    <android.support.v7.widget.CardView
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_margin="4dp"
        app:cardCornerRadius="0dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toEndOf="@+id/divider"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintWidth_percent="0.5">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical">

            <include layout="@layout/toolbar_dualline"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"/>

            <FrameLayout
                android:id="@+id/detail_container"
                android:layout_width="match_parent"
                android:layout_height="match_parent" />

        </LinearLayout>

    </android.support.v7.widget.CardView>

    <View
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toEndOf="@+id/divider"
        app:layout_constraintTop_toBottomOf="@+id/detailBackgroundToolbar" />

</android.support.constraint.ConstraintLayout>

класс фрагмента

public class MyFragment extends Fragment {

    public MyFragment() {}

    List<Product> wcList;

    RecyclerView mRecyclerView;

    /**
     * Whether or not the activity is in two-pane mode, i.e. running on a tablet device.
     */
    public boolean mTwoPane;

    public static MyFragment newInstance() {
        return new MyFragment();
    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.activity_main, container, false);
        mTwoPane = Objects.requireNonNull(getActivity()).findViewById(R.id.detail_container) != null;

        mRecyclerView = view.findViewById(R.id.recyclerView_list);
        mRecyclerView.setHasFixedSize(true);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this.getActivity()));
        mRecyclerView.addItemDecoration(new DividerItemDecoration(Objects.requireNonNull(getContext()), LinearLayout.VERTICAL));

        myList = new ArrayList<>();

        String[] items = getResources().getStringArray(R.array.product_names);
        String[] itemDescriptions = getResources().getStringArray(R.array.product_descriptions);
        for (int n = 0; n < items.length; n++){
            Product desserts = new Product();
            desserts.setProductName(items[n]);
            wdessertsc.setProductDescriptions(itemDescriptions[n]);
            myList.add(desserts);
        }

        MyListAdapter listAdapter = new MyListAdapter(getActivity(), myList);

        mRecyclerView.setAdapter(listAdapter);

        return view;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        mTwoPane = Objects.requireNonNull(getActivity()).findViewById(R.id.detail_container) != null;

        super.onActivityCreated(savedInstanceState);
    }
}

класс адаптера

    public class MyListAdapter extends RecyclerView.Adapter<MyListAdapter.MyViewHolder> {
        public boolean mTwoPane;

        private Context mCtx;

        private List<Product> myList;

        public MyListAdapter(Context mCtx, List<Product> myList) {
            this.mCtx = mCtx;
            this.myList = myList;
        }

        @NonNull
        @Override
        public MyListAdapter.MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            LayoutInflater inflater = LayoutInflater.from(mCtx);
            View view = inflater.inflate(R.layout.listitem_dualline, parent,false);
            return new MyListAdapter.MyViewHolder(view);
        }

        @Override
        public void onBindViewHolder(@NonNull final MyListAdapter.MyViewHolder holder, final int position) {
            Log.d(TAG, "onBindViewHolder: called.");

            final Product product = myList.get(holder.getAdapterPosition());

            holder.textviewTitle.setText(product.getProductName());
            holder.textviewSubtitle.setText(product.getPRoductDescription());


            holder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (mTwoPane) {
                        Fragment newFragment;
                        if (product.getStationName().equals(v.getResources().getString(R.string.product_1))) {
                            newFragment = new FragmentProduct1();
                        } else {
                            newFragment = new FragmentProdcut2();
                        }
                        MyActivity activity = (MyActivity) v.getContext();
                        FragmentTransaction transaction = activity.getSupportFragmentManager().beginTransaction();
                        transaction.replace(R.id.detail_container, newFragment);
                        transaction.commit();
                    } else {
                        Intent intent;
                        if (product.getStationName().equals(v.getResources().getString(R.string.product_1))) {
                            intent = new Intent(v.getContext(), Product1Activity.class);
                        } else {
                            intent = new Intent(v.getContext(), Product2Activity.class);
                        }
                        mCtx.startActivity(intent);
                    }
                }
            });
        }

        @Override
        public int getItemCount() {
            return myList.size();
        }

        class MyViewHolder extends RecyclerView.ViewHolder {
            RelativeLayout relativeLayout;
            TextView textviewTitle, textviewSubtitle;

            StationViewHolder(View itemView) {
                super(itemView);

                mTwoPane = itemView.findViewById(R.id.detail_container) != null;

                relativeLayout = itemView.findViewById(R.id.listitem_relativelayout);
                textviewTitle = itemView.findViewById(R.id.listitem_title);
                textviewSubtitle = itemView.findViewById(R.id.listitem_subtitle);
            }
    }
}

Ответы [ 2 ]

0 голосов
/ 26 октября 2018

Я думаю, что вы проверяете элемент два сковородки с элементом повторного просмотра xml

mTwoPane = itemView.findViewById(R.id.detail_container) != null;

То, что вы можете проверить при построении адаптера в программе recyclerview и сохранить его из самого представления содержимого деятельности.

0 голосов
/ 26 октября 2018

Эта строка mTwoPane = itemView.findViewById(R.id.detail_container) != null; от вашего держателя просмотра всегда будет false .

Почему?

Потому что ваш detail_container не является частью контейнера элемента вашего держателя вида, поэтому itemView всегда будет возвращать null на ваш взгляд.вместо этого передайте свой логический флаг из вашего фрагмента в ваш адаптер!

...