将数据从片段中的RecyclerView传递到另一个片段

时间:2018-11-04 21:52:19

标签: android android-fragments android-recyclerview

我有RecycleView的应用程序,单击行后,我需要根据第一个RecycleView中单击的行中的数据在另一个RecycleView中打开另一个Fragment。我在工作所在的地方有了应用程序,现在我想要DrawerMenuFragments,但我不知道该怎么做。我是Android的新手,我所知道的全部都是教程中的内容。

BaseActivity

package cz.revelio.mhdapp;
import android.support.annotation.NonNull;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.widget.Toast;

public class BaseActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
    private DrawerLayout drawer;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

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

    drawer = findViewById(R.id.drawer_layout);
    NavigationView navigationView = findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(this);

    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar,
            R.string.navigation_drawer_open, R.string.navigation_drawer_close);
    drawer.addDrawerListener(toggle);
    toggle.syncState();

    if (savedInstanceState == null) {
        getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
                new ZapisFragment()).commit();
        navigationView.setCheckedItem(R.id.nav_message);
    }
}

@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
    switch (item.getItemId()) {

        case R.id.nav_chat:
            getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
                    new ZapFragment()).commit();
            break;
        case R.id.nav_profile:
            getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
                    new SeznamFragment()).commit();
            break;
        case R.id.nav_message:
            getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
                    new ZapisFragment()).commit();
            break;
        case R.id.nav_share:
            Toast.makeText(this, "Share", Toast.LENGTH_SHORT).show();
            break;
        case R.id.nav_send:
            Toast.makeText(this, "Send", Toast.LENGTH_SHORT).show();
            break;
    }

    drawer.closeDrawer(GravityCompat.START);
    return true;
}

@Override
public void onBackPressed() {
    if (drawer.isDrawerOpen(GravityCompat.START)) {
        drawer.closeDrawer(GravityCompat.START);
    } else {
        super.onBackPressed();
    }
}
}

BaseActivity中,我可以呼叫 SeznamFragment ,其中第一个是RecyclerView

   package cz.revelio.mhdapp;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.content.Context;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.List;


public class SeznamFragment extends Fragment {
    RecyclerView recyclerView;
    DatabaseHelper mDatabaseHelper;
    TextView info;
    Context context;


@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View v =  inflater.inflate(R.layout.fragment_seznam, container, false);
    info = (TextView) v.findViewById(R.id.info_count_in_dash);
    recyclerView= (RecyclerView) v.findViewById(R.id.recyclerview);
    mDatabaseHelper = new DatabaseHelper(context);
    int vsechyZaznamy = mDatabaseHelper.getCountAllLogs();
    int unikatniZaznamy = mDatabaseHelper.getCountUniqueLogs();
    info.setText(vsechyZaznamy+" záznamů, z toho "+unikatniZaznamy+" unikátních.");
    getData();
    return v;
}

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

}
public void getData(){
    List<String> dataZaznamy = mDatabaseHelper.getAllLogs();
    String[] zaznamy = new String[dataZaznamy.size()];
    zaznamy = dataZaznamy.toArray(zaznamy);
    recyclerView.setLayoutManager(new LinearLayoutManager(context));
    recyclerView.setAdapter(new Adapter(context,zaznamy));
}


}

Adapter.java (来自RecycleView

package cz.revelio.mhdapp;


import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.constraint.ConstraintLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v7.widget.RecyclerView;
import android.text.Layout;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

public class Adapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
    Context context;
    String[] items;
    public Adapter(Context context, String[] items){
        this.context=context;
        this.items=items;
    }
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
    LayoutInflater inflater = LayoutInflater.from(context);
    View row = inflater.inflate(R.layout.costume_row, viewGroup, false);
    Item item=new Item(row);
    return item;
}

@Override
public void onBindViewHolder(@NonNull RecyclerView.ViewHolder viewHolder, int position) {
    String text = items[position];
    final String casti[] = text.split(",");
    ((Item)viewHolder).itemName.setText(casti[0]);
    ((Item)viewHolder).itemCount.setText(casti[2]+"x");
    ((Item)viewHolder).itemLast.setText("Naposledy zapsáno:  "+casti[3]);
    ((Item) viewHolder).lay.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            //Toast.makeText(context, "OnClick Called on position "+position+" a lince "+ casti[0], Toast.LENGTH_SHORT).show();
         Fragment fragment = new VehicleFragment();
         Bundle b = new Bundle();
         b.putString("vehicle_id", casti[0]);
         fragment.setArguments(b);

         //android.support.v4.app.FragmentManager fragmentManager = get
          /*  Intent intent = new Intent(context, VehicleList.class);
            intent.putExtra("vehicle_id", casti[0]);
            context.startActivity(intent);*/
        }
    });
    ((Item) viewHolder).lay.setOnLongClickListener(new View.OnLongClickListener() {
        @Override
        public boolean onLongClick(View v) {
            //Toast.makeText(context, "OnLongClick Called on position "+position, Toast.LENGTH_SHORT).show();
            return true;
        }
    });
}



@Override
public int getItemCount() {
    return items.length;
}
public class Item extends RecyclerView.ViewHolder {
    TextView itemName;
    TextView itemCount;
    TextView itemLast;
    ConstraintLayout lay;

    public Item(View itemView){
        super(itemView);
        itemName= (TextView) itemView.findViewById(R.id.item_name);
        itemCount= (TextView) itemView.findViewById(R.id.item_count);
        itemLast= (TextView) itemView.findViewById(R.id.item_last);
        lay = (ConstraintLayout) itemView.findViewById(R.id.item_rr);
    }
}


}

VehicleFragment (第二个RecyclerView在哪里,我需要从SeznamFragment.java来的数据在哪里:

package cz.revelio.mhdapp;


import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import java.util.List;


public class VehicleFragment  extends Fragment {

    private static final String TAG = "LineList";
    RecyclerView recyclerView;
    DatabaseHelper mDatabaseHelper;
    Context context;
    String vehicle_id;
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_seznam, container, false);

    }

@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    context = getContext();
    mDatabaseHelper = new DatabaseHelper(context);

    //getIncomingIntent();
}

/*private void getIncomingIntent(){

    if(getActivity().getIntent().hasExtra("vehicle_id")){
        String vehicle_id =  getActivity().getIntent().getStringExtra("vehicle_id");
        getData(vehicle_id);
    }
}*/

public void getData(String id_vehicle){
    List<String> dataZaznamy = mDatabaseHelper.getAllLogsByVehId(id_vehicle);
    String[] zaznamy = new String[dataZaznamy.size()];
    zaznamy = dataZaznamy.toArray(zaznamy);
    recyclerView.setLayoutManager(new LinearLayoutManager(context));
    recyclerView.setAdapter(new AdapterVehicle(context,zaznamy));
    }

}

AdapterVehicle (第二秒RecyclerView

package cz.revelio.mhdapp;



import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.constraint.ConstraintLayout;
import android.support.v7.widget.RecyclerView;
import android.text.Layout;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

public class AdapterVehicle extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
    DatabaseHelper mDatabaseHelper;
    Context context;
    String[] items;

    public AdapterVehicle(Context context, String[] items){
        this.context=context;
        this.items=items;

    }
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
        LayoutInflater inflater = LayoutInflater.from(context);
        View row = inflater.inflate(R.layout.costume_row_veh, viewGroup, false);
        Item item=new Item(row);
        return item;
    }
@Override
public void onBindViewHolder(@NonNull RecyclerView.ViewHolder viewHolder, int position) {
    mDatabaseHelper = new DatabaseHelper(context);
    String text = items[position];
    final String casti[] = text.split(",");
    if(casti[5].equals("true")) {
        ((Item) viewHolder).itemName.setText("Jízda linkou " + casti[1]);
    }else{
        ((Item) viewHolder).itemName.setText("Linka " + casti[1]);
    }
    ((Item)viewHolder).itemCount.setText(casti[2]);
    ((Item)viewHolder).itemLast.setText(casti[3]);
    ((Item) viewHolder).lay.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // Toast.makeText(context, "OnClick Called on position "+position+" a lince "+ casti[0], Toast.LENGTH_SHORT).show();
            Intent intent = new Intent(context, VehicleEdit.class);
            intent.putExtra("vehicle_id", casti[0]);
            intent.putExtra("line", casti[1]);
            intent.putExtra("datum", casti[2]);
            intent.putExtra("cas", casti[3]);
            intent.putExtra("jedu", casti[5]);
            intent.putExtra("id", casti[4]);
            context.startActivity(intent);
        }
    });
    ((Item) viewHolder).lay.setOnLongClickListener(new View.OnLongClickListener() {
        @Override
        public boolean onLongClick(View v) {
            //Toast.makeText(context, "OnLongClick Called on position "+position, Toast.LENGTH_SHORT).show();
            //pass the 'context' here
            AlertDialog.Builder alertDialog = new AlertDialog.Builder(context);
            alertDialog.setTitle("Smazat záznam");
            alertDialog.setMessage("Chcete záznam smazat?");
            alertDialog.setPositiveButton("Ano", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {

                    Toast.makeText(context, "Záznam vozidla "+casti[0]+" na lince "+casti[1]+" byl smazán.", Toast.LENGTH_SHORT).show();
                    mDatabaseHelper.removeItem(casti[4]);
                    notifyDataSetChanged();
                    Intent intent = new Intent(context, SeznamFragment.class);
                    context.startActivity(intent);
                }
            });
            alertDialog.setNegativeButton("Ne", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.cancel();
                }
            });

            AlertDialog dialog = alertDialog.create();
            dialog.show();
            return true;
        }
    });
}

@Override
public int getItemCount() {
    return items.length;
}
public class Item extends RecyclerView.ViewHolder {
    TextView itemName;
    TextView itemCount;
    TextView itemLast;
    ConstraintLayout lay;

    public Item(View itemView){
        super(itemView);
        itemName= (TextView) itemView.findViewById(R.id.item_name_veh);
        itemCount= (TextView) itemView.findViewById(R.id.item_count_veh);
        itemLast= (TextView) itemView.findViewById(R.id.item_last_veh);
            lay = (ConstraintLayout) itemView.findViewById(R.id.item_rr_veh);
        }
    }
}

我尝试了StackOvreflow的另一种解决方案,但对我没有任何帮助。

在这里您可以找到我的实际代码 https://drive.google.com/file/d/1W6OzBCjwH4PJkix73woLCHHDBrh26-U1/view?usp=sharing

3 个答案:

答案 0 :(得分:0)

您可以通过Bundle传递:

public static VehicleFragment newInstance(String your_data_if_its_string) {
        VehicleFragment frag = new VehicleFragment();
        Bundle args = new Bundle();
        args.putString(PersonDBFields.ID, person_id);
        frag.setArguments(args);
        return frag;
    }

将其放入您的VehicleFragment中, 并使用VehicleFragment.newInstance("yourData");,或者您可以在类中创建一个字段并为其创建一个Setter,然后在新实例中调用setter方法而不是Bundle

答案 1 :(得分:0)

您没有做任何事情,只是没有将其添加到片段管理器中,这就是为什么您无法启动SecondFragment的原因。这样做:

    VehicleFragment frag = new VehicleFragment();
    Bundle args = new Bundle();
    args.putString(PersonDBFields.ID, person_id);
    frag.setArguments(args);
    return frag;

//now add it to the fragment manager.like you are doing in your activity
getFragmentManager().beginTransaction().add(R.id.container, frag).commit();

在新的VehicleFragment的onCreateView中:

//Retrieve the value
String value = getArguments().getString("YourKey");

您必须在适配器类中获得片段管理器。

   @Override
    public void onClick(View view){
     VehicleFragment vehicleFragment =VehicleFragment.getInstance();
     Bundle b = new Bundle();
     b.putString("vehicle_id", casti[0]);
     vehicleFragment.setArguments(b);
    AppCompatActivity activity = (AppCompatActivity) view.getContext();         
    activity.getSupportFragmentManager().beginTransaction()
   .replace(R.id.fragment_container, 
    myFragment).addToBackStack(null).commit();

 }

答案 2 :(得分:0)

最近,Android Jetpack拥有一些相当不错的库,这些库包含ViewModel个对象,这些对象使管理和存储数据更加容易。 它使您可以访问应用程序中不同活动或片段处的数据。您尝试一下,希望对您有用