Currently I have a tab host activity that contains SherlockFragment. In one of these tabs (Fragments), I want to implement a ViewPager that will show images (ImageView). I created a FragmentPagerAdapter and Fragment to add it in the ViewPager. But when I run the application, my ViewPager appears empty with no image in it.
Here are my classes:
BonusFragment.Java
public class BonusFragment extends SherlockFragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getImages(); //Here I get the images for the viewpager
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if (container == null) {
return null;
}
View view = inflater.inflate(R.layout.bonus_frag, container, false);
viewPager = (ViewPager) view.findViewById(R.id.pagr);
Q.ADAPTER = new BonusPagerAdapter(getActivity()
.getSupportFragmentManager(), myImagesList);
viewPager.setAdapter(Q.ADAPTER);
return view;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
}
BonusPagerAdapter.Java
private ArrayList<Bitmap> items;
public BonusPagerAdapter(FragmentManager fm, ArrayList<Bitmap> items) {
super(fm);
this.items = items;
}
#Override
public int getCount() {
return items.size();
}
#Override
public Fragment getItem(int position) {
Bitmap bitmap = items.get(position);
BonusImageFragment fragment = BonusImageFragment.newInstance("Glass 1");
fragment.setBitmap(bitmap);
return fragment;
}
#Override
public int getItemPosition(Object object) {
return PagerAdapter.POSITION_NONE;
}
#Override
public void notifyDataSetChanged() {
super.notifyDataSetChanged();
}
}
BonusImageFragment.Java
public class BonusImageFragment extends SherlockFragment {
private Bitmap bitmap;
public static final String EXTRA_MESSAGE = "EXTRA_MESSAGE";
private static String frag = "";
public BonusImageFragment() {
}
public static final BonusImageFragment newInstance(String message)
{
frag = message;
BonusImageFragment f = new BonusImageFragment();
Bundle bdl = new Bundle(1);
bdl.putString(EXTRA_MESSAGE, message);
f.setArguments(bdl);
return f;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.glass_item, container, false);
ImageView image = (ImageView) v.findViewById(R.id.glass_view);
image.setImageBitmap(bitmap);
return v;
}
public Bitmap getBitmap() {
return bitmap;
}
public void setBitmap(Bitmap bitmap) {
this.bitmap = bitmap;
}
}
Now why does my ViewPager always appears empty?
Fixed it... I had to change "getActivity().getSupportFragmentManager()" in "BonusFragment.Java" with "getChildFragmentManager()"
Related
Im trying to use Material Container Transform in Recyclerview Adapter as described by this post MaterialContainerTransform transition is not Working on Return , but after implementing this in my project im getting null pointer exception error.
As everyone know Material Container Transform animation tutorials are in kotlin and im doing it in java.
So if anyone know how to properly use material container transform animation in recyclerview and point out my mistakes i will be very much thankful to him.
RecyclerView Adapter Class(source)
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> implements Filterable {
private Context context;
private List<Astadhyayi> wordList;
private List<Astadhyayi> filwordList;
private DictionaryDB dictionaryDB;
private OnclickListenerInterface listener;
public RecyclerViewAdapter(Context context, List<Astadhyayi> itemList, DictionaryDB dictionaryDB) {
this.context = context;
this.wordList = itemList;
this.dictionaryDB = dictionaryDB;
filwordList = new ArrayList<Astadhyayi>(itemList);
}
public void setClickListener(OnclickListenerInterface onclickListener) {
this.listener = onclickListener;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(context);
View view = inflater.inflate(R.layout.wordslist_two_rv, parent, false);
ViewHolder viewHolder = new ViewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(final ViewHolder holder, int position) {
Astadhyayi word = wordList.get(position);
holder.rsutras.setText(word.mSutras);
// Animation******
holder.rsutras.setTransitionName(word.getMSutras());
if (word.mStatus != null && word.mStatus.equals(DictionaryDB.BOOKMARKED)) {
holder.bookmark.setImageResource(R.drawable.cards_heart);
} else {
holder.bookmark.setImageDrawable(null);
}
}
#Override
public Filter getFilter() {
return Searched_Filter;
}
private Filter Searched_Filter = new Filter() {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
List<Astadhyayi> filteredList = new ArrayList<>();
if (constraint == null || constraint.length() == 0) {
filteredList.addAll(filwordList);
} else {
String filterPattern = constraint.toString().toLowerCase().trim();
for (Astadhyayi item : filwordList) {
if (item.getMSutras().toLowerCase().contains(filterPattern)) {
filteredList.add(item);
}
}
}
FilterResults results = new FilterResults();
results.values = filteredList;
return results;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
wordList.clear();
wordList.addAll((ArrayList<Astadhyayi>)results.values);
notifyDataSetChanged();
}
};
#Override
public int getItemCount() {
return wordList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private TextView rsutras;
private ImageView bookmark;
public ViewHolder(View itemView) {
super(itemView);
itemView.setOnClickListener(this);
rsutras = itemView.findViewById(R.id.tvSansTerm);
bookmark = itemView.findViewById(R.id.bookmarkBtn);
}
/*
#Override
public void onClick(View view) {
if(listener!=null) listener.onItemClicked(getAbsoluteAdapterPosition(), rsutras);
}
*/
#Override
public void onClick(View view) {
int position = this.getAbsoluteAdapterPosition();
Astadhyayi word = wordList.get(position);
//*************** Bundle **************\\
Bundle bundle = new Bundle();
bundle.putParcelable("allData", word);
bundle.putString("transition_name", word.getMSutras());
Fragment detailsFragment = new TermThreeDetailsFragment();
detailsFragment.setSharedElementEnterTransition(new MaterialContainerTransform());
detailsFragment.setArguments(bundle);
FragmentTransaction fT =((AppCompatActivity)context).getSupportFragmentManager().beginTransaction();
fT.setReorderingAllowed(true);
fT.addSharedElement(rsutras, rsutras.getTransitionName()); // Shared element!
fT.replace(R.id.fragment_container, detailsFragment);
fT.addToBackStack(null);
fT.commit();
}
}
}
RecyclerView Fragment Class(source)
public class ShowtermsTwoFragment extends Fragment {
private RecyclerView rv;
private EditText tV;
private Toolbar toolbar;
private LinearLayoutManager layoutManager;
private static DictionaryDB db;
private RecyclerViewAdapter rvAdapter;
private SearchView searchView = null;
private SearchView.OnQueryTextListener queryTextListener;
private List<Astadhyayi> wordsList = new ArrayList<>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setExitTransition(new MaterialElevationScale(false));
setReenterTransition(new MaterialElevationScale(true));
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_terms_recyclerview, container, false);
return view;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
toolbar = ((Toolbar) view.findViewById(R.id.toolbar_rv));
rv = view.findViewById(R.id.rvTerms);
tV = view.findViewById(R.id.tVinput);
//*********** TOOLBAR
AppCompatActivity activity = (AppCompatActivity) getActivity();
activity.setSupportActionBar(toolbar);
setHasOptionsMenu(true);
// new Get_DbData().execute();
databaseCheck();
recyclerCheck1();
postponeEnterTransition();
((ViewGroup) view.getParent()).getViewTreeObserver()
.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
public boolean onPreDraw() {
startPostponedEnterTransition();
return true;
}
});
}
private void databaseCheck() {
String sanskritWord = getActivity().getIntent().getStringExtra("sanskritWord");
//*********** ### DATABASE OPENING ### ***********\\
db = DictionaryDB.getInstance(this.getActivity());
wordsList = db.getWords((sanskritWord));
}
private void recyclerCheck1() {
layoutManager = new LinearLayoutManager(getContext());
rv.setLayoutManager(layoutManager);
rv.setHasFixedSize(true);
DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(rv.getContext(), layoutManager.getOrientation());
rv.addItemDecoration(dividerItemDecoration);
rvAdapter = new RecyclerViewAdapter(getContext(), wordsList, db);
rv.setAdapter(rvAdapter);
/////********** rvAdapter.setClickListener(this);
rvAdapter.notifyDataSetChanged();
}
}
Details Fragment Class(destination)
public class TermThreeDetailsFragment extends Fragment {
private TextView sutraTV,vrittiTV,padaTv,adhyayTV,sutraIdTV ;
private CoordinatorLayout coordinatorLayout;
private FloatingActionButton fabBtn;
private static DictionaryDB db;
private Astadhyayi word;
private BottomAppBar bottomAppBar;
private TextToSpeech pronunciation;
private AudioManager audio;
private String ttsID , trans;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
MaterialContainerTransform transform = new MaterialContainerTransform();
transform.setScrimColor(Color.TRANSPARENT);
setSharedElementEnterTransition(transform);
setSharedElementReturnTransition(transform);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.show_three_details, container, false);
view.findViewById(R.id.tvSutra).setTransitionName(word.getMSutras());
return view;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
sutraTV = view.findViewById(R.id.tvSutra);
adhyayTV = view.findViewById(R.id.tVAdhyay);
padaTv = view.findViewById(R.id.tVPada);
sutraIdTV = view.findViewById(R.id.tVSutraId);
vrittiTV = view.findViewById(R.id.tvVritti);
fabBtn = view.findViewById(R.id.favFAB);
coordinatorLayout = view.findViewById(R.id.parentCordlayout);
bottomAppBar = view.findViewById(R.id.bottom_app_bar);
bundleCheckWithDb();
WordCheck();
}
private void bundleCheckWithDb() {
//*********** Geting Parcelable Data
word = new Astadhyayi(Parcel.obtain());
Bundle bundle = this.getArguments();
if (bundle != null) {
word = bundle.getParcelable("allData");
trans = bundle.getString("transition_name");
adhyayTV.setText(word.getMAdhyay());
padaTv.setText(word.getMPada());
sutraIdTV.setText(word.getMSutra_id());
sutraTV.setText(word.getMSutras());
vrittiTV.setText(word.getMVritti());
}
//*********** DATABASE OPENING
db = DictionaryDB.getInstance(this.getActivity());
}
private void WordCheck() {
if (word.mStatus != null && word.mStatus.equals(DictionaryDB.BOOKMARKED)) {
fabBtn.setImageResource(R.drawable.cards_heart);
} else {
fabBtn.setImageResource(R.drawable.cards_heart_white);
}
fabBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
bookMarkWord(word, fabBtn);
}
});
}
}
Error im getting
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.sanskrit.mysearcher.models.Astadhyayi.getMSutras()' on a null object reference
at com.sanskrit.mysearcher.fragments.TermThreeDetailsFragment.onCreateView(TermThreeDetailsFragment.java:69)
From the current given information, I think you should do something like this:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
word = new Astadhyayi(Parcel.obtain());
Bundle bundle = this.getArguments();
if (bundle != null) {
word = bundle.getParcelable("allData");
}
View view = inflater.inflate(R.layout.show_three_details, container, false);
view.findViewById(R.id.tvSutra).setTransitionName(word.getMSutras());
return view;
}
Again, I am not sure what getMSutras() actually returns and if it's right to use that here.
I’ve been having difficulties sending data from one fragment to another when utilizing a TabLayout. I’ve read copious amounts of online posts pertaining to how to do this and have had no success when implementing them myself.
I have four fragments set up in my application. I'm trying to send data gathered from an EditText element in the fourth fragment to the TextView element of the second fragment.
I don't get any errors, but the text does not show up in the second fragment. I don't know how to proceed from here. Thanks!
Fourth Fragment (sending Fragment)
public class settings extends Fragment {
SendMessage SM;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(
R.layout.setl, container, false);
return rootView;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
Button btnPassData = (Button) view.findViewById(R.id.btnPassData);
final EditText inData = (EditText) view.findViewById(R.id.inMessage);
btnPassData.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SM.sendData(inData.getText().toString().trim());
}
});
}
public interface SendMessage {
void sendData(String message);
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
try {
SM = (SendMessage) getActivity();
} catch (ClassCastException e) {
throw new ClassCastException("Error in retrieving data. Please try again");
}
}
}
Second Fragment (receiving fragment)
public class tt extends Fragment {
TextView txtData;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(
R.layout.ttl, container, false);
return rootView;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
txtData = (TextView)view.findViewById(R.id.txtData);
}
public void displayReceivedData(String message) {
txtData.setText("Data received: "+ message);
}
}
Main Activity
public class MainActivity extends AppCompatActivity implements settings.SendMessage {
#Override
protected void onCreate(Bundle savedInstanceState) {
getWindow().setFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS, WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_test);
SectionsPagerAdapter sectionsPagerAdapter = new SectionsPagerAdapter(this, getSupportFragmentManager());
ViewPager viewPager = findViewById(R.id.view_pager);
viewPager.setAdapter(sectionsPagerAdapter);
TabLayout tabs = findViewById(R.id.tabs);
tabs.setupWithViewPager(viewPager);
}
#Override
public void sendData(String message) {
String tag = "android:switcher:" + R.id.view_pager + ":" + 1;
tt f = (tt) getSupportFragmentManager().findFragmentByTag(tag);
f.displayReceivedData(message);
}
}
Something might be breaking in other part of your app.
Below is code of your working example.
class MainActivity
public class MainActivity extends AppCompatActivity implements Setting.SendMessage {
#Override
protected void onCreate(Bundle savedInstanceState) {
getWindow().setFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS, WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SectionsPagerAdapter sectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager(),this );
ViewPager viewPager = findViewById(R.id.viewpager);
viewPager.setAdapter(sectionsPagerAdapter);
TabLayout tabs = findViewById(R.id.sliding_tabs);
tabs.setupWithViewPager(viewPager);
}
#Override
public void sendData(String message) {
String tag = "android:switcher:" + R.id.viewpager + ":" + 1;
tt f = (tt) getSupportFragmentManager().findFragmentByTag(tag);
f.displayReceivedData(message);
}
}
class Setting
public class Setting extends Fragment {
SendMessage SM;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(
R.layout.setl, container, false);
return rootView;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
Button btnPassData = (Button) view.findViewById(R.id.btnPassData);
final EditText inData = (EditText) view.findViewById(R.id.inMessage);
btnPassData.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SM.sendData(inData.getText().toString().trim());
}
});
}
public interface SendMessage {
void sendData(String message);
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
try {
SM = (SendMessage) getActivity();
} catch (ClassCastException e) {
throw new ClassCastException("Error in retrieving data. Please try again");
}
}
}
class tt
public class tt extends Fragment {
TextView txtData;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(
R.layout.tt, container, false);
return rootView;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
txtData = (TextView)view.findViewById(R.id.txtData);
}
public void displayReceivedData(String message) {
txtData.setText("Data received: "+ message);
}
}
class SectionsPagerAdapter
public class SectionsPagerAdapter extends FragmentPagerAdapter {
final int PAGE_COUNT = 2;
private String tabTitles[] = new String[] { "Tab1", "Tab2"};
private Context context;
public SectionsPagerAdapter(FragmentManager fm, Context context) {
super(fm);
this.context = context;
}
#Override
public int getCount() {
return PAGE_COUNT;
}
#Override
public Fragment getItem(int position) {
if(position==0){
return new Setting();
}
else
return new tt();
}
#Override
public CharSequence getPageTitle(int position) {
return tabTitles[position];
}
}
how can i implement a onRefreshListener in fragments if i am using ViewPager (ViewPager 2) with FragmentStateAdapter.
I found only examples with FragmentPageAdapter.
the other code works so far, i mean swiping between fragments an displaying a list of strings.
Just the refresh (pull from top to bottom) don't work.
I just see the refresh symbol short and then it dissapears.
In the debugger the onRefresh functions will not be called, after a refresh action.
This is my Code:
main activity
viewPager = findViewById(R.id.view_pager);
tabLayout = findViewById(R.id.tabs);
viewPager.setAdapter(new ViewPagerAdapter(this, dataManager));
new TabLayoutMediator(tabLayout, viewPager,
new TabLayoutMediator.TabConfigurationStrategy() {
#Override public void onConfigureTab(#NonNull TabLayout.Tab tab, int position) {
tab.setText("Tab " + (position + 1));
}
}).attach();
viewpager
public class ViewPagerAdapter extends FragmentStateAdapter {
private static final int CARD_ITEM_SIZE = 3;
private DataManager dataManager;
public ViewPagerAdapter(#NonNull FragmentActivity fragmentActivity, DataManager dataManager) {
super(fragmentActivity);
this.dataManager = dataManager;
}
#NonNull #Override public Fragment createFragment(int position) {
Fragment fragment = null;
if (position == 0)
{
fragment = new FragmentA();
Bundle bundle = new Bundle(2);
bundle.putString("TOKEN", dataManager.getToken());
bundle.putString("SERVER_URL", dataManager.getServerURL());
fragment.setArguments(bundle);
}
else if (position == 1)
{
fragment = new FragmentB();
}
else if (position == 2)
{
fragment = new FragmentC();
}
return fragment;
}
#Override public int getItemCount() {
return CARD_ITEM_SIZE;
}
fragment
public class FragmentA extends Fragment implements SwipeRefreshLayout.OnRefreshListener{
private RecyclerView recyclerView;
private SwipeRefreshLayout swipeLayout;
private Bundle bundle;
private ListView mainListView;
private LibrariesAdapter listAdapter;
private LibraryDataManager libraryDataManager;
private RecyclerViewAdapter adapter;
private GetLibrariesTask getLibrariesTask;
private String token;
private String serverUrl;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
bundle = getArguments();
if (bundle != null) {
token = bundle.getString("TOKEN");
serverUrl = bundle.getString("SERVER_URL");
libraryDataManager = new LibraryDataManager(token, serverUrl);
} else {
// ToDo show error or something else
}
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(
R.layout.fragment, container, false);
swipeLayout = rootView.findViewById(R.id.swiperefresh);
getLibrariesTask = new GetLibrariesTask();
getLibrariesTask.execute();
return rootView;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mainListView = view.findViewById(android.R.id.list);
ArrayList<Library> librariesList = new ArrayList<>();
listAdapter = new LibrariesAdapter(getActivity(), librariesList);
mainListView.setAdapter(listAdapter);
swipeLayout.setOnRefreshListener(this);
swipeLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
getLibrariesTask = new GetLibrariesTask();
getLibrariesTask.execute();
}
});
}
private class GetLibrariesTask extends AsyncTask<Void, Void, List<Library>> {
#Override
protected List<Library> doInBackground(Void... args) {
List<Library> libraries = libraryDataManager.getLibraries();
return libraries;
}
#Override
protected void onPostExecute(List<Library> libraries) {
listAdapter.clear();
listAdapter.addAll(libraries);
listAdapter.notifyDataSetChanged();
Logger.debug("on refresh2");
// swipeLayout.setRefreshing(false);
}
}
}
i have a ListFragment which contain a recycler view and i want to make it when an item is clicked the DetailFragmentdisplay beside it in a multi-pane layout i know how to create a multi-pane layout but i don't know how to send data between fragments because i don't where to initialize the click to send data, where should i initialize the on click so it passes data from ListFragment to DetailFragment and display it ? * note: i am getting my data from a dialog fragment
MainActivity
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FragmentManager fm = getSupportFragmentManager();
Fragment fragment = fm.findFragmentById(R.id.fragment_list_container);
if (fragment == null) {
fragment = new ListFragment();
fm.beginTransaction()
.add(R.id.fragment_list_container, fragment)
.commit();
}
}
}
ListFragment
public class ListFragment extends Fragment implements MyDialog.OnInputSelected {
#Override
public void sendInput(String title, Uri imageUri) {
Wallpaper wallpaper = new Wallpaper(title, imageUri);
wallpaperList.add(wallpaper);
passWallpaper.passWallpaperMethod(wallpaper);
}
private List<Wallpaper> wallpaperList;
private RecyclerViewAdapter recyclerViewAdapter;
private RecyclerView recyclerView;
private FloatingActionButton fabOpenDialog;
public ListFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_list, container, false);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
fabOpenDialog = view.findViewById(R.id.fab_open_dialog);
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
fabOpenDialog.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
MyDialog dialog = new MyDialog();
dialog.setTargetFragment(ListFragment.this, 1);
dialog.show(getFragmentManager(), "MyDialog");
}
});
wallpaperList = new ArrayList<>();
recyclerView = getView().findViewById(R.id.recyclerview);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
recyclerViewAdapter = new RecyclerViewAdapter(wallpaperList, getActivity());
recyclerView.setAdapter(recyclerViewAdapter);
}
}
RecyclerViewAdapter
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> {
private List<Wallpaper> wallpaperList;
private Context context;
public RecyclerViewAdapter(List<Wallpaper> wallpaperList, Context context) {
this.wallpaperList = wallpaperList;
this.context = context;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.recycler_row, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
Wallpaper wallpaper = wallpaperList.get(position);
holder.iv.setImageURI(wallpaper.getImageUrl());
holder.tvTitle.setText(wallpaper.getTitle());
}
#Override
public int getItemCount() {
return wallpaperList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
public View view;
public ImageView iv;
public TextView tvTitle;
public ViewHolder(#NonNull View itemView) {
super(itemView);
view = itemView;
iv = itemView.findViewById(R.id.row_iv);
tvTitle = itemView.findViewById(R.id.row_tv_title);
}
}
}
DetailActivity
public class DetailsActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_details);
FragmentManager fm = getSupportFragmentManager();
Fragment fragment = fm.findFragmentById(R.id.details_container);
if (fragment == null) {
fragment = new DetailsFragment();
fm.beginTransaction()
.add(R.id.details_container, fragment)
.commit();
}
}
}
DetailsFrgament
public class DetailsFragment extends Fragment {
private TextView tvTitle;
private ImageView ivWallpaper;
public DetailsFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_details, container, false);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
tvTitle = view.findViewById(R.id.fragment_details_tv_title);
ivWallpaper = view.findViewById(R.id.details_fragment_iv_wallpaper);
}
DialogFragment
public class MyDialog extends DialogFragment implements View.OnClickListener {
public interface OnInputSelected {
void sendInput(String title, Uri imageUri);
}
public OnInputSelected onInputSelected;
#Override
public void onAttach(#NonNull Context context) {
super.onAttach(context);
try {
// "getTargetFragment()" instead of "getActivity()"
onInputSelected = (OnInputSelected) getTargetFragment();
} catch (ClassCastException e) {
Log.d("DialogFragment", "Class Cast Exception: " + e.getMessage());
}
}
TextView yes, no;
private EditText etTitle;
private ImageView imageView;
private Uri imageUri;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
setCancelable(false);
return inflater.inflate(R.layout.dialog_add_wallpaper, null);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
yes = view.findViewById(R.id.dialog_tv_ok);
no = view.findViewById(R.id.dialog_tv_cancel);
imageView = view.findViewById(R.id.dialog_iv_add_image);
imageView.setOnClickListener(this);
yes.setOnClickListener(this);
no.setOnClickListener(this);
etTitle = view.findViewById(R.id.et_add_title);
}
#NonNull
#Override
public Dialog onCreateDialog(#Nullable Bundle savedInstanceState) {
Dialog dialog = super.onCreateDialog(savedInstanceState);
dialog.setTitle("Title testing");
return dialog;
}
#Override
public void onClick(View v) {
if (v.getId() == R.id.dialog_tv_ok) {
onInputSelected.sendInput(etTitle.getText().toString().trim(), imageUri);
dismiss();
} else if (v.getId() == R.id.dialog_tv_cancel) {
onInputSelected.sendInput("got canceled", null);
dismiss();
} else {
Intent imageIntent = new Intent(Intent.ACTION_GET_CONTENT);
imageIntent.setType("image/*");
startActivityForResult(imageIntent, 1);
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1 && resultCode == Activity.RESULT_OK && data != null &&
data.getData() != null) {
imageUri = data.getData();
imageView.setImageURI(imageUri);
}
}
}
You can initialize clickListener in onBindViewHolder in RecyclerViewAdapter and inside something like this:
holder.iv.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
((MainActivity) view.getContext()).getFragmentManager().beginTransaction()
.replace(R.id.fragment_list_container, new DetailsFrgament())
.commit();
}
});
For transfering data you can use Bundle
i have written code for image slider but i use drawable images..
Actually i want to know, How to use online images in slideshow instead of
drawables...please help me with complete code as i am new to android..
public class DealsFragment extends Fragment {
private PagerAdapter mPagerAdapter;
public static DealsFragment newInstance() {
DealsFragment fragment = new DealsFragment();
return fragment;
}
public DealsFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_deals, container, false);
List<Fragment> fragments = new Vector<Fragment>();
fragments.add(Fragment.instantiate(getActivity(), ImageOneDeals.class.getName()));
fragments.add(Fragment.instantiate(getActivity(), ImageTwoDeals.class.getName()));
fragments.add(Fragment.instantiate(getActivity(), ImageThreeDeals.class.getName()));
mPagerAdapter = new ImagePagerAdapter(getChildFragmentManager(), fragments);
pager.setAdapter(mPagerAdapter);
return view;
}
}
ImageOneDeals.java
public class ImageOneDeals extends Fragment {
public View onCreateView(LayoutInflater inflater,ViewGroup container,Bundle savedInstanceState){
if(container==null){
return null;
}
return (LinearLayout) inflater.inflate(R.layout.image1_deals,container,false);
}
}
ImagePagerAdapter.java
public class ImagePagerAdapter extends FragmentPagerAdapter {
private List<Fragment> fragments;
public ImagePagerAdapter(FragmentManager fragmentManager, List<Fragment> fragments){
super(fragmentManager);
this.fragments=fragments;
}
#Override
public Fragment getItem(int position) {
return this.fragments.get(position);
}
#Override
public int getCount() {
return this.fragments.size();
}
}
Your Deal Fragment:-
public class DealFragment extends Fragment {
private View rootView;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
if (rootView == null) {
rootView = inflater.inflate(R.layout.slide_view_pager, container, false);
new GetUserImage().execute(); //run your webservices here
}
return rootView;
}
public class GetUserImage extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pd = new ProgressDialog(getActivity());
pd.setCancelable(true);
pd.setMessage("Loading...");
pd.setProgressStyle(ProgressDialog.STYLE_SPINNER);
pd.show();
}
#Override
protected String doInBackground(String... params) {
postUserImageData();
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
//save your data in a list
// set Adapter after you get data from webservices
mPager = (ViewPager) rootView.findViewById(R.id.slidePager);
ImagePagerAdapter viewImagePagerAdapter = new ImagePagerAdapter(getChildFragmentManager(), TotalCount, imagearr);
mPager.setAdapter(viewImagePagerAdapter);
mPager.getCurrentItem();
}
public void postUserImageData() {
}
}
}
your Adapter:-
public class ImagePagerAdapter extends FragmentPagerAdapter {
private int numOfItemSize;
List<UserImage> arr1;
public ImagePagerAdapter (FragmentManager childFragmentManager, int num_pages, List<UserImage> customMessageListView) {
super(childFragmentManager);
this.numOfItemSize = num_pages;
this.arr1 = customMessageListView;
}
#Override
public Fragment getItem(int position) {
ImageOneDeals userImageDetailFragment = new ImageOneDeals ();
UserImage sc = arr1.get(position);
Bundle bundle = new Bundle();
bundle.putString("ProfilePic", sc.ProfilePic);
bundle.putString("Work", sc.Work);
bundle.putString("BirthTime", sc.BirthTime);
bundle.putString("Message", sc.Message);
userImageDetailFragment.setArguments(bundle);
return userImageDetailFragment;
}
#Override
public int getCount() {
return numOfItemSize;
}
}
your ImageOneDeals :-
public class ImageOneDeals extends Fragment {
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
Title = getArguments().getString("ProfilePic");
BirthTime = getArguments().getString("BirthTime");
Work = getArguments().getString("Work");
Message = getArguments().getString("Message");
}
#Override
public View onCreateView(LayoutInflater inflater, final ViewGroup container, Bundle savedInstanceState) {
final View view = (View) inflater.inflate(R.layout.slide_user_image, container, false);
return view;
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
initialiseViews();
}
public void initialiseViews() {
ImageView imgDetails = (ImageView) getView().findViewById(R.id.UserimageView);
TextView usrname = (TextView) getView().findViewById(R.id.userName);
TextView usrwork = (TextView) getView().findViewById(R.id.userWork);
// imgLoader.DisplayImage(Title,imgDetails);
Picasso.with(getActivity())
.load(Title)
.placeholder( R.mipmap.add_photo)
.error( R.mipmap.add_photo)
.into(imgDetails);
usrname.setText(Message);
usrwork.setText(Work);
}
}