Where should the code go; in Fragment or in Activity? - android

Imagine this situation:
Activity.
Activity contains layout with 2 fragments. FragmentA and FragmentB
FragmentA has a layout with a button that should print a toast "Hello".
FragmentB has a layout with a button that should print a toast "Bye".
Both buttons have a onClick attribute set. First one with "sayHello" and second one with "SayBye".
So which is the correct way of finally displaying the toast?
Case A:
public class ActivityCustom extends FragmentActivity{
[...]
public void sayHello(View v){
//SHOW TOAST HERE
}
public void sayBye(View v){
//SHOW TOAST HERE
}
}
Case B:
public class ActivityCustom extends FragmentActivity{
[...]
public void sayHello(View v){
((FragmentA)this.findFragmentById(R.id.fragmentA)).showToast();
}
public void sayBye(View v){
((FragmentB)this.findFragmentById(R.id.fragmentB)).showToast();
}
}
I'm a bit confused about that.
Because if we delegate all the work on the fragments, I guess Activity will be kinda clear of code. It will just have the code to "connect" the two fragments, right?

I think this is a matter of OOP principles specifically "encapsulation", i don't think activity should contain code that do not care about, hence the proper way taking on count your example would be having each toast message in the Fragment because is their behavior and in case of modifications you actually know where to go, unlike having everything in the activity becoming the single point for every single functionality losing maintainability and extensibility, since there will be a point where all your code will rely on your activity. By the way there's nothing wrong on having Activities with just a few code, is actually good to keep code out of activity if it doesn't have to do with the activity life cycle itself...
Regards!

I believe you should show the toasts in each fragment. In FragmentA's onCreateView method, you get the button, add the listener and show the toast in the onCLick() method there. Same on FragmentB.
No problem for the activity to have less code.

Related

Programmatically show Layout to preface an activity

What I want to do:
I want to have multiple activities each prefaced with a page explaining to the user what the activity is about.
What I'm currently doing:
So my main class BaseModuleActivity extends Activity and I am trying to write a function called showTutorial() which will explain the next steps to the users.
Here is my attempt in doing so:
public void showTutorial(String title, String explanation){
setContentView(R.layout.tutorial_screen);
TextView tv1 = (TextView)findViewById(R.id.tutoTextTitle);
tv1.setText(title);
TextView tv2 = (TextView)findViewById(R.id.tutoTextExplanation);
tv2.setText(explanation);
findViewById(R.id.tutoButton).setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
//remove the tutorial's view
findViewById(R.id.tutoLayout).setVisibility(View.GONE);
}
});
}
And this method is called in the following:
public class myFirstActivity extends BaseModuleActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
//First show tuto
super.showTutorial(getString(R.string.upTitle),getString(R.string.upExplanation));
//TODO then actually do the activity stuff
/*
(findViewById(R.id.next_button)).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
finish();
}
});
*/
}
}
Problem:
I think the problem is mainly conceptual. I don't know the best approach to do this and the approach I'm taking is not working.
What I'm doing is not working because the view just become empty. I thought setting the visibility of the linearLayout to gone would make it disappear and the actual activity will able to take place.
What I need:
I need to understand if I can do what I want with my approach or not? Or what approach should I take.
I found some similar questions. However, the answer to these questions didn't seem to fit my problem.
I also looked into layout inflater and fragment, but layout inflater seem to be more for listView and fragment uses layout inflater.
Well, there are some approaches to show a guide for your activity (or application).
First one, and probably the easiest, is to show a dialog/TextView when user enters an activity and explain the activity guide in that dialog/TextView using plain text. From your explanation, I think this one is what your are trying to do.
Second one is to use something like slides with pictures to explain about your activity (like Google Sheets application).
Third one is to explain each control in your activity separatly by highlighting them (similar to how Go Launcher explains its feature on first launch)
You can find more info in below links:
How to implement first launch tutorial like Android Lollipop apps: Like Sheets, Slides app?
Android - first launch interactive tutorial
Seems that what you want is actually an introduction. Take a look at this project:
https://github.com/rubengees/introduction
From each introduction page you can launch the correspondent activity.

Continuous notification from one Activity to another

How can I have an activity B, which pops up and partially obscures a "parent" activity A, continuously send update info to A?
The normal mechanism, of course, would be to send an Intent back to A. But this can only happen once, when calling finish().
I suppose another way would be to have a handler in A and let B post to the handler. Getting the handler from A to B could be done through a "global" Application member.
Is there a better way?
EDIT: Using DialogFragment appears to be a good solution. However there is a position issue with DialogFragment. Please see my new post: https://stackoverflow.com/questions/30471032/position-dialogfragmet-relative-to-view
As far as I know, an Activity always covers another Activity. At any point, Android could reclaim memory and destroy Activity A.
This means that you should manage your data differently. Either through your Application instance, if there is not much to share.
But you probably should consider another storage mechanism. What kind of data do you want to pass to your Activity A ? And what do you mean by "partially obscures"?
EDIT
I would suggest that your DialogFragment keeps a reference to your Activity. Take a look at the developer page. You can try to implement something like this:
In you Activity, when you would like to show your dialog:
void showDialog() {
DialogFragment newFragment = MyAlertDialogFragment.newInstance(
R.string.alert_dialog_two_buttons_title);
newFragment.setActivity(this);
newFragment.show(getFragmentManager(), "dialog");
}
In your DialogFragment class, simply implement a setter method:
public static class MyAlertDialogFragment extends DialogFragment {
Activity activity;
//rest of the code here
public void setActivity(Activity a){
this.activity = a;
}
private void notifyActivity(){
int level = aMethod();
activity.somethingHappened(level);
}
}
Now, everytime you would like to call a method of your Activity, use the reference you passed previously.
I would also make an Interface, and make your Activity implement it. Like this, you are not dependent on one specific Activity, but it could be any UI component. Hope it helps.

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.

How to Handle back button for Fragment in android?

I would like handle back button in my application i have used fragment class in whole application .So when i would like to come back to base activity,it throw out application,Please give me any suggestion.
You just need to override the onBackPressed method on your activity.
#Override
public void onBackPressed() {
//Put your logic here :)
}
I dont understand what you want to do, but if you want to implement your own code in the back button this is how you do it.
#Override
public void onBackPressed() {
// your code
}
If you do nothing, then nothing will happen on a back press.
Edit: perhaps the above is not at all what you want, I've some difficulties understanding you. However, if you properly want to understand activities and how they are managed / created this is a must read. http://developer.android.com/guide/components/tasks-and-back-stack.html

Accessing members within mainThread from Activity or Fragment

I have a class called MainGamePanel that extends SurfaceView where I run a thread that handles my updating and drawing code. Then I have an activity which runs editor.xml file which contains a Relative layout which runs my MainGamePanel and a FrameLayout which I am using as a container to hold a fragment. So I have the MainGamePanel taking up 2/3 of the screen and the fragment is on the right taking the remaining 1/3 of the screen.
The fragment contains a button that I want to use to reset objects that are located within my MainGamePanel. How can I access a member of MainGamePanel from my fragment or vice versa?
Here is the code for my fragment where I check for the button click
Button button = (Button) view.findViewById(R.id.resetGrid_button);
// A simple OnClickListener for our button. You can see here how a Fragment can encapsulate
// logic and views to build out re-usable Activity components.
button.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
Activity activity = getActivity();
if (activity != null)
Toast.makeText(activity, R.string.reset_button, Toast.LENGTH_LONG).show();
}
});
Instead of just doing the toast I would like to have it reset some objects located in my MainGamePanel surfaceView class. Thank you for your time and any information you can send my way.
Answered:
I figured out that I have to get a handle to my view inside of my activity and have the activity access the information. Then when the user clicks the button in my fragment, I let the activity know and update the information.
you need to create an interface to communicate between the Activity and Fragment,
follow this example -
http://developer.android.com/training/basics/fragments/communicating.html
once your Activity knows about the pressed button you should call a public method within your custom class that will handle the desired logic.

Categories

Resources