繁体   English   中英

如何在 recyclerview 适配器中为 Activity 扩展上下文

[英]How do I extablish context for an Activity within a recyclerview adapter

我在活动中的片段内的回收视图的行中有按钮。 当用户单击其中一个按钮时,我想切换到不同的活动。 如何为 Intent 建立上下文以切换到新活动。

或者,我是否应该将 onClickListener 移回片段或活动(将 onClickListener 放在 recyclerview 适配器代码中是否不正确)。 如果是这样,我如何获取对从 recyclerview 适配器外部单击的按钮的引用。

这是片段代码(CheckInRecentList.java)

package com.example.checkingin;
import android.app.Application;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;

import android.net.Uri;
import android.os.Bundle;

import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import android.widget.TextView;



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

import java.util.List;

import static androidx.constraintlayout.widget.Constraints.TAG;

/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link CheckInRecentList.OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link CheckInRecentList#newInstance} factory method to
 * create an instance of this fragment.
 */
public class CheckInRecentList extends Fragment {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    private RecyclerView recyclerView;
    private RecyclerView.Adapter checkInListAdapter;
    //private RecyclerView.LayoutManager layoutManager;
    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;
    private MainViewModel mViewModel;
    private CheckInListAdapter mAdapter;
    private MainViewModelProviderFactory viewModelFactory;
    private TextView checkInLastDateTime;
    private TextView checkInTitle;
    private TextView checkInDestinationName;
    private TextView checkInComments;
    private Context context;

    private OnFragmentInteractionListener mListener;

    public CheckInRecentList() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment CheckInRecentList.
     */
    // TODO: Rename and change types and number of parameters
    public static CheckInRecentList newInstance(String param1, String param2) {
        CheckInRecentList fragment = new CheckInRecentList();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.i(TAG, "onCreate: On Create");
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }

            }

   @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

       mViewModel = new ViewModelProvider(this, viewModelFactory).get(MainViewModel.class);
       Log.i(TAG, "onCreateView: On Create View"); 
       // Inflate the layout for this fragment
              return inflater.inflate(R.layout.fragment_check_in_recent_list, container, false);



    }

    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        Log.i(TAG, "onButtonPressed: ");
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onAttach(Context context) {

        super.onAttach(context);

        Log.i(TAG, "onAttach: OnAttach");

        viewModelFactory = new MainViewModelProviderFactory(context.getApplicationContext());
        mViewModel = new ViewModelProvider(this, viewModelFactory).get(MainViewModel.class);

        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
       Log.i(TAG,"OnAttach completed");
    }
    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
       super.onActivityCreated(savedInstanceState);

       Log.i(TAG, "onActivityCreated: On Activity Created");


       mViewModel = new ViewModelProvider(this, viewModelFactory).get(MainViewModel.class);

       mAdapter = new CheckInListAdapter(R.layout.fragment_check_in_recent_list);
       RecyclerView recyclerView = getView().findViewById(R.id.check_in_recent_recycler_view);
       recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
       recyclerView.setAdapter(mAdapter);
       recyclerView.addItemDecoration(new DividerItemDecoration(getContext(),
               LinearLayoutManager.VERTICAL));

        observerSetup();
        Log.i(TAG, "onActivityCreated: Observer SetUp");

        ItemTouchHelper.SimpleCallback callback = new
            ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.RIGHT | ItemTouchHelper.LEFT) {


                public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
                    return false;
                }

                @Override
                public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {

                    int position = viewHolder.getAdapterPosition();

                    mAdapter.deleteItem(position);
                    Snackbar snackbar = Snackbar.make(viewHolder.itemView, "Item " + (direction == ItemTouchHelper.RIGHT ? "deleted" : "archived") + ".", Snackbar.LENGTH_LONG);
                    snackbar.setAction(android.R.string.cancel, new View.OnClickListener() {

                        @Override
                        public void onClick(View view) {
                            mAdapter.undoDelete();
                        }
                    });
                    snackbar.show();
                    }
                    @Override
                    public void onChildDraw (Canvas c, RecyclerView
                    recyclerView, RecyclerView.ViewHolder viewHolder,float dX, float dY,
                    int actionState, boolean isCurrentlyActive){
                        new RecyclerViewSwipeDecorator.Builder(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive)
                                .addSwipeLeftBackgroundColor(ContextCompat.getColor(getContext(), R.color.recycler_view_item_swipe_left_background))
                                .addSwipeLeftActionIcon(R.drawable.ic_archive_white_24dp)
                                .addSwipeRightBackgroundColor(ContextCompat.getColor(getContext(), R.color.recycler_view_item_swipe_right_background))
                                .addSwipeRightActionIcon(R.drawable.ic_delete_white_24dp)
                                .addSwipeRightLabel(getString(R.string.action_delete))
                                .setSwipeRightLabelColor(Color.WHITE)
                                .addSwipeLeftLabel(getString(R.string.action_archive))
                                .setSwipeLeftLabelColor(Color.WHITE)
                                .create()
                                .decorate();
                        super.onChildDraw(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive);
                    }
                };

        ItemTouchHelper itemTouchHelper = new ItemTouchHelper(callback);
        itemTouchHelper.attachToRecyclerView(recyclerView);

        CustomToast newtoast = new CustomToast(getContext(),"you clicked on this" );
        newtoast.show();

    }

    @Override
    public void onDetach() {
        super.onDetach();
        Log.i(TAG, "onDetach: ");
        mListener = null;

    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }
    private void clearFields() {
        checkInLastDateTime.setText("");
        checkInDestinationName.setText("");
        checkInTitle.setText("");
        checkInComments.setText("");
    }




    private void observerSetup() {
        Log.i(TAG, "observerSetup:");
        checkInLastDateTime = getView().findViewById(R.id.checkInLastDateTime);
        checkInTitle = getView().findViewById(R.id.checkInTitle);
        checkInDestinationName = getView().findViewById(R.id.checkInDestinationName);
        checkInComments = getView().findViewById(R.id.checkInComments);
        if(mViewModel.getAllCheckIn() != null)
            mViewModel.getAllCheckIn().observe(getViewLifecycleOwner(), new Observer<List<CheckInTable>>(){
                @Override
                public void onChanged(@Nullable final List<CheckInTable> allCheckIn) {
                    mAdapter.setCheckInList(allCheckIn);
            }
        });

    }

 }

这是recyclerview适配器代码

package com.example.checkingin;


import android.app.Activity;
import android.content.Context;

import android.content.Intent;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.coordinatorlayout.widget.CoordinatorLayout;
import androidx.recyclerview.widget.RecyclerView;

import java.util.List;

import static androidx.constraintlayout.widget.Constraints.TAG;


public class CheckInListAdapter extends RecyclerView.Adapter<CheckInListAdapter.ViewHolder>{
    private int checkInListLayout;
    private List<CheckInTable> checkInList;
    private CoordinatorLayout coordinatorLayout;
    private RecyclerView recyclerView;
    private CheckInTable mRecentlyDeletedItem;
    private int mCheckInTablePrimaryKey;
    private int mRecentlyDeletedItemPosition;
    private Context context;


    public CheckInListAdapter(int layoutId) {
        Log.i(TAG, "CheckInListAdapter: ");
        checkInListLayout = layoutId;
    }

    public void setCheckInList(List<CheckInTable> allCheckIn) {
        checkInList = allCheckIn;
        Log.i(TAG, "setCheckInList: ");
        notifyDataSetChanged();
    }
    public void deleteItem(int position) {
        mRecentlyDeletedItem = checkInList.get(position);
        mRecentlyDeletedItemPosition = position;
        checkInList.remove(position);
        notifyItemRemoved(position);
    }

    public void undoDelete() {
        checkInList.add(mRecentlyDeletedItemPosition,
                mRecentlyDeletedItem);
        notifyItemInserted(mRecentlyDeletedItemPosition);
    }
    @Override
    public int getItemCount() {
        return checkInList == null ? 0 : checkInList.size();
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        Log.i(TAG, "onCreateViewHolder: ");
        View view = LayoutInflater.from(
                parent.getContext()).inflate(R.layout.recycler_view_item, parent, false);
        ViewHolder checkInListViewHolder = new ViewHolder(view);
        return checkInListViewHolder;
    }

    @Override
    public void onBindViewHolder(final ViewHolder holder, final int listPosition) {

        TextView checkInTablePrimaryKey = holder.checkInTablePrimaryKey;
        TextView checkInLastDateTime = holder.checkInLastDateTime;
        TextView checkInTitle = holder.checkInTitle;
        TextView checkInDestinationName = holder.checkInDestinationName;
        TextView checkInComments = holder.checkInComments;
        holder.checkInEditButton.setImageResource(R.drawable.ic_menu_edit);
        holder.checkInResendButton.setImageResource(R.drawable.ic_menu_share);


        Log.i(TAG, "onBindViewHolder: ");

        //checkInTablePrimaryKey.setText(checkInList.get(listPosition).getCheckInTablePrimaryKey());
        checkInLastDateTime.setText(checkInList.get(listPosition).getCheckInLastDateTime());
        checkInTitle.setText(checkInList.get(listPosition).getCheckInTitle());
        checkInDestinationName.setText(checkInList.get(listPosition).getCheckInDestinationName());
        checkInComments.setText(checkInList.get(listPosition).getCheckInComments());

        ImageView checkInEditButton = holder.checkInEditButton;
        ImageView checkInResendButton = holder.checkInResendButton;

        ImageButton editCheckInButton = checkInEditButton.findViewById(R.id.checkInEditButton);
        ImageButton resendCheckInButton = checkInResendButton.findViewById(R.id.checkInResendButton);

        editCheckInButton.setOnClickListener(new View.OnClickListener() {
             @Override
             public void onClick(View view) {
             //put in edit check in logic

                 Integer value = (checkInList.get(listPosition).getCheckInTablePrimaryKey());
                 Intent intent = new Intent(context, CheckInNew.class);
                 intent.putExtra("checkInTablePrimaryKey",value);
                 context.startActivity(intent);

                 //Bundle extras = getIntent().getExtras();
                 //if (extras != null) {
                 //    String value = extras.getInt("checkInTablePrimaryKey");
                     //The key argument here must match that used in the other activity
                 //}
            }
          });
        resendCheckInButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //put in resend logic

            }
        });

    }

    static class ViewHolder extends RecyclerView.ViewHolder {
        TextView  checkInTablePrimaryKey;
        TextView checkInLastDateTime;
        TextView checkInTitle;
        TextView checkInDestinationName;
        TextView checkInComments;
        ImageView checkInEditButton;
        ImageView checkInResendButton;
        ViewHolder(View itemView) {
            super(itemView);
            Log.i(TAG, "ViewHolder: ");
            checkInTablePrimaryKey = itemView.findViewById(R.id.checkInTablePrimaryKey);
            checkInLastDateTime = itemView.findViewById(R.id.checkInLastDateTime);
            checkInTitle = itemView.findViewById(R.id.checkInTitle);
            checkInDestinationName = itemView.findViewById(R.id.checkInDestinationName);
            checkInComments = itemView.findViewById(R.id.checkInComments);
            checkInEditButton = itemView.findViewById(R.id.checkInEditButton);
            checkInResendButton = itemView.findViewById(R.id.checkInResendButton);


        }
    }
}

这是活动代码 CheckIn.java

package com.example.checkingin;

import android.net.Uri;
import android.os.Bundle;


import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;
import android.view.View;
import android.view.Menu;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;
import com.google.android.material.tabs.TabLayout;


public class CheckIn extends AppCompatActivity implements
        CheckInRecentList.OnFragmentInteractionListener,
        CheckInApproveRequested.OnFragmentInteractionListener,
        CheckInSearch.OnFragmentInteractionListener {
    //private AdView mAdView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_check_in);

        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        FloatingActionButton fab = findViewById(R.id.fab);
        //MobileAds.initialize(this, new OnInitializationCompleteListener() {
        //    @Override
        //    public void onInitializationComplete(InitializationStatus initializationStatus) {
        //    }
        //});
        //mAdView = findViewById(R.id.adView);
        //AdRequest adRequest = new AdRequest.Builder().build();
        //mAdView.loadAd(adRequest);

        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });

        DrawerUtil.getDrawer(this,toolbar);
        configureTabLayout();

    }

    private void configureTabLayout() {
        TabLayout tabLayout = findViewById(R.id.check_in_main_tab_layout);

        tabLayout.addTab(tabLayout.newTab().setText("Recent"));
        tabLayout.addTab(tabLayout.newTab().setText("Approve Requested"));
        tabLayout.addTab(tabLayout.newTab().setText("Search"));

        final ViewPager viewPager = findViewById(R.id.check_in_main_pager);
        final PagerAdapter adapter = new CheckInMainPagerAdapter
                (getSupportFragmentManager(),
                        tabLayout.getTabCount());
        viewPager.setAdapter(adapter);

        viewPager.addOnPageChangeListener(new
                TabLayout.TabLayoutOnPageChangeListener(tabLayout));
        tabLayout.addOnTabSelectedListener(new
               TabLayout.OnTabSelectedListener() {
       @Override
       public void onTabSelected(TabLayout.Tab tab) {
                viewPager.setCurrentItem(tab.getPosition());
       }

       @Override
       public void onTabUnselected(TabLayout.Tab tab) {

       }

       @Override
       public void onTabReselected(TabLayout.Tab tab) {

       }

       });
    }

    @Override
    public void onFragmentInteraction(Uri uri) {
    }

    public boolean onCreateOptionsMenu(Menu menu) {
          // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.check_in, menu);
        return true;
    }
}

在 CheckInListAdapter 的构造函数中传递另一个参数作为上下文

public CheckInListAdapter(int layoutId, Context context) {
        Log.i(TAG, "CheckInListAdapter: ");
        checkInListLayout = layoutId;
        this.context = context
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM