Есть фрагмент со списоком с адаптером. Я вставляю фрагмент несколько раз в активность. Мне нужно при нажатии на элемент в одном адаптере - обновлять данные в другом. Как это реализовать? Класс адаптера один и тот же.
RecyclerStationAdapter.class
public class RecyclerStationAdapter extends RecyclerView.Adapter<RecyclerStationAdapter.ViewHolder> {
private LayoutInflater mLayoutInflater;
private List<Station> mStations;
private Context mContext;
private Radio mRadio;
private ArrayList<ViewHolder> viewHolders = new ArrayList<>();
PreferenceHelper preferenceHelper;
public RecyclerStationAdapter(Context context, Radio radio) {
this.mStations = radio.getStations();
this.mRadio = radio;
this.mLayoutInflater = LayoutInflater.from(context);
mContext = context;
preferenceHelper = new PreferenceHelper(mContext);
}
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = mLayoutInflater.inflate(R.layout.example_list_item_station, parent, false);
ViewHolder viewHolder = new ViewHolder(view);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, final int position) {
Station station = mStations.get(position);
holder.textView.setText(station.getName());
Glide.with(mContext)
.asBitmap()
.load(station.getImage())
.diskCacheStrategy(DiskCacheStrategy.AUTOMATIC)
.into(new CustomTarget<Bitmap>() {
@Override
public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
RadioStationController.setHashMap(station, resource);
holder.imageView.setImageBitmap(resource);
}
@Override
public void onLoadCleared(@Nullable Drawable placeholder) {
}
});
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
createFirebaseReport(position);
//Toaster.Toast(mContext, "Adapter.holder.onClick: " + mStations.get(position).getName());
ReportHelper.report(mStations.get(position));
AnimatorHelper.viewHolders = viewHolders;
RadioStationController.setSelectedRadio(mRadio);
if (RadioStationController.getSelectedStation() != null && RadioStationController.getSelectedStation() == mStations.get(position) && PlayerService.isPlaying) {
MediaControllerHelper.mediaController.getTransportControls().pause();
AnimatorHelper.stopAnimation(holder.playViewAnimation);
} else {
if (PlayerService.isPlaying) {
MediaControllerHelper.mediaController.getTransportControls().pause();
}
if (MediaControllerHelper.mediaController != null) {
MediaControllerHelper.mediaController.getTransportControls().play();
}
AnimatorHelper.startAnimation(holder.playViewAnimation);
}
RadioStationController.setSelectedStation(mStations.get(position));
if ((holder.imageView.getDrawable()) != null)
RadioStationController.setImageSelectedStation(RadioStationController.getBitmapFromhashmap(station));
}
});
holder.itemView.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
KeyboardHelper.closeKeyboard(mContext, holder.itemView);
return false;
}
});
holder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
if (mRadio.getGenre().equals("Избранное") | preferenceHelper.checkContainsStation(station)) {
preferenceHelper.deleteFavoriteStation(station);
mStations = preferenceHelper.getFavoriteListStations();
notifyItemRemoved(position);
notifyItemRangeChanged(position, mStations.size());
Toaster.Toast(mContext, "RecyclerStationAdapter.OnLongClickListener.DELETE_FROM_"+mRadio.getGenre().toUpperCase());
} else {
preferenceHelper.addFavoriteStation(station);
Toaster.Toast(mContext, "RecyclerStationAdapter.OnLongClickListener.ADD_TO_"+mRadio.getGenre().toUpperCase());
}
notifyDataSetChanged();
return false;
}
});
viewHolders.add(holder);
if (RadioStationController.getSelectedStation() != null && checkEqualsStation(station, RadioStationController.getSelectedStation()) && PlayerService.isPlaying)
AnimatorHelper.startAnimation(holder.playViewAnimation);
}
private boolean checkEqualsStation(Station station, Station selectedStation) {
return station.getStream().equals(selectedStation.getStream());
}
@Override
public int getItemViewType(int position) {
return position;
}
@Override
public long getItemId(int position) {
return position;
}
private void createFirebaseReport(int position) {
try {
FirebaseAnalytics firebaseAnalytics = FirebaseAnalytics.getInstance(mContext);
Bundle eventDetails = new Bundle();
StringBuilder sb = new StringBuilder();
sb.append(mStations.get(position).getName() + " : " + mStations.get(position).getStream());
eventDetails.putString("station", sb.toString());
firebaseAnalytics.logEvent("select_station", eventDetails);
} catch (Exception e) {
Log.d("glide", e.getMessage());
}
}
@Override
public int getItemCount() {
return mStations.size();
}
public class ViewHolder extends RecyclerView.ViewHolder implements Serializable {
final ImageView imageView;
final TextView textView;
public final AVLoadingIndicatorView playViewAnimation;
public ViewHolder(@NonNull View itemView) {
super(itemView);
imageView = itemView.findViewById(R.id.ivStation);
textView = itemView.findViewById(R.id.tvStation);
playViewAnimation = itemView.findViewById(R.id.playing_anim);
}
}
}
StationsFragment.class
public class StationsFragment extends Fragment {
private Radio mRadio;
private Context mContext;
public RecyclerView mRecyclerView;
private RecyclerStationAdapter mRecyclerStationAdapter;
public StationsFragment(Context context, Radio radio) {
mRadio = radio;
mContext = context;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_stations, container, false);
mRecyclerView = view.findViewById(R.id.recyclerView);
mRecyclerView.setNestedScrollingEnabled(false);
mRecyclerStationAdapter = new RecyclerStationAdapter(mContext, mRadio);
mRecyclerView.setAdapter(mRecyclerStationAdapter);
return view;
}
}
MainActivity.class
public class MainActivity extends AppCompatActivity {
private LinearLayout mLinearLayout;
private PreferenceHelper preferenceHelper;
private FirebaseAnalytics mFirebaseAnalytics;
static {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
}
@Override
protected void onDestroy() {
super.onDestroy();
MediaControllerHelper.mediaController.getTransportControls().stop();
unbindService(MediaControllerHelper.serviceConnection);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
CreateNotificationChannel.create(this);
preferenceHelper = new PreferenceHelper(this);
if (savedInstanceState == null) {
// Set the local night mode to some value
AppCompatDelegate.setDefaultNightMode(
AppCompatDelegate.MODE_NIGHT_YES);
}
MediaControllerHelper.onCreate(this);
bindService(new Intent(this, PlayerService.class), MediaControllerHelper.serviceConnection, BIND_AUTO_CREATE);
mLinearLayout = findViewById(R.id.main_container);
mFirebaseAnalytics = FirebaseAnalytics.getInstance(this);
if (savedInstanceState == null) {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
}
ArrayList<Radio> radioArray = (ArrayList<Radio>) JSONHelper.importFromJSON(getApplicationContext());
radioArray.add(0, preferenceHelper.getRadio());
RadioStationController.setListRadios(radioArray);
SearchFragment searchFragment = new SearchFragment(radioArray, mLinearLayout);
FragmentTransaction mFragmentTransaction = getSupportFragmentManager().beginTransaction();
mFragmentTransaction.add(R.id.container_from_toolbar, searchFragment).commit();
initialyzeAppMetrica(radioArray);
createListStations(radioArray);
}
private void initialyzeAppMetrica(ArrayList<Radio> radioArray) {
ReportHelper.setRadioList(radioArray);
}
@Override
protected void onPause() {
TinyDB tinydb = new TinyDB(this);
ArrayList<Object> holderObjects = tinydb.getListObject("HOLDER", RecyclerStationAdapter.ViewHolder.class);
if (AnimatorHelper.viewHolders == null)
AnimatorHelper.viewHolders = new ArrayList<>();
for(Object o : holderObjects)
AnimatorHelper.viewHolders.add((RecyclerStationAdapter.ViewHolder) o);
tinydb.putInt("POSITION", RadioStationController.getPosition());
super.onPause();
}
private void createListStations(ArrayList<Radio> radioArray) {
if (radioArray != null) {
preferenceHelper.addFavoriteStation(radioArray.get(1).getStations().get(0));//test fav
for (Radio r : radioArray) {
/* for (Station station : r.getStations()){
Glide.with(this).asBitmap().load(station.getImage()).into(new CustomTarget<Bitmap>() {
@Override
public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
RadioStationController.setHashMap(station, resource);
}
@Override
public void onLoadCleared(@Nullable Drawable placeholder) {
}
});
}*/
RadioStationController.getListStations().addAll(r.getStations());
StationsFragment stationsFragment = new StationsFragment(this, r);
inflateContainers(stationsFragment, r.getGenre(), r.getStations().size());
}
}
}
private void inflateContainers(Fragment fragment, String textGenre, int textCount){
LayoutInflater inflater = (LayoutInflater) this.getSystemService(this.LAYOUT_INFLATER_SERVICE);
View childLayout = inflater.inflate(R.layout.layout_child_conteiner, mLinearLayout, false);
ImageView imageView = childLayout.findViewById(R.id.child_container_imageview_arrow);
FragmentManager mFragmentManager = getSupportFragmentManager();
FragmentTransaction mFragmentTransaction = mFragmentManager.beginTransaction();
ExpandableLayout expandableLayout = childLayout.findViewById(R.id.child_container_expandableLayout);
expandableLayout.setId(View.generateViewId());
expandableLayout.setInterpolator(new LinearInterpolator());
LinearLayout linearLayout = childLayout.findViewById(R.id.child_container_main_container);
linearLayout.setId(LinearLayout.generateViewId());
linearLayout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (expandableLayout.isExpanded()) {
AnimationRotate.RotateArrow(imageView, expandableLayout.isExpanded());
expandableLayout.toggle();
} else {
AnimationRotate.RotateArrow(imageView, expandableLayout.isExpanded());
expandableLayout.expand();
}
KeyboardHelper.closeKeyboard(getApplicationContext(), v);
}
});
LinearLayout linearLayoutContainer = childLayout.findViewById(R.id.child_container_container);
linearLayoutContainer.setId(LinearLayout.generateViewId());
TextView textViewGenre = childLayout.findViewById(R.id.child_container_textview_genre);
textViewGenre.setId(View.generateViewId());
textViewGenre.setText(textGenre);
TextView textViewCountStations = childLayout.findViewById(R.id.child_container_textview_count_stations);
textViewCountStations.setId(View.generateViewId());
textViewCountStations.setText(String.valueOf(textCount));
mFragmentTransaction.add(linearLayoutContainer.getId(), fragment, textGenre).commit();
mLinearLayout.addView(linearLayout);
expandableLayout.toggle();
if (!expandableLayout.isExpanded())
imageView.setRotation(Const.CURRENT_ROTATE_ARROW);
}
}