У меня есть экран, на котором отображается содержимое двух папок. Я использую TabLayout с теми же фрагментами, но использую два разных экземпляра фрагмента.
Вот код фрагмента
public class SavedFragment extends Fragment {
private Context context;
private ArrayList<Uri> files;
private DataAdapter dataAdapter;
private RecyclerView recyclerView;
protected boolean isInstagramStatuses;
private SharedPreferences sharedPreferences;
private SharedPreferences.OnSharedPreferenceChangeListener savedAnythingListener;
public SavedFragment() {
// Required empty public constructor
}
public SavedFragment(boolean isInsta) {
isInstagramStatuses = isInsta;
}
public static SavedFragment newInstance(boolean isInstagramStatuses) {
SavedFragment savedFragment=new SavedFragment();
Bundle bundle=new Bundle();
bundle.putBoolean("isInsta",isInstagramStatuses);
savedFragment.setArguments(bundle);
return savedFragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
if (savedInstanceState != null) {
isInstagramStatuses = savedInstanceState.getBoolean("isInsta", false);
}
files = getFileNames();
if (getActivity() != null) {
sharedPreferences = getActivity().getSharedPreferences(getString(R.string.sharedPrefName), Context.MODE_PRIVATE);
savedAnythingListener = new SharedPreferences.OnSharedPreferenceChangeListener() {
@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
if (key.equals(getString(R.string.sharedPrefIsFilesUpdates))) {
updateDataAdapter(sharedPreferences.getBoolean(key, false));
}
}
};
sharedPreferences.edit().putBoolean(getString(R.string.sharedPrefIsFilesUpdates), false).apply();
sharedPreferences.registerOnSharedPreferenceChangeListener(savedAnythingListener);
dataAdapter = new DataAdapter(getContext(), files);
dataAdapter.setClickListener(new DataAdapter.ItemClickListener() {
@Override
public void onItemClick(View view, int position) {
if (dataAdapter.hasSelection()) {
dataAdapter.toggleSelection(position);
} else {
Intent intent = new Intent(getContext(), FullScreenActivity.class);
intent.putExtra(getResources().getString(R.string.current_media_path), dataAdapter.getFileName(position));
intent.putExtra("alreadySaved", true);
if (String.valueOf(dataAdapter.getFileName(position)).endsWith(".mp4")) {
intent.putExtra("videoView", true);
}
startActivity(intent);
}
}
@Override
public boolean onItemLongClick(View view, int position) {
dataAdapter.toggleSelection(position);
return false;
}
});
}
super.onCreate(savedInstanceState);
}
@Override
public void onSaveInstanceState(@NonNull Bundle outState) {
outState.putBoolean("isInsta", isInstagramStatuses);
super.onSaveInstanceState(outState);
}
private void updateDataAdapter(boolean update) {
if (update) {
dataAdapter.updateFiles(getFileNames());
sharedPreferences.edit().putBoolean(getString(R.string.sharedPrefIsFilesUpdates), false).apply();
}
}
private ArrayList<Uri> getFileNames() {
ArrayList<Uri> fileNames = new ArrayList<>();
String dirName = Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + getResources().getString(R.string.folderName);
File dir;
File[] files;
if (isInstagramStatuses) {
dir = new File(dirName + "/Instagram");
files = dir.listFiles(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return name.endsWith(".mp4") || name.endsWith(".jpg") || name.endsWith(".png");
}
});
if (files != null && files.length > 0) {
for (File file : files) {
fileNames.add(Uri.parse("file://" + file.getAbsolutePath()));
}
}
} else {
dir = new File(dirName + "/WhatsApp");
files = dir.listFiles(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return name.endsWith(".mp4") || name.endsWith(".jpg") || name.endsWith(".png");
}
});
if (files != null && files.length > 0) {
for (File file : files) {
fileNames.add(Uri.parse("file://" + file.getAbsolutePath()));
}
}
}
return fileNames;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_saved, container, false);
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
if (isInstagramStatuses) {
view.findViewById(R.id.message).setVisibility(View.GONE);
} else {
view.findViewById(R.id.message).setVisibility(View.VISIBLE);
}
recyclerView = view.findViewById(R.id.listItems);
recyclerView.setLayoutManager(new GridLayoutManager(getContext(), 4, GridLayoutManager.VERTICAL, false));
recyclerView.setAdapter(dataAdapter);
}
@Override
public void onDetach() {
if(sharedPreferences!=null){
sharedPreferences.unregisterOnSharedPreferenceChangeListener(savedAnythingListener);
}
super.onDetach();
}
}
Вот код для добавления фрагментов в окно просмотра и макет вкладки
public class MyFilesActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_files);
toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
tabLayout = findViewById(R.id.tabs);
pager = findViewById(R.id.viewPager);
setViewPager();
}
private void setViewPager() {
tabsViewPagerAdapter = new TabsViewPagerAdapter(getSupportFragmentManager(), 1);
SavedFragment savedFragment=new SavedFragment(false);
SavedFragment whatsapp=new SavedFragment(true);
tabsViewPagerAdapter.addFragment(savedFragment, getResources().getString(R.string.whatsapp));
tabsViewPagerAdapter.addFragment(whatsapp, getResources().getString(R.string.instagram));
pager.setAdapter(tabsViewPagerAdapter);
tabLayout.setupWithViewPager(pager);
}
}
Вот и удаление выполнено в FullScreenActivity
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
if(item.getItemId()==R.id.delete){
finish();
if(new File(String.valueOf(mediaPath).substring(7)).delete()){
sharedPreferences.edit().putBoolean(getString(R.string.sharedPrefIsFilesUpdates),true).apply();
showToast("deleted");
}
}
return super.onOptionsItemSelected(item);
}
}
Моя проблема заключается в том, что всякий раз, когда я обновляю данные, например, если я добавляю / удаляю файлы в папке WhatsApp, логическое значение isInstagramStatuses
во фрагменте меняется с true на false или false на true. так что обновляется только один из данных фрагмента.