将项目添加到主要活动中嵌入片段的RecyclerView中

时间:2018-12-10 15:30:25

标签: android android-activity android-recyclerview fragment recycler-adapter

我遇到以下问题:我有一个主活动(MainActivity),其中有一个Nav Drawer,我正在从中加载不同的片段。它加载的片段之一包含一个显示数据列表(自行车)的recyclerView。另一个片段负责将自行车添加到列表中。问题出在这里:当我将自行车添加到列表中时,您必须用新自行车重新加载自行车列表。我留下代码:Fragment ItemFragment:负责显示自行车列表

    public class ItemFragment extends Fragment {

// TODO: Customize parameter argument names
private static final String ARG_COLUMN_COUNT = "column-count";
// TODO: Customize parameters
private int mColumnCount = 1;
private OnListFragmentInteractionListener mListener;
private List<Bike> bikes;
private RecyclerView recyclerView;
private MyItemRecyclerViewAdapter myAdapter;
/**
 * Mandatory empty constructor for the fragment manager to instantiate the
 * fragment (e.g. upon screen orientation changes).
 */
public ItemFragment() {
    this.bikes = new ArrayList<Bike>();
}

// TODO: Customize parameter initialization
@SuppressWarnings("unused")
public static ItemFragment newInstance(int columnCount) {
    ItemFragment fragment = new ItemFragment();
    Bundle args = new Bundle();
    args.putInt(ARG_COLUMN_COUNT, columnCount);
    fragment.setArguments(args);
    return fragment;
}

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

    if (getArguments() != null) {
        mColumnCount = getArguments().getInt(ARG_COLUMN_COUNT);
    }

}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_item_list, container, false);

    // Set the adapter
    if (view instanceof RecyclerView) {
        Context context = view.getContext();
        recyclerView = (RecyclerView) view;
        if (mColumnCount <= 1) {
            recyclerView.setLayoutManager(new LinearLayoutManager(context));
        } else {
            recyclerView.setLayoutManager(new GridLayoutManager(context, mColumnCount));
        }
        this.bikes = new ArrayList<Bike>();
        bikes.add(new Bike("Bike1", "First Bike"));
        bikes.add(new Bike("Bike2", "Second Bike"));
        bikes.add(new Bike("Bike3", "Third Bike"));
        bikes.add(new Bike("Bike4", "Fourth Bike"));
        bikes.add(new Bike("Bike5", "Fifth Bike"));
        bikes.add(new Bike("Bike6", "Sixth Bike"));
        this.myAdapter = new MyItemRecyclerViewAdapter(bikes, mListener);
        recyclerView.setAdapter(myAdapter);
        ((MainActivity)this.getActivity()).shareFragment(this);

    }
    return view;
}



@Override
public void onAttach(Context context) {
    super.onAttach(context);
    if (context instanceof ItemFragment.OnListFragmentInteractionListener) {
        mListener = (ItemFragment.OnListFragmentInteractionListener) context;
    } else {
        throw new RuntimeException(context.toString()
                + " must implement OnListFragmentInteractionListener");
    }

}


@Override
public void onDetach() {
    super.onDetach();
    mListener = null;
}

public void addBike(Bike bike) {
    this.bikes.add(bike);
    if (this.myAdapter!=null)
        this.myAdapter.notifyDataSetChanged();
}



/**
 * 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 OnListFragmentInteractionListener {
    // TODO: Update argument type and name
    void onListFragmentInteraction(Bike item);
}
}

AddBikeFragment:将自行车添加到列表中

public class AddBikeFragment extends Fragment{
private OnClickListener listener;

private TextInputEditText mIdView;
private TextInputEditText mContentView;

@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    return inflater.inflate(R.layout.activity_add_bicycle,container,false);
}

@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    mIdView=view.findViewById(R.id.idBike);
    mContentView=view.findViewById(R.id.content);
    Button mAddBike = (Button) view.findViewById(R.id.addBike);
    mAddBike.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            String idBike = mIdView.getText().toString();
            String content = mContentView.getText().toString();

            if (idBike!=null) {
                //Log.d("TDDM", " itemFragment -" + this.itemFragment + "-");

                Bike bike=new Bike(idBike, content);

                listener.addItem(bike);
            }

        }
    });
}

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

}

// Define the events that the fragment will use to communicate
public interface OnClickListener {
    // This can be any number of events to be sent to the activity
    void addItem(Bike bike);
}

@Override
public void onAttach(Context context) {
    super.onAttach(context);
    if (context instanceof OnClickListener) {
        listener = (OnClickListener) context;
    } else {
        throw new ClassCastException(context.toString()
                + " must implement AddBikeFragment.OnClickListener");
    }


}

MainActivity:负责加载片段并对其进行操作

public class MainActivity extends AppCompatActivity
    implements NavigationView.OnNavigationItemSelectedListener, ItemFragment.OnListFragmentInteractionListener, AddBikeFragment.OnClickListener, MapFragment.OnFragmentInteractionListener, CitiesFragment.OnListFragmentInteractionListener {

private Fragment fragment;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main2);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);



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

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


}

@Override
public void onBackPressed() {
    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    if (drawer.isDrawerOpen(GravityCompat.START)) {
        drawer.closeDrawer(GravityCompat.START);
    } else {
        super.onBackPressed();
    }
}

请,有人可以引导我吗?我认为我在MainActivity的addItem方法中遇到问题,我在其中实例化了一个新的ItemFragment,而侦听器为空,我该怎么办? 谢谢

1 个答案:

答案 0 :(得分:0)

一种方法是将自行车列表保存为单例:

public class BikeData{

    private static BikeData single_instance = null; 
    private List<Bike> bikes;

       public static BikeData getInstance() 
        { 
            if (single_instance == null)single_instance = new BikeData(); 

            return single_instance; 
        } 
    } 

    }

然后创建添加,删除或检索自行车的方法。 例如

public static List<Bike> getBikeData(){
return bikes;
}

添加自行车时,您需要更新适配器。

您可以在片段中调用adapter.notifyDataSetChanged()并重置适配器:

recyclerview.setAdapter(adapter)

还值得一提的是,您可以借助eventBus轻松地在片段之间进行通信。

希望有帮助。