簡體   English   中英

將項目添加到主要活動中嵌入片段的RecyclerView中

[英]Add Item to RecyclerView embebed in Fragment from Main Activity

我有以下問題:我有一個主活動(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,而偵聽器為空,我該怎么辦? 謝謝

一種方法是將自行車列表保存為單身:

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輕松地在片段之間進行通信

希望能有所幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM