首页 > 解决方案 > 如何在将在 RecyclerView 中添加卡片的片段中设置 OnclickListener FAB

问题描述

我正在尝试添加一个 FAB,如果单击 FAB 位于它包含 recyclerview 的片段中,它将向回收器视图添加一张卡片

这是我的适配器

    package com.example.tmcpm;

    import android.content.Context;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.Button;
    import android.widget.TextView;
    import android.widget.Toast;

    import                 com.google.android.material.floatingactionbutton.FloatingActionButton;

    import java.util.List;

    import androidx.annotation.NonNull;
    import androidx.recyclerview.widget.RecyclerView;

    public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.MyViewHolder> {

Context mContext ;
List<MediCard> mData;


public RecyclerViewAdapter(Context mContext, List<MediCard> mData) {
    this.mContext = mContext;
    this.mData = mData;
}

@NonNull
@Override
public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {

    View v ;
    v = LayoutInflater.from(mContext).inflate(R.layout.fragment_medicard_recycler,parent,false);
    MyViewHolder vHolder = new MyViewHolder(v);


    return vHolder;
}

@Override
public void onBindViewHolder(@NonNull MyViewHolder holder, final int position) {

    int currentPosition = position;
    final MediCard infoData = mData.get(position);


    holder.tv_num.setText(mData.get(position).getMediCardNumber());

    holder.buttonDelete.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Toast.makeText(mContext,"Deleted Medication" , Toast.LENGTH_SHORT).show();

           removeItem(infoData);
        }

        private void removeItem(MediCard infoData) {

            int currPosition = mData.indexOf(infoData);
            mData.remove(currPosition);
            notifyItemRemoved(currPosition);
            notifyItemRangeChanged(currPosition,mData.size());
            notifyDataSetChanged();
        }


    });

  /* holder.buttonAdd.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Toast.makeText(mContext,"ADDING", Toast.LENGTH_SHORT).show();
        }
    });*/

}

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

public static class MyViewHolder extends RecyclerView.ViewHolder {

    private TextView tv_num;
    private Button buttonDelete;
    public FloatingActionButton buttonAdd;


    public MyViewHolder(@NonNull View itemView) {
        super(itemView);

        tv_num = (TextView) itemView.findViewById(R.id.word);
        buttonDelete = (Button) itemView.findViewById(R.id.buttonDelete);
        buttonAdd = (FloatingActionButton) itemView.findViewById(R.id.floatButtonAdd);

    }
}

}

这是我的选项卡式活动 Java

    package com.example.tmcpm;

    import android.os.Bundle;
    import android.view.LayoutInflater;
    import android.view.Menu;
    import android.view.MenuItem;
    import android.view.View;
    import android.view.ViewGroup;

    import com.google.android.material.tabs.TabLayout;

    import java.util.ArrayList;
    import java.util.List;

    import androidx.appcompat.app.AppCompatActivity;
    import androidx.fragment.app.Fragment;
    import androidx.fragment.app.FragmentManager;
    import androidx.fragment.app.FragmentPagerAdapter;
    import androidx.recyclerview.widget.LinearLayoutManager;
    import androidx.recyclerview.widget.RecyclerView;
    import androidx.viewpager.widget.ViewPager;

    public class Prescribe extends AppCompatActivity {

       // private final LinkedList<String> mWordList = new LinkedList<>();

private RecyclerView myrecyclerview;
private List<MediCard> lstnum;
/**
 * The {@link androidx.viewpager.widget.PagerAdapter} that will provide
 * fragments for each of the sections. We use a
 * {@link FragmentPagerAdapter} derivative, which will keep every
 * loaded fragment in memory. If this becomes too memory intensive, it
 * may be best to switch to a
 * androidx.fragment.app.FragmentStatePagerAdapter.
 */
private SectionsPagerAdapter mSectionsPagerAdapter;

/**
 * The {@link ViewPager} that will host the section contents.
 */
private ViewPager mViewPager;

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



    //Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    //setSupportActionBar(toolbar);
    // Create the adapter that will return a fragment for each of the three
    // primary sections of the activity.
    mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());

    // Set up the ViewPager with the sections adapter.
    mViewPager = (ViewPager) findViewById(R.id.container);
    mViewPager.setAdapter(mSectionsPagerAdapter);

    TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);

    mViewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
    tabLayout.addOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(mViewPager));


   /* for (int i = 1; i < 6; i++) {
        mWordList.addLast("Medicine # " + i);
    }*/
    ;




}


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

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

/**
 * A placeholder fragment containing a simple view.
 */
public static class PlaceholderFragment extends Fragment {
    /**
     * The fragment argument representing the section number for this
     * fragment.
     */
    private static final String ARG_SECTION_NUMBER = "section_number";


    public PlaceholderFragment() {
    }

    /**
     * Returns a new instance of this fragment for the given section
     * number.
     */
    public static PlaceholderFragment newInstance(int sectionNumber) {
        PlaceholderFragment fragment = new PlaceholderFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_SECTION_NUMBER, sectionNumber);
        fragment.setArguments(args);
        return fragment;
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        RecyclerView myrecyclerview;
        List<MediCard> mData = new ArrayList<>();



        mData.add(new MediCard("Medication 1"));
        mData.add(new MediCard("Medication 2"));
        mData.add(new MediCard("Medication 3"));
        mData.add(new MediCard("Medication 4    "));


        View rootView = null;
        switch(getArguments().getInt(ARG_SECTION_NUMBER)){
            case 1:
                //do something

                rootView = inflater.inflate(R.layout.fragment_prescribe, container, false);

                break;

            case 2:
                //do something
                rootView = inflater.inflate(R.layout.medicard_fragment,container,false);
                myrecyclerview = rootView.findViewById(R.id.medicard_recyclerview);
                RecyclerViewAdapter recyclerAdapter = new RecyclerViewAdapter(getContext(),mData);
                myrecyclerview.setLayoutManager(new LinearLayoutManager(getActivity()));
                myrecyclerview.setAdapter(recyclerAdapter);
                new FragmentMedicard();


                break;

            case 3:
                rootView = inflater.inflate(R.layout.medicard_fragment, container, false);
                break;
        }

        //TextView textView = (TextView) rootView.findViewById(R.id.section_label);
       // textView.setText(getString(R.string.section_format, getArguments().getInt(ARG_SECTION_NUMBER)));
        return rootView;
    }
}




/**
 * A {@link FragmentPagerAdapter} that returns a fragment corresponding to
 * one of the sections/tabs/pages.
 */
public class SectionsPagerAdapter extends FragmentPagerAdapter {

    public SectionsPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {
        // getItem is called to instantiate the fragment for the given page.
        // Return a PlaceholderFragment (defined as a static inner class below).
        return PlaceholderFragment.newInstance(position + 1);
    }

    @Override
    public int getCount() {
        // Show 3 total pages.
        return 3;
    }
}

}

和包含 recyclerView Java 的 Fragment

    package com.example.tmcpm;

    import android.content.Context;
    import android.os.Bundle;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.Toast;

    import com.google.android.material.floatingactionbutton.FloatingActionButton;

    import java.util.List;

    import androidx.fragment.app.Fragment;
    import androidx.recyclerview.widget.RecyclerView;

    public class FragmentMedicard extends Fragment implements View.OnClickListener {


View v;
private RecyclerView myrecyclerview;
private List<MediCard> mData;
FloatingActionButton fabAdd;
Context mContext;


public View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedinstanceState) {
    View myView = inflater.inflate(R.layout.medicard_fragment, container, false);
    fabAdd = (FloatingActionButton) myView.findViewById(R.id.floatButtonAdd);
    fabAdd.setOnClickListener(this);
    return myView;
}



@Override
public void onClick(View v) {
    Toast.makeText(mContext,"ADDING", Toast.LENGTH_SHORT).show();
}

}

我真的不知道该怎么办了

标签: javaandroidandroid-fragmentsandroid-recyclerviewfloating-action-button

解决方案


创建一个实例变量以将您的 recyclerAdapter 保存在您的片段中。然后您可以让 FAB 点击监听器将 MediaCard 添加到 mData。

然后打电话

recyclerAdapter.notifyDataSetChanged();

推荐阅读