How to structure this Fragment / RecyclerView - android

I know this is somewhat of a design question but I do have specific questions for it. I'm trying to understand how to handle a situation like this one:
Let's say I have a RecyclerViewFragment which loads a RecyclerView containing a bunch of Toy objects.
In one situation: Maybe this RecyclerViewFragment is part of a ViewPager on main display. There is a FloatingActionButton add-button present over this RecyclerView. You click the + button and you can add a new Toy to the list. Or you can click a Toy from the list directly and a floating menu pops up with Edit/Delete buttons, and pressing Edit lets you edit the Toy's details in a DialogFragment, or clicking Delete removes it from the RecyclerView.
In another situation: Now I am in a separate part of the app where I want to choose toys to use. So I press a button and a DialogFragment appears with a RecyclerView of Toys. I can click a Toy and it'll be added to my cart.
It seems like I should be re-using the same RecyclerView code in both situations, since they both involve a list of the same Toys. The only difference is that in one situation, I can add Toys and edit Toy details, and in the other situation, there is no Add button and clicking on a toy does something different (adding to a cart as opposed to bringing up an Edit/Delete dialog).
Is this the correct way to handle this:
Communication from Fragment to Activity: Interfaces? Have the RecyclerViewFragment, in the onAttach method, assign a listener of my design to the context. Then when a row of the RecyclerView is pressed, the callback is triggered. Now the underlying Activity can decide what to do with that press -- show the Edit/Delete dialog in one situation, add the Toy to a Cart in the other situation. Either way, the click item sends the Toy to the calling Activity so it can decide what to do with it.
Communication from Activity to Fragment: Now what about the situation with the Add button? This Add button would not be intrinsically part of the RecyclerViewFragment, so when I click Add, it would bring up the details dialog box where I can give the Toy details, and then press OK to add it. So somehow I have to transfer this new Toy to the Fragment to have it added to the RecyclerView. Would I simply do something like this:
RecyclerViewFragment recyclerViewFragment = (RecyclerViewFragment ) getSupportFragmentManager().findFragmentByTag("TOY_RECYCLERVIEW");
recyclerViewFragment.getNewToyAndRefreshList(newToy);
and then in the RecyclerViewFragment:
public void getNewToyAndRefreshList(Toy newToy) {
toyList.add(newToy);
Collections.sort(toyList); //Toy has Comparable implemented, sort by name
recyclerViewAdapter.notifyDataSetChanged();
}
Am I on the right track? Is there a different way to fix this situation?

That's certainly a design question, but IMHO there's a very specific issue on it and I believe it's a good question (reason I'm answering), but that also means other developers might have other approaches to solve the issue.
1. that is a totally fair and acceptable approach to it. You let the fragment be simple UI element and let someone else (the activity) implement the click behavior.
For this approach remember to code it only against the interface. That means, don't cast it to your activity. For example:
// do this
toyClickListener.onToyClicked(toy);
// don't do this
((MyActivity)getActivity()).onToyClicked(toy);
That way you keep the "simple UI element" be completely unaware of who is implementing the behavior.
2. IMO for this kind of scenario (specially on RecyclerView.Adapter) the best thing to do is to forget the UI and only focus on the data. And how speciafically you implement this, will vary on what is your data source.
But the base idea is that you have somewhere a data repo (DB?) and anyone using data from there, should subscribe to changes to it.
So you override RecyclerView.Adapter.registerAdapterDataObserver and unregisterAdapterDataObserver add the subscription/listener code, something like that:
#Override registerAdapterDataObserver(RecyclerView.AdapterDataObserver observer) {
super.registerAdapterDataObserver(observer);
db.subscribe(this, toyList);
}
#Override unregisterAdapterDataObserver(RecyclerView.AdapterDataObserver observer) {
db.unsubscribe(this);
super.unregisterAdapterDataObserver(observer);
}
#Override public void onDbDataUpdate(new Data comes here){
update the data, and call .notifyDataSetChanged();
}
that way once the FAB + and then dialog is clicked the new Toy gets added to the DB and the adapter gets "automatically" notified.
So if this data comes from a SQLite you can call on the cursor registerContentObserver if it's a RealmDB you'll use addChangeListener, even Android databinding libraries have a ObservableList

Related

What's the correct way of displaying ViewPager after associated ListView's item click?

I'm a beginner in Android, so I apologize for the mistakes and I'd appreciate any constructive criticism.
I'm writing a basic application with a ListView of images, and when the user clicks on an item in the list, I want to display that image in a ViewPager, where the user can swipe back and forth to browse the whole list of images. Afterwards when the user presses the back button, I want to switch back to the ListView.
I manage the business logic in the MainActivity, which uses MainActivityFragment for the ListView and ImageHolderFragment for ViewPager.
The simplified code so far is as follows:
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mListItems = new ArrayList<>();
mListItemAdapter = new ListItemAdapter(this, R.layout.list_item, R.id.list_item_name, mListItems);
mListView = (ListView) findViewById(R.id.list_view_content);
mListView.setAdapter(mListItemAdapter);
mDeletedListItems = new ArrayList<>();
mViewPager = (ViewPager) getLayoutInflater().inflate(R.layout.image_display, null, true);
mImageAdapter = new ImageAdapter(getSupportFragmentManager(), mListItems);
mViewPager.setAdapter(mImageAdapter);
mViewPager.setOffscreenPageLimit(3);
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
mViewPager.setCurrentItem(position);
setContentView(mViewPager); // TODO: this is very wrong!
}
});
loadImages();
noContentText = (TextView) findViewById(R.id.no_content_text);
if (mListItems.isEmpty()) {
noContentText.setText(R.string.no_images);
} else {
mImageAdapter.notifyDataSetChanged();
}
}
Although this does work to some extent, meaning that it manages to display the ViewPager when an item in the list is clicked, there are two things about it ringing the alarm bells:
I've read that calling setContentView() for the second time in the same class is pretty much a sin. Nobody explained me why.
The back button doesn't work in this case. When it's pressed, the application is terminated instead of going back to the list view. I believe this is connected to the first point.
I would appreciate any help, explanations if my idea is completely wrong, and if my case is hopeless, I'd like to see a successful combination of ListView and ViewPager with transitions between each other.
Your activity already has R.layout.activity_main set as content view, which rightly displays the list view - that's what the responsibility of this activity is as you defined it. If we want to change what's shown on the screen, we should use a different instance of a building block (activity or fragment) to display the view pager images.
To say the least, imagine if you wanted to change the view to a third piece of functionality or UI, or a fourth... it would be a nightmare to maintain, extend and test as you're not separating functionality into manageable units. Fields that are needed in one view are mixed with those needed in another, your class file would grow larger and larger as each view brings its click listeners, callbacks, etc., you'd also have to override the back button so it does what you want - it's just not how the Android framework was designed to help you. And what if you wanted to re-use UI components in different contexts whilst tapping in to the framework's activity lifecycle callbacks? That's why fragments were introduced.
In your case, the list view could continue to run in your MainActivity and in your click listener, onItemClick you could start a new activity that will hold a viewPager:
Intent i = new Intent(MainActivity.this, MyLargePhotoActivityPager.class);
i.putExtra(KEY_POSITION, position);
// pass the data too
startActivityForResult(i, REQUEST_CODE);
Notice how you could pass the position to this activity as an int extra, in order for that second activity to nicely set the viewPager to the position that the user clicked on. I'll let you discover how to build the second activity and put the ViewPager there. You also get back button functionality assuming your launch modes are set accordingly, if needed. One thing to note is that when you do come back to the list View, you'd probably want to scroll to the position from the view pager, which is why you could supply that back as a result via a request code. The returned position can be supplied back to the list view.
Alternatively, you could use the same activity but have two fragments (see the link further above) and have an equivalent outcome. In fact, one of your fragments could store the list view, and the second fragment could be a fullscreen DialogFragment that stores a viewPager, like a photo gallery (some details here).
Hope this helps.
I've read that calling setContentView() for the second time in the
same class is pretty much a sin. Nobody explained me why.
Well, you kind of get an idea as to why.
When you use setContentView() to display another 'screen' you do no have a proper back stack.
You also keep references to Views (like mListView) that are not visible anymore and are therefore kind of 'useless' after you setContentView() for the second time.
Also keep in mind orientation changes or your app going to the background - you'll have to keep track of the state that your Activity was in which is way more complicated than it has to be if you have one Activity that does two different things.
You won't be arrested for doing things like you do right now, but it's just harder to debug and keep bug free.
I'd suggest using two different Activities for the two different things that you want to do, or use one Activity and two Fragments, swapping them back and forth.
If you insist on having it all in one Activity you need to override onBackPressed() (called when the user presses the back button) and restore the first state of your Activity (setContentView() again, pretty much starting all over).

Using onMenuItemCLickListener from activity to call methods from multiple fragments

i wish you all a good day.
First of all, sorry if i mispell frecuently because i din't know how to write on english, at least properly. But that's not a problem for all the response's that u can give me because i can read english pretty well (yeah, im a lazzy a.s.s. to learn it as should have to).
Second, im learning android right now and had been developing an app for like a month. The problem is that my app have an actionbar Menu on the Activity that contains 3 fragments THAT ARE ADDED BY a VIEWPAGER, so i can't cast them in activity to run their methods.... Thats a big problem!. Each one of those fragments have several EditText, and what i want is to USE MY ACTIVITY ACTIONBAR MENU ITEM CLICK to store all data from the EdtiText's and store it in an SQLite Database; one table per fragment.
I have been done everything and the only thing that i need isis to know how to call methods from the three fragments when pressing an item, on the onOptionClickListener OF THE MENU ITEM OF MY ACTIVITY. (The most important thing is that is the menu of my activity, not the fragment's, and i cant instantate the fragments on my activity because im using viewpager to create them).
Sorry again of my mispell's, and sorry for not posting my code, but, is really large so instead of make it clear my problem im gonna confuse everbody, so its better that you can help me withow the need of my really large code, so thanks for understanding and helping me.
There is a class for this.
Check Observer class. actually is nothing too complicated. You can easily remake this behave.
*just make a interface with a method
public interface MyObserverInterface {
//the code that will run when a save button is clicked in your menu
//fragment
public void starAction();
}
*make your fragments implament this interface.
*create a second class in wich you will get a reference to your fragments
public class MyObserver {
List<Fragment> listFragments;
//make sure your fragments implement the MyObserverInterface interface
public MyObserver(Fragment fragment1, Fragment fragment2) {
listFragments = new ArrayList<Fragment>();
listFragments.add(fragment1);
listFragments.add(fragment2);
}
public void startActionInAllFragments(){
for(int n=0;n<listFragments.size();n++){
listFragments.get(n).starAction();
}
}
}
Now just create an instance of MyObserver class in your fragment and call its method startActionInAllFragments()
let me know if it worked for u.

Updating edittext from fragment

I currently have the following situation:
1) The "main view" which contains the EditText I'm trying to update. (Let's call it mainView)
2) A fragment that is opened whenever I click in a button that is contained in the "main view", the
fragment receives mainView as parameter.
3) An OnClickListener which is set to a button that is contained by the fragment. This listener receives the fragment as parameter.
Basically what I need to do is, each time I click on the button that triggers the listener, I need to update the editText, however it doesn't seem to be working. I believe it has something to do with "notifying" the view, but I haven't been able to get it working no matter what I try. After I update the text I close the fragment and
Basically the code is the following:
public void onClick(View v){
String newMessageContent = "hello world";
fragment1.mainView.editText1.setText(newMessageContent);
FragmentManager manager = this.fragment1.getActivity().getFragmentManager();
manager.beginTransaction().replace(R.id.container,this.fragment1.mainView.getPlaceHolderFragment()).commit();
}
Please note that I have simplified the problem a little bit and changed the name of the fragment/views in order for you guys to understand better. The text "hello world" is actually dynamic, and depends no another parameter that is received by the OnClickListener.
After I click the fragment does get replaced, so I know the onClickListener is working correctly, however I believe there's something wrong with the way the data change is being notified.
I've already looked at many SO questions, however none of them have helped me to achieve what I need.
Any help is appreciated, thanks.
I suggest implementing an interface, say, IUpdateFromFragment with method, say, onUpdate(String message), then let activity implement that interface and inside the fragment just call something like ((IUpdateFromFragment)this.getActivity()).onUpdate(newMessageContent);
I realized the problem was that each time I replaced the fargment via the fragmentManager, the method setActivityView was being called again, which replaced the EditText content.
In order to avoid this, I manually removed the fragment (instead of replacing it), doing the following:
FragmentManager manager = this.selectTemplateFragment.getActivity().getFragmentManager();
manager.beginTransaction().remove(this.selectTemplateFragment).commit();
Update the fragment via transaction, then within the fragment1 class OnViewCreated, you can do mainView.editText1.setText("whatever");
The way you're doing this now, I'm surprised isn't throwing an exception since the view isn't inflated yet.

Where to put the Fragment functional code?

Just a general question about working with Fragments and Activitys for android development: where does the business end of the functional code go for Fragments loaded into an Activity dynamically? (i.e. a fragment's OnClickListeners, OnCheckedChangedListeners, button logic methods...)
Do they go in the Fragment class, or the Activity class?
All the GUI logic for views attached to a fragment should be contained inside the fragment itself.
Thus a fragment should be as self contained as possible.
You can, though, if necessary do callbacks to your activity based on fragment GUI interaction. This can easily be done like this inside the fragment:
#Override
public void onAttach(Activity activity) {
if (!(activity instanceof SherlockFragmentActivity)) {
throw new IllegalStateException(getClass().getSimpleName()
+ " must be attached to a SherlockFragmentActivity.");
}
mActivity = (SherlockFragmentActivity) activity;
super.onAttach(activity);
}
In this specific case the reason for gaining a reference to SherlockFragmentActivity is to gain access to the support menu inflater mActivity.getSupportMenuInflater(), hence the construction can of course also serve to gain information from the underlying activity.
This probably depends on how much the Fragment's functionalities have in common, and how many, let's say Buttons, have to be handled.
I personally (and it's probably most common practice) handle onClick(...) events separately for each Fragment, meaning that I let each Fragment implement it's own OnClickListener.
Furthermore, when handling everything through the Activity, probably not all the components that react to click-events are in memory at all times and can be reached via findViewById(...), depending on which Fragment is currently displayed and how your user-interface is built up in general.
they always in fragment class because fragment is one type of component in android which we can reuse it. if we put onclick and oncheckchanged in activity then what meaning of reusing that component??
for more information about please go through following step:
Link 1 for basic level of information about fragment and how to handle them
Link 2 for dealing with multi pane fragment
Standard site for fragment
It depends:
If fragment can handle logic which is self sufficient(complete) then that code can be handled by fragment. e.g. on click call phone number.
If fragment have UI whose action is activity specific, then you want to add listener in activity.
e.g. master detail view like email client, on tablet user click on title fragment1 which have list of email titles, then handler on click in activity can show detail fragment2 in activity.
In all you want to keep fragment reusable.

Switching between layouts from the same activity: Possible but recomended?

I want to know why do people keep recommending starting new Activities when you want to display another screen?
Let's say I want to display a screen with a label and an edit_text to ask for username, then another similar screen to ask for age, then another screen to display the data entered and ask for confirmation.
I did this:
main_layout.xml: has a button let's say mainButton, onClick="startRegistration"
name_layout.xml: edittext asking for name
age_layout.xml: edittext asking for age
confirm_layout.xml: display info + button to confirm
and in:
public class MainActivity extends Activity {
onCreate(...) {
...
setContentView(R.layout.main_layout);
}
public void startRegistration(View clickedButton) {
setContentView(R.layout.name_layout);
}
..
}
... and so on, all button handlers are public void methods in main class and each method contains setContentView() with the next layout as parameter.
I have a feeling this is bad programming style, however it works perfectly fine. Is it ok to do this? If not, is there any other easy way? Starting a new activity for such things feels really stupid to me.
Normally you group 'activities' together in an Activity. For you, registration uses multiple screens but are linked to each other. I would suggest using 1 Activity with a ViewFlipper.
Having 1 Activity for all will screw up the navigation for the user. The Back key has to be handled specially. "if back key, set this content, else set this content, etc"
If you code different layouts for the same type of screen then its not really an ideal idea. The better idea is to have the same layout and point to the same layout from the classes where the layouts are the same. In the screen where you want to have an extra/less control or different control then just have unique IDs to such controls.
Refer the controls from their IDs and you will have a single layout file. Writing different layout classes where the controls are same will pave way to code repetition and hence is not an ideal way of coding.

Categories

Resources