如何在recyclerview和许多片段之间传递数据

时间:2018-02-04 10:59:56

标签: android android-recyclerview recycler-adapter

您好我有一个简单的应用程序,其中包含带有列表项的recyclerView(每个代表一个"员工"对象
 我使用tabhost使用这个tuto https://www.androidhive.info/2015/09/android-material-design-working-with-tabs/但是当我点击item recycleler视图时我想在其中一个标签中传递一些数据     recycleler view item ===>片段

this is xml fragment 

<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.iset.tse.Employee.OneFragment">

    <TextView
        android:id="@+id/textView3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="92dp"
        android:text="Information de contact :"
        android:textColor="?android:attr/statusBarColor"
        android:textSize="30sp"
        android:textStyle="bold"
        app:layout_constraintHorizontal_bias="0.312"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/name_emp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginTop="26dp"
        android:text="username"
        app:layout_constraintHorizontal_bias="0.204"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView3" />
</android.support.constraint.ConstraintLayout>



code Java



public class OneFragment extends Fragment


{


    TextView txt_name;

    public OneFragment() {}

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);




    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment

        txt_name=(TextView) txt_name.findViewById(R.id.name_emp);
        String name = getArguments().getString("name");
        txt_name.setText(name);
        return inflater.inflate(R.layout.fragment_one, container, false);

    }
    public static OneFragment newInstance(String nameValue) {
        String name;

        Bundle args = new Bundle();
        OneFragment fragment = new OneFragment();
        name = nameValue;
        fragment.setArguments(args);
        return fragment;
    }

Activity 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"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.iset.tse.Employee.Details_Employee">

    <View
        android:id="@+id/view"
        android:layout_width="421dp"
        android:layout_height="211dp"
        android:background="#1ABC9C"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintHorizontal_bias="0.0" />

    <ImageView
        android:id="@+id/imageView9"
        android:layout_width="70dp"
        android:layout_height="57dp"
        app:srcCompat="@drawable/employee"
        app:layout_constraintTop_toTopOf="parent"
        android:layout_marginTop="105dp"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintHorizontal_bias="0.53" />

    <TextView
        android:id="@+id/name_emp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Name"
        android:textAlignment="center"
        android:textAllCaps="false"
        android:textStyle="bold|italic"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        android:layout_marginTop="8dp"
        app:layout_constraintTop_toBottomOf="@+id/imageView9" />

    <android.support.design.widget.TabLayout
        android:id="@+id/tabs"
        android:layout_width="0dp"
        android:layout_height="69dp"
        android:background="@color/wallet_bright_foreground_holo_dark"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/view"
        app:tabGravity="fill"
        app:tabMode="fixed" />

    <android.support.v4.view.ViewPager
        android:id="@+id/viewpager"
        android:layout_width="0dp"
        android:layout_height="541dp"

        app:layout_behavior="@string/appbar_scrolling_view_behavior"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/tabs">


    </android.support.v4.view.ViewPager>

</android.support.constraint.ConstraintLayout>

java activity code


        //tabs
        viewPager = (ViewPager) findViewById(R.id.viewpager);
        setupViewPager(viewPager);

        tabLayout = (TabLayout) findViewById(R.id.tabs);
        tabLayout.setupWithViewPager(viewPager);
        setupTabIcons();

     /*   Date_sys = (TextView) findViewById(R.id.date_sys);
        String currentDateTimeString = DateFormat.getDateInstance().format(new Date());
        Date_sys.setText(currentDateTimeString);
        chechk_in.setText(chechkin);
    */
    }

    private void setupTabIcons() {

        TextView tabOne = (TextView) LayoutInflater.from(this).inflate(R.layout.custom_tab, null);
        tabOne.setText("ONE");
        tabOne.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.ic_tab_info, 0, 0);
        tabLayout.getTabAt(0).setCustomView(tabOne);

        TextView tabTwo = (TextView) LayoutInflater.from(this).inflate(R.layout.custom_tab, null);
        tabTwo.setText("TWO");
        tabTwo.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.ic_tab_time, 0, 0);
        tabLayout.getTabAt(1).setCustomView(tabTwo);


    }

    private void setupViewPager(ViewPager viewPager) {
        ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
        adapter.addFrag(new OneFragment(), "ONE");
        adapter.addFrag(new TwoFragment(), "TWO");

        viewPager.setAdapter(adapter);
    }

    class ViewPagerAdapter extends FragmentPagerAdapter {
        private final List<Fragment> mFragmentList = new ArrayList<>();
        private final List<String> mFragmentTitleList = new ArrayList<>();

        public ViewPagerAdapter(FragmentManager manager) {
            super(manager);
        }

        @Override
        public Fragment getItem(int position) {
            return mFragmentList.get(position);
        }

        @Override
        public int getCount() {
            return mFragmentList.size();
        }

        public void addFrag(Fragment fragment, String title) {
            mFragmentList.add(fragment);
            mFragmentTitleList.add(title);
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return mFragmentTitleList.get(position);
        }
    }

    String name;

    public void sendData(String nameAdapter) {
        name = nameAdapter;
        if (name != null) {
            OneFragment med_frag = OneFragment.newInstance(name);
            getSupportFragmentManager().beginTransaction()
                    .replace(R.id.viewpager, med_frag)
                    .commit();
        }
    }


this is My adapter

public class EmployeeAdapter extendsRecyclerView.Adapter<EmployeeAdapter.EmployeeHolder> {
    final List<Employee> EmployeeList;
    private Context context;

    @Override

    public EmployeeHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View row = 
LayoutInflater.from(parent.getContext()).inflate(R.layout.employee_row,parent,false);

        EmployeeHolder holder= new EmployeeHolder(row);
        return holder;
    }

   public EmployeeAdapter(List<Employee> EmployeeList) {
    this.EmployeeList=EmployeeList;
    }

    @Override
    public void onBindViewHolder(EmployeeHolder holder, int position) {
        Employee employee=EmployeeList.get(position);
       // holder.id.setText(employee.getId());
        holder.name.setText(employee.getName());



    }

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

    }



     public class EmployeeHolder extends RecyclerView.ViewHolder
    {
        private final Context context;

        TextView name;

        public EmployeeHolder(View itemView) {

            super(itemView);
            context = itemView.getContext();
            name=(TextView)itemView.findViewById(R.id.name_emp);



            itemView.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {

                    ((Details_Employee)context).sendData(name.getText().toString());

}

2 个答案:

答案 0 :(得分:0)

所以你需要的是一个模型类,用于数据和从一个片段到另一个片段的数据共享。 您可以使用ArrayList(您的模型类)共享数据作为第一个片段的参数,并在构造函数中获取该ArrayList。

例如:frag A和frag B以及名为model的模型类。

首先是存储所有数据的模型类,例如

模型类

public class model{

private String item1,item2,item3;
private int a,b,c;

public model(String item1, String item2, String item3, int a, int b, int c) {
    this.item1 = item1;
    this.item2 = item2;
    this.item3 = item3;
    this.a = a;
    this.b = b;
    this.c = c;
}

public String getItem1() {
    return item1;
}

public void setItem1(String item1) {
    this.item1 = item1;
}

public String getItem2() {
    return item2;
}

public void setItem2(String item2) {
    this.item2 = item2;
}

public String getItem3() {
    return item3;
}

public void setItem3(String item3) {
    this.item3 = item3;
}

public int getA() {
    return a;
}

public void setA(int a) {
    this.a = a;
}

public int getB() {
    return b;
}

public void setB(int b) {
    this.b = b;
}

public int getC() {
    return c;
}

public void setC(int c) {
    this.c = c;
}
}

现在进来 frag A

public class frag_A extends Fragment {


private RecyclerView mRecyclerView;
MainAdapter mAdapter;
ArrayList<model> data_list;//DEFINE AN ARRAYLIST OF YOUR MODEL CLASS


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

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View v = inflater.inflate(R.layout.fragment_frag_A, container, false);

    mRecyclerView = (RecyclerView)v.findViewById(R.id.recyclerview_service);
    data_list = new ArrayList<>();

    //THIS IS WHERE MODEL CLASS IS USED TO SET DATA IN ARRAYLIST

    model new_data=new model(item1,item2,item3,a,b,c);

    data_list.add(model);//add the model data to your arraylist

    mAdapter = new MainAdapter(data_list);//SET ARRAYLIST IN ADAPTER

    //set all recyclerview components you want
    mRecyclerView.setHasFixedSize(true);
    mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
    mRecyclerView.setAdapter(mAdapter);

    //onclicklistener for recyclerview items
    mRecyclerView.addOnItemTouchListener(
            new mehakmeet.startup.com.v1.home.room_services.food_order.Adapter.RecyclerItemClickListener(getActivity().getApplicationContext(), new mehakmeet.startup.com.v1.home.room_services.food_order.Adapter.RecyclerItemClickListener.OnItemClickListener() {
                @Override
                public void onItemClick(View view, final int position) {

                    //THIS IS THE PLACE WHERE DATA IS SHARED
                    service_details hk = new service_details(data_list);

                    //YOU CAN SHARE THE POSITION CLICKED HERE using bundle
                     Bundle args=new Bundle();
                  args.putString("position",String.valueOf(position);
                    hk.setArguments(args);

                    FragmentManager fragmentManager = getFragmentManager();
                    fragmentManager.beginTransaction()
                            .replace(R.id.main_home, hk).addToBackStack(null)
                            .commit();


                }
            })
    );


    return v;
}
}

现在要获取该arraylist参数,请在frag_B构造函数

中实现此arraylist

<强> frag_B

public class frag_B extends Fragment {

ArrayList<model> data_list;//Again define an arraylist of your model class
TextView item1,item2,item3
int a,b,c;

Button make_book;

//This is the constructor that uses the arraylist from previous fragment and can be used as arraylist in this fragment.
public frag_B(ArrayList<model> data_list) {
    this.data_list=data_list;
}


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View v= inflater.inflate(R.layout.fragment_service_details, container, false);
    item1=(TextView)v.findViewById(R.id.item_1);
    item2=(TextView)v.findViewById(R.id.item_2);
    item3=(TextView)v.findViewById(R.id.item_3);
    //HERE GET THE POSITION CLICKED HERE
    int position=Integer.parseInt(getArguments().getString("position");

    item1.setText(data_list.get(position).getitem1());
    item2.setText(data_list.get(position).getitem2());
    item3.setText(data_list.get(position).getitem3());

    a=data_list.get(position).getA();
    b=data_list.get(position).getB();
    c=data_list.get(position).getC();


    return v;
}

}

答案 1 :(得分:0)

您可以使用EventBus。查看自述文件以了解如何使用它。