android fragment with recycler view communication - java

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

Related

How to setOnClickListener in adapter using RecyclerView to display inside fragment

I cannot access the ID of the item to view it in ToastMessage, or even store it in the database (use Room DataBase)
I have tried but the message does not appear
I need the reference ID to use for database storage and complete the process for storing the shopping cart
itemAdapter.java
public class itemAdapter extends RecyclerView.Adapter<itemAdapter.ItemViewHolder> {
private Context context;
private ArrayList<Items> arrayList;
private AdapterView.OnItemClickListener listener;
public itemAdapter(Context context, ArrayList<Items> arrayList) {
this.context = context;
this.arrayList = arrayList;
}
#NonNull
#Override
public ItemViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(context).inflate(R.layout.item, parent, false);
return new ItemViewHolder(v);
}
#Override
public void onBindViewHolder(#NonNull ItemViewHolder holder, int position) {
holder.name.setText(arrayList.get(position).getItemName());
holder.desc.setText(arrayList.get(position).getItemDesc());
holder.price.setText(arrayList.get(position).getItemPrice());
holder.add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context,arrayList.get(position).getItemIid(),Toast.LENGTH_SHORT);
}
});
holder.name.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context,arrayList.get(position).getItemPrice(),Toast.LENGTH_SHORT);
}
});
}
#Override
public int getItemCount() {
return arrayList.size();
}
class ItemViewHolder extends RecyclerView.ViewHolder {
TextView name, desc, price;
ImageView remove, add;
public ItemViewHolder(#NonNull View itemView) {
super(itemView);
name = itemView.findViewById(R.id.tvName);
desc = itemView.findViewById(R.id.tvDesc);
price = itemView.findViewById(R.id.tvPrice);
remove = itemView.findViewById(R.id.btnDelete);
add = itemView.findViewById(R.id.btnAdd);
}
}
}
MealsFragment.java
public class MealsFragment extends Fragment {
public MealsFragment() {
// Required empty public constructor
}
RecyclerView recyclerView;
itemAdapter adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_meals, container, false);
}
#Override
public void onViewCreated( View view, Bundle savedInstanceState) {
ArrayList<Items> ItemsList = (ArrayList<Items>) RoomDatabaseSingleton.getInstance(getContext().getApplicationContext())
.getAppDatabase()
.getDao()
.getItems("meals");
recyclerView = view.findViewById(R.id.rvMeals);
RecyclerView.LayoutManager manager = new LinearLayoutManager(
getContext(), RecyclerView.VERTICAL, false);
recyclerView.setLayoutManager(manager);
adapter = new itemAdapter(getContext(), ItemsList);
recyclerView.setAdapter(adapter);
}
}
Try the following instead
holder.add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context,arrayList.get(position).getItemIid(),Toast.LENGTH_SHORT).show();
}
});
holder.name.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context,arrayList.get(position).getItemPrice(),Toast.LENGTH_SHORT).show();
}
});
The static method makeText of Toast is used to create the Toast object and show() method on the Toast object is used to display the Toast

Sending Data From Fragment to Fragment Using TabLayout

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 to put a RecyclerView into a Fragment?

I am still new for the android development. Currently, I am trying to show a RecyclerView within a Fragment. I tried to show the RecyclerView without using Fragment and it worked fine. But when it come to using Fragment, nothing is shown.
Here is the MainActivity containing the Fragment:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//ButterKnife.bind(this);
BottomNavigationView navView = findViewById(R.id.nav_view);
navView.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
mViewModel = ViewModelProviders.of(this).get(MainActivityViewModel.class);
mFragmentManager = getSupportFragmentManager();
mFragmentTransaction = mFragmentManager.beginTransaction();
mFragmentTransaction.add(R.id.fragment_container, missionListFragment).addToBackStack(null).commit();
}
And the Fragment's onCreateView method:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_mission_list, container, false);
//ButterKnife.bind(rootview);
mRecycler = (RecyclerView) rootView.findViewById(R.id.recycler);
mFirestore = FirebaseFirestore.getInstance();
mQuery = mFirestore.collection("COLLECTION_NAME").limit(LIMIT);
if (mQuery == null) {
Log.w(TAG, "No query, not initializing RecyclerView. Created data on server.");
}
mAdapter = new RecyclerViewAdapter(mQuery, this) {
#Override
protected void onDataChanged() {
}
#Override
protected void onError(FirebaseFirestoreException e) {
// Show a snackbar on errors
Snackbar.make(getActivity().findViewById(android.R.id.content),
"Error: check logs for info.", Snackbar.LENGTH_LONG).show();
}
};
mRecycler.setLayoutManager(new LinearLayoutManager(getActivity()));
mRecycler.setAdapter(mAdapter);
return rootView;
}
With the RecyclerViewAdapter:
public class RecyclerViewAdapter extends FirestoreAdapter<RecyclerViewAdapter.ViewHolder> {
private static final int UNAVAILABLE = 0, AVAILABLE = 1;
public interface OnItemSelectedListener {
void onItemSelected(DocumentSnapshot item);
}
private OnItemSelectedListener mListener;
public RecyclerViewAdapter(Query query, OnItemSelectedListener listener) {
super(query);
mListener = listener;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
return new ViewHolder(inflater.inflate(R.layout.item, parent, false));
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.bind(getSnapshot(position), mListener);
}
static class ViewHolder extends RecyclerView.ViewHolder {
#BindView(R.id.view1)
TextView view1;
#BindView(R.id.view2)
TextView view2;
#BindView(R.id.view3)
TextView view3;
#BindView(R.id.view4)
TextView view4;
public ViewHolder(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
}
public void bind(final DocumentSnapshot snapshot,
final OnItemSelectedListener listener) {
Item item = snapshot.toObject(Item.class);
Resources resources = itemView.getResources();
view1.setText(item.getfield1());
view2.setText(Integer.toString(item.getfield2()));
if(item.getfield3() == AVAILABLE)
view3.setText("Available");
else
view3.setText("Unavailable");
view4.setText(item.getfield4().toString());
// Click listener
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (listener != null) {
listener.onItemSelected(snapshot);
}
}
});
}
}
}
As you can notice above, I am getting data from the Firebase and displaying them as a RecyclerView. But I don't think it is the problem of empty query data, so please help.
It could be that data from firebase is not being retrieved, hence there is no content for recyclerview to display. Please check if your firebase connection is working fine and you are retrieving something from it

Error when i start fragment with recyclerview and adapter

When I start activity with fragment, recyclerview and adapter the app is stopping. I don't know where the problem is. I've tried different methods.
My logcat:
java.lang.NullPointerException: Attempt to invoke virtual method 'void
android.support.v7.widget.RecyclerView.setAdapter(android.support.v7.widget.RecyclerView$Adapter)'
on a null object reference
at com.orthodox.FeedActivity.onStart(FeedActivity.java:133)
at android.support.v4.app.Fragment.performStart(Fragment.java:2287)
My code:
public class FeedActivity extends Fragment{
private RecyclerView mBlogList;
private Query mQuery;
private Query mQueryck;
private DatabaseReference mDatabaseUsers;
private FirebaseUser mCurrent;
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
FirebaseRecyclerAdapter mAdapter;
public FeedActivity() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final FragmentActivity c = getActivity();
View layout = inflater.inflate(R.layout.fragment_feed, container, false);
return layout;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
mBlogList = (RecyclerView) view.findViewById(R.id.blog_list);
mBlogList.setHasFixedSize(true);
LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
mBlogList.setLayoutManager(layoutManager);
mAuth = FirebaseAuth.getInstance();
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
if(firebaseAuth.getCurrentUser() == null){
Intent loginIntent = new Intent(getActivity(), SignUpActivity.class);
loginIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(loginIntent);
}
}
};
mQuery = FirebaseDatabase.getInstance().getReference().child("Blog").limitToLast(20);
mQuery.keepSynced(true);
mQueryck = FirebaseDatabase.getInstance().getReference().child("Block").limitToLast(20);
mQueryck.keepSynced(true);
mDatabaseUsers = FirebaseDatabase.getInstance().getReference().child("users");
mDatabaseUsers.keepSynced(true);
mCurrent = mAuth.getCurrentUser();
}
#Override
public void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthListener);
FirebaseRecyclerOptions<User> options = new FirebaseRecyclerOptions.Builder<User>().setQuery(mQuery, User.class).build();
FirebaseRecyclerOptions<User> optionss = new FirebaseRecyclerOptions.Builder<User>().setQuery(mQueryck, User.class).build();
mAdapter = new FirebaseRecyclerAdapter<User, BlogViewHolder>(options) {
#Override
public BlogViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
// Create a new instance of the ViewHolder
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.blog_row, parent, false);
return new BlogViewHolder(view);
}
#Override
protected void onBindViewHolder(BlogViewHolder viewHolder, int position, User model) {
final String post_key = getRef(position).getKey();
viewHolder.setTitle(model.getTitle());
viewHolder.setDesc(model.getDesc());
viewHolder.setTime(model.getFirstname());
viewHolder.setImage(getApplicationContext(), model.getImage());
}
};
mBlogList.setAdapter(mAdapter);
mAdapter.startListening();
mAdapter = new FirebaseRecyclerAdapter<User, BlogViewHolder>(optionss) {
#Override
protected void onBindViewHolder(BlogViewHolder viewHolder, int position, User model) {
final String post_key = getRef(position).getKey();
viewHolder.setTitle(model.getTitle());
viewHolder.setDesc(model.getDesc());
viewHolder.setTime(model.getFirstname());
viewHolder.setImage(getApplicationContext(), model.getImage());
viewHolder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent bsingle = new Intent(getActivity(), SinglePostActivity.class);
bsingle.putExtra("post", post_key);
startActivity(bsingle);
}
});
}
#Override
public BlogViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.blog_row, parent, false);
return new BlogViewHolder(view);
}
};
}
public static class BlogViewHolder extends RecyclerView.ViewHolder {
View mView;
public BlogViewHolder(View itemView) {
super(itemView);
mView = itemView;
}
public void setTitle(String title){
TextView post_title = (TextView) mView.findViewById(R.id.post_title);
post_title.setText(title);
}
public void setDesc(String desc){
TextView post_desc = (TextView) mView.findViewById(R.id.post_desc);
post_desc.setText(desc);
}
public void setImage(Context ctx, String image){
if (image != null) {
ImageView post_image = (ImageView) mView.findViewById(R.id.post_image);
Picasso.with(ctx).load(image).into(post_image);
}
else {
ImageView post_image = (ImageView) mView.findViewById(R.id.post_image);
post_image.setVisibility(View.GONE);
}
}
public void setTime(String time){
TextView post_time = (TextView) mView.findViewById(R.id.post_username);
post_time.setText(time);
}
Initialize your all views in onCreateView method.
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final FragmentActivity c = getActivity();
View layout = inflater.inflate(R.layout.fragment_feed, container, false);
mBlogList = (RecyclerView) layout.findViewById(R.id.blog_list);
return layout;
}

Animating shared element transitions using android fragments seems to be a nightmare

Animating a shared element transition between two fragments seems to be a pain. I have it working elsewhere in my app with the exact same code.
here is my on click code inside a recyclerview adapter:
private void click(int position, ItemViewHolder holder){
final ItemDescription itemDescription = itemListFiltered.get(position);
FragmentManager fm = mContext.getSupportFragmentManager();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && itemDescription != null) {
//animate transition
TransitionSet transitionSet = new TransitionSet();
transitionSet.addTransition(new ChangeTransform());
transitionSet.addTransition(new ChangeBounds());
transitionSet.addTransition(new ChangeImageTransform());
transitionSet.setDuration(300);
//set up fragment
ScanDetailsFragment frag = ScanDetailsFragment.newInstance(itemDescription, holder.productImage.getTransitionName());
frag.setEnterTransition(transitionSet);
frag.setExitTransition(transitionSet);
fm.beginTransaction().replace(R.id.fragment_container, frag)
.addSharedElement(holder.productImage, "product_image")
.addToBackStack("item details")
.commit();
}else {
ScanDetailsFragment itemDetails = ScanDetailsFragment.newInstance(itemDescription);
fm.beginTransaction().replace(R.id.fragment_container, itemDetails).addToBackStack("item details").commit();
}
I just can't seem to get this animation to work.
here is how I did it
Fragment with the RecyclerView
public class DogFragment extends Fragment implements DogAdapter.OnItemCLickListener {
public static final String TAG = "DogFragment";
#InjectView(R.id.recyclerview_dog)
RecyclerView mRecyclerView;
DogAdapter adapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
final View v = inflater.inflate(R.layout.fragment_dog, container, false);
ButterKnife.inject(this, v);
return v;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
final List<Integer> images = new ArrayList<>();
images.add(R.drawable.dog1);
images.add(R.drawable.dog2);
images.add(R.drawable.dog3);
final RecyclerView.LayoutManager layoutManager = new GridLayoutManager(getActivity(), 1);
mRecyclerView.setLayoutManager(layoutManager);
adapter = new DogAdapter(images);
adapter.setOnItemClickListener(this);
mRecyclerView.setAdapter(adapter);
}
public String getTAG() {
return TAG;
}
#Override
public void onItemClick(int position, int imageRefId, ImageView imageView) {
SingleDogFragment fragment = SingleDogFragment.getInstance(getActivity(), adapter.getImageTransitionName(getActivity(), position), imageRefId);
getFragmentManager().beginTransaction()
.addSharedElement(imageView, adapter.getImageTransitionName(getActivity(), position))
.replace(R.id.container, fragment, fragment.getTag())
.addToBackStack(null)
.commit();
}
}
The adapter
public class DogAdapter extends RecyclerView.Adapter<DogAdapter.ViewHolder> {
private OnItemCLickListener mItemClickListener;
private List<Integer> mImages;
public DogAdapter(List<Integer> images) {
mImages = images;
}
public int getItem(int position) {
return mImages.get(position);
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.gridview_element_dog, viewGroup, false);
return new ViewHolder(v);
}
#Override
public void onBindViewHolder(ViewHolder viewHolder, int i) {
viewHolder.mImageView.setImageResource(getItem(i));
viewHolder.mImageView.setTransitionName(
getImageTransitionName(viewHolder.mImageView.getContext(), i)
);
}
public String getImageTransitionName(Context context, int position) {
return context.getString(R.string.dog_transition_name) + position;
}
#Override
public int getItemCount() {
return mImages.size();
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
#InjectView(R.id.dog_imageview)
ImageView mImageView;
public ViewHolder(final View view) {
super(view);
ButterKnife.inject(this, view);
view.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if (mItemClickListener != null) {
mItemClickListener.onItemClick(getPosition(), getItem(getPosition()), mImageView);
}
}
}
public interface OnItemCLickListener {
public void onItemClick(int position, int refId, ImageView imageView);
}
public void setOnItemClickListener(final OnItemCLickListener mItemClickListener) {
this.mItemClickListener = mItemClickListener;
}
}
Target fragment
public class SingleDogFragment extends Fragment {
private static final String ARG_TRANSITION_NAME = "ARG_TRANSITION_NAME";
private static final String ARG_IMAGE_REF_ID = "ARG_IMAGE_REF_ID";
#InjectView(R.id.single_dog_imageview)
ImageView mDogImage;
public static SingleDogFragment getInstance(Context context, String transitionName, int imageRefId) {
SingleDogFragment fragment = new SingleDogFragment();
Bundle bundle = new Bundle();
bundle.putString(ARG_TRANSITION_NAME, transitionName);
bundle.putInt(ARG_IMAGE_REF_ID, imageRefId);
fragment.setSharedElementEnterTransition(TransitionInflater.from(context).inflateTransition(R.transition.change_transform));
fragment.setEnterTransition(TransitionInflater.from(context).inflateTransition(R.transition.slide_left));
fragment.setExitTransition(TransitionInflater.from(context).inflateTransition(R.transition.slide_left));
fragment.setArguments(bundle);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
View v = inflater.inflate(R.layout.fragment_single_dog, container, false);
ButterKnife.inject(this, v);
mDogImage.setTransitionName(getArguments().getString(ARG_TRANSITION_NAME));
mDogImage.setImageResource(getArguments().getInt(ARG_IMAGE_REF_ID));
return v;
}
}
change_transform.xml
<?xml version="1.0" encoding="utf-8"?>
<transitionSet xmlns:android="http://schemas.android.com/apk/res/android">
<targets>
<target android:excludeId="#android:id/statusBarBackground"/>
<target android:excludeId="#android:id/navigationBarBackground"/> <!-- exclude the status bar and the navigation bar of the animation -->
</targets>
<changeBounds/>
<changeTransform/>
</transitionSet>
And here is what it look like
Hope I could help !

Categories