From a view (a custom status bar) I need to know when the activity is paused and resumed. Is it possible?
Is it possible?
Yes and very easily.
Declare a interface and provide its implementation via your inner view to the outer activity.
Call the respective delegate in the onResume and onPause of activity to notify your inner view.
Simple. Hope this helps :)
Something like this
class MyActivity extends Activity {
public interface ActivityLifeCycleLister{
onResumeCalled();
}
public ActvityLifeCycleLsistener listener;
public void setActivityLifeCycleListener(ActvityLifeCycleLsistener listener) {
this.listener = listener;
}
#Override
public void onResume(){
super.onResume();
if(listener != null) {
listener.onResumeCalled();
}
}
class MyInnerView extends View {
// Some init method
void init() {
MyActivity.setActivityLifeCycleListener(new ActivityLifeCycleListener() {
void onResumeCalled() {
// Do whatever here
}
});
}
}
}
This approach can be used for all the components of your application who wants to listen life cycle events.
You can just create two methods onResume() and onPause() of your custom View (you can call this two methods whatever you want). Then in your activity you will have override onResume and onPause and call customView.onResume() and customView.onPause().
Related
long story short.
I have the mainActivity with two Fragments. So instead of the mainActivity there are the two Fragments.
In the first Fragment there is a Switch.
Is it possible to update the background from the mainActivity when the switch is checked or unchecked? The Background is set in the content_main.xml, because then you have no transition when changing the fragments.
So is it at all possible?
I thought this would work:
if(switch.isChecked()) {
SharedPreferences sharedPref = getActivity().getSharedPreferences("my_prefs", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt("background1", R.drawable.background2);
editor.apply();
}
And in the MainActivity:
SharedPreferences sharedPref = getSharedPreferences("my_prefs", Context.MODE_PRIVATE);
int bg = sharedPref.getInt("background1", R.drawable.background1);
getWindow().setBackgroundDrawableResource(bg);
Or is it just not possible because the fragment isn't loading itself new?
If so. How is it possible?
Thanks in advance guys
source:
Changing background of an activity from another activity
Use callback interface to communicate between fragment and your activity
Please see the below code snippet :
public class YourFragment extends Fragment{
OnCallbackReceived mCallback;
// Implement this interface in your Activity.
public interface OnCallbackReceived {
public void Update(boolean state);
}
In your fragment :
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mCallback = (OnCallbackReceived) activity;
} catch (ClassCastException e) {
}
}
// You can Call the event from fragment as mentioned below
// mCallback is the activity context.
mCallback.Update(switch.isChecked());
Activity :
public class MainActivity extends Activity
implements YourFragment.OnCallbackReceived {
// Implemented method.
public override void Update(boolean state) {
// Update bg here
}
Original:
How to send data from fragment to activity
use Otto event bus,It's easy and simple
Click this link
add this to your dependencies
implementation compile 'com.squareup:otto:1.3.8'
Activity or Fragment onCreate add this one
Bus bus = new Bus();
You can post event like this from your activity or fragment
bus.post(new AnswerAvailableEvent(42));
if you want to get events even when your fragment is in the foreground or background, Subscribe to the events like below
#Subscribe public void answerAvailable(AnswerAvailableEvent event) {
// TODO: React to the event somehow!
}
Don't forget to register and unregister in onStart and onStop
#Override
protected void onStart(){
super.onStart();
bus.register(this);
}
#Override
protected void onStop(){
super.onStop();
bus.unregister(this);
}
Yes, it's possible to achieve that. I think the easiest way to do so is through a listener/callback.
First of all, create your listener class:
public interface MyCallback {
void onSwitchStateChanged(boolean isChecked);
}
After that, make your Activity implement that interface, and implement your background changing logic inside the onSwitchStateChanged method.
Now, inside your Fragment's onAttach() method, do the following (this example is in Kotlin):
override fun onAttach(context: Context?) {
super.onAttach(context)
if (context is MyCallback) {
myListener = context as MyCallback
}
else {
throw RuntimeException("Must implement MyCallback!")
}
}
Where myListener is a variable inside your fragment.
Now add a setOnCheckedChangeListener on your switch, like it's described on this answer, and use the callback inside it. For example (in Java):
mySwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
myListener.onSwitchStateChanged(isChecked);
}
});
I think this question may simple but I didn't find any solution for this,
I there any way in Android that if any one of an activity calls onPause() I need to show Toast message or any notification kind of thing need to show. Generally I want to get notified when activity calls onPause() but I need it in one place since I may have some 15 activity I don't want to add it in all the activity.
ex:If I have activity when any one of the activity calls onPause I need to get notified but that notification code should be in one place and we should not add any line of code onPause() Is it possible to do this.
Thanks.
Create a baseActivity, which has for example :
open class BaseActivity : AppCompatActivity() {
override fun onPause() {
super.onPause()
Toast.makeText(this, "notified", Toast.LENGTH_SHORT).show()
}
}
Then you can extends this in your activities and handle the on pause call in BaseActivity
If your minSdkVersion >= 14, you can use Application.ActivityLifecycleCallbacks: ActivityLifecycleCallbacks
You have to define a custom Application class and you can register for this callbacks afterwards:
public class MyApplication extends Application {
private class LifecycleCallbacks implements Application.ActivityLifecycleCallbacks {
#Override
public void onActivityCreated(final Activity activity, final Bundle savedInstanceState) {
//nothing to do
}
#Override
public void onActivityDestroyed(final Activity activity) {
//nothing to do
}
#Override
public void onActivityPaused(final Activity activity) {
// TODO Do your stuff, e.g. show toast.
}
#Override
public void onActivityResumed(final Activity activity) {
//nothing to do
}
#Override
public void onActivitySaveInstanceState(final Activity activity, final Bundle outState) {
//nothing to do
}
#Override
public void onActivityStarted(final Activity activity) {
}
#Override
public void onActivityStopped(final Activity activity) {
}
}
private final LifecycleCallbacks callbacks;
public void onCreate() {
super.onCreate();
callbacks = new LifecycleCallbacks();
application.registerActivityLifecycleCallbacks(callbacks);
}
}
Create a BaseActivity which contain all the methods you want to use in all other activities.
Then extend every activity with BaseActivity to call onPause() method.
Could any one help me out with this situation.
I have implemented OnUserInteraction() method for Android Activity it is working fine for me.
But I want it for Fragments too.How can i able call OnUserInteraction() or is there any another way to identify userInteraction with the UI.
#Sunil's answer causes java.lang.StackOverflowError so I corrected it. Below code works smoothly
Create a java class in your app named UserInterationListener and put below code there
public interface UserInteractionListener {
void onUserInteraction();
}
Then create an instance variable in your activity, for this interface as below
private UserInteractionListener userInteractionListener;
Then implement a setter method for this variable, in your activity.
public void setUserInteractionListener(UserInteractionListener userInteractionListener) {
this.userInteractionListener = userInteractionListener;
}
Now override the onUserInteraction method of your activity and if the listener variable is not null, invoke the interface method.
#Override
public void onUserInteraction() {
super.onUserInteraction();
if (userInteractionListener != null)
userInteractionListener.onUserInteraction();
}
Now, in your fragment class, implement UserInteractionListener as below
public myFragment extends Fragment implements UserInteractionListener
also override interface's method
#Override
public void onUserInteraction(){
//TODO://do your work on user interaction
}
then in your fragment invoke your activity's userinteraction setter method like below
((YourActivity) getActivity()).setUserInteractionListener(this);
this last part is important.
There is another way around.
Create a listener in your activity as below
public interface UserInteractionListener {
void onUserInteraction();
}
Then create an instance variable in your activity, for this interface as below
private UserInteractionListener userInteractionListener;
Then implement a setter method for this variable, in your activity. (You can even keep a List of eventlistener objects, if you want to pass same userinteraction to multiple consumers)
public void setUserInteractionListener(UserInteractionListener userInteractionListener) {
this.userInteractionListener = userInteractionListener;
}
Now override the onUserInteraction method of your activity and if the listener variable is not null, invoke the interface method.
#Override
public void onUserInteraction() {
super.onUserInteraction();
if (userInteractionListener != null)
userInteractionListener.onUserInteraction();
}
Now, in your fragment class, register for events as below
((YourActivity) getActivity()).setUserInteractionListener(new YourActivity.UserInteractionListener() {
#Override
public void onUserInteraction() {
// Do whatever you want here, during user interaction
}
});
In my main Activity, I have a DialogFragment that contains a FragmentTabHost. I have two tabs, one that is a DialogFragment and one that is a ListFragment. When either the 'OK' button is pressed in the inner DialogFragment or when an element in the ListFragment is pressed, I want to pass two Strings (that are entered in two TextView's in the inner DialogFragment and are displayed in each element in the ListFragment) back to the Activity, but I am unsure of how to do this with multiple levels of Fragments.
Any help is appreciated!
There's no magic.
You can achieve with two approaches.
Use callback.
Create interface and class to pass the data through child Fragment to Activity. You don't need to modify bridged TabHostFragment as Fragment always rely on its mother Context (Activity) no matter how many fragments wrap the fragment.
public class TwoStrings {
public TwoStrings(String one, String two){
this.one = one;
this.two = two;
}
public String one;
public String two;
}
First, declare interface.
public interface DataPassListener {
void dataPassed(TwoStrings data);
}
And, implement interface in Activity.
public class MainActivity extends Activity implements DataPassListener {
#Override
public void dataPassed(TwoStrings data) {
// do something with data.
Log.d("string one", data.one);
Log.d("string two", data.two);
}
}
Finally, let child Fragment acknowlege that mother Activity has the callback listener.
public class DialogFragment1 extends DialogFragment {
DataPassListener listener;
#Override
public void onAttach(Activity activity) {
if (activity instanceOf DataPassListener)
listener = (DataPassListener) activity;
}
public void setDataPassListener(DataPassListener listener){
listener = ((DataPassListener) listener);
}
public void doSomeThing(){
if(listener != null) // important to prevent NullPointerException
listener.dataPassed("a", "b");
}
}
Use EventBus.
I prefer to use Otto in order to publish and subscribe data.
To subscribe event for listening in Activity,
public class MainActivity extends Activity {
#Override
public void onResume() {
super.onResume();
BusProvider.getInstance().register(this);
}
#Override
public void onPause() {
super.onPause();
BusProvider.getInstance().unregister(this);
}
#Subscribe
public void onUpdateTwoStrings(TwoStrings event) {
// do something with data.
Log.d("string one", data.one);
Log.d("string two", data.two);
}
}
And, publish event in anywhere in Fragment.
bus.post(new TwoStrings("a", "b"));
Take a look at setTargetFragment() and getTargetFragment() methods. You could connect fragments with each other through it without any additional callbacks and libs.
I am using android annotations and have some code that I need to execute in the onResume() function in my activity.
Is it safe to just override the onResume function from the android annotation activity (ie with #EActivity)?
Yeah, you should use these lifecycle methods just like with plain Android activities. There is one thing though: injected Views are not yet available in your onCreate method, this is why #AfterViews exist:
#EActivity(R.layout.views_injected)
public class ViewsInjectedActivity extends Activity {
#ViewById
Button myButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// myButton is not yet available here
}
#AfterViews
void setupViews() {
// myButton is first available here
myButton.setText("Hello");
}
#Override
protected void onResume() {
super.onResume();
// just as usual
}
}
Yeah. Just call super.onResume() and then add your code.
I'd do it just like their on create example here: https://github.com/excilys/androidannotations/wiki/Enhance-activities
You can bind your custom class with lifecycle component of android. It holds life cycle information of android component so that your custom class observe lifecycle changes.
public class MyObserver implements LifecycleObserver {
#OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
public void connectListener() {
...
}
#OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
public void disconnectListener() {
...
}
}
myLifecycleOwner.getLifecycle().addObserver(new MyObserver());