Добавить элемент в RecyclerView, встроенный во фрагмент из основного действия - PullRequest
0 голосов
/ 10 декабря 2018

У меня следующая проблема: у меня есть основное действие (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();
    }
}

Пожалуйста, кто-нибудь может мне помочь?Я думаю, у меня есть проблема в методе addItem MainActivity, где я создаю новый ItemFragment, а слушатель пуст, как мне это сделать?Спасибо

1 Ответ

0 голосов
/ 11 декабря 2018

Один из способов сделать это - сохранить список велосипедов в отдельном файле:

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 .

Надежда, которая помогает.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...