Android custom onBackPressed to OnBackPressedCallback - java

I have this custom back press:
override fun onBackPressed() {
if (condition()) {
doSomething()
} else {
super.onBackPressed()
}
}
I can't seem to find a way to make it a OnBackPressedCallback,
private fun setupBackPress() {
onBackPressedDispatcher.addCallback(owner = this) {
if (condition()) {
doSomething()
} else {
onBackPressedDispatcher.onBackPressed()
// I don't know what to do in this case,
// this here would be an infinite loop
// but I need to just make it like super.onBackPressed()
}
}
}
Any ideas? thanks

Related

How to setCancelable(false) for standard dialog PreferenceFragmentCompat

I'm using PreferenceFragmentCompat to display and set SharedPreferences. This all works fine. However, I keep getting "W/InputEventReceiver: Attempted to finish an input event but the input event receiver has already been disposed." in my logs, because the standard dialog used by PreferencesFragmentCompat does not seem to use the .setCancelable(false) in its showDialog method. I guess I could build my own custom dialog, but that seems a bit of an overkill just to solve this one small problem. Is there any way to simply overwrite the method?
Update:
It was enough to add this to my PreferencesFragmet (removed MultiSelectListPreferenceDialogFragmentCompat, as I don't use it)
#Override
public void onDisplayPreferenceDialog(Preference pref) {
DialogFragment dialogFragment = null;
String DIALOG_FRAGMENT_TAG = "androidx.preference.PreferenceFragment.DIALOG";
if (pref instanceof EditTextPreference) {
dialogFragment = EditTextPreferenceDialogFragmentCompat.newInstance(pref.getKey());
} else if (pref instanceof ListPreference) {
dialogFragment = ListPreferenceDialogFragmentCompat.newInstance(pref.getKey());
}
if (dialogFragment != null) {
dialogFragment.setTargetFragment(this, 0);
dialogFragment.setCancelable(false); //adding this!
if (this.getFragmentManager() != null) {
dialogFragment.show(this.getFragmentManager(), DIALOG_FRAGMENT_TAG);
}
} else {
super.onDisplayPreferenceDialog(pref);
}
}
I sorted though PreferenceFramgnetCompat source code to solve this issue.
Unfortunately, you can't execute '.setCancelable(false)' to dialog without callback or override.
I'll explain it with callback.
You should implement 'PreferenceFragmentCompat.OnPreferenceDisplayDialogCallback' interface on activity which contains PreferenceFragmentCompat fragment.
When user press a preference one of EditTextPreference, ListPreference or AbstractMultiSelectListPreference, the onPreferenceDisplayDialog method will be executed.
When onPreferenceDisplayDialog method is executed, you should open dialog.
Fortunately, there are three type dialog and Google provide it by public so you don't need to make a custom dialog for them.
Just create instance of dialog and call setCancelable(false) and show it!
Please refer below codes.
class SettingsActivity : FragmentActivity(), PreferenceFragmentCompat.OnPreferenceDisplayDialogCallback {
private val DIALOG_FRAGMENT_TAG = "android.support.v7.preference.PreferenceFragment.DIALOG"
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
supportFragmentManager.beginTransaction()
.replace(android.R.id.content, SettingsFragment(), "setting_fragment").commit()
}
override fun onPreferenceDisplayDialog(caller: PreferenceFragmentCompat, preference: Preference?): Boolean {
// check if dialog is already showing
if (supportFragmentManager!!.findFragmentByTag(DIALOG_FRAGMENT_TAG) != null) {
return true
}
val f: DialogFragment
if (preference is EditTextPreference) {
f = EditTextPreferenceDialogFragmentCompat.newInstance(preference.getKey())
} else if (preference is ListPreference) {
f = ListPreferenceDialogFragmentCompat.newInstance(preference.getKey())
} else if (preference is AbstractMultiSelectListPreference) {
f = MultiSelectListPreferenceDialogFragmentCompat.newInstance(preference.getKey())
} else {
throw IllegalArgumentException("Tried to display dialog for unknown " + "preference type. Did you forget to override onDisplayPreferenceDialog()?")
}
f.setTargetFragment(supportFragmentManager.findFragmentByTag("setting_fragment"), 0)
f.isCancelable = false // !! HERE !!
f.show(supportFragmentManager!!, DIALOG_FRAGMENT_TAG)
return true
}
}

Terminating Android Timer if user doesn't use the App(Prevent running in the background)

I have a Timer in my App that infinitely runs an Animation. like this:
Timer t = new Timer();
t.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
//Running Animation Code
}
});
}
}, 1000, 1000);
Now I realized that this code runs even if user click Back Button of android. if fact it runs in the background and it seems uses a lot of memory.
I need this code run ONLY if user in the app. In fact when user click on Back Button, this Timer goes to end and if user clicks on Home Button, after a while that user doesn't use the App, terminates this Timer.
What I need is to prevent using memory. Because i realized if this codes runs a while, App freezes! I need a normal behavior.
If your Activity is the last element in the BackStack, then it will be put in the background as if you pressed the Home button.
As such, the onPause() method is triggered.
You can thus cancel your animation there.
#Override protected void onPause() {
this.timer.cancel();
}
You should as well start your animation in the onResume() method.
Note that onResume() is also called right after onCreate(); so it's even suitable to start the animation from a cold app start.
#Override protected void onResume() {
this.timer.scheduleAtFixedRate(...);
}
onPause() will be also called if you start another Application from your app (e.g: a Ringtone Picker). In the same way, when you head back to your app, onResume() will be triggered.
There is no need to add the same line of code in onBackPressed().
Also, what's the point in stopping the animation in onStop() or onDestroy()?
Do it in onPause() already. When your are app goes into the background, the animation will already be canceled and won't be using as much memory.
Don't know why I see such complicated answers.
You can do it like this, in onBackPressed() or onDestroy(), whatever suits you.
if (t != null) {
t.cancel();
}
If you need, you can start timer in onResume() and cancel it in onStop(), it entirely depend on you requirement.
If a caller wants to terminate a timer's task execution thread
rapidly, the caller should invoke the timer's cancel method. - Android Timer documentation
You should also see purge and
How to stop the Timer in android?
Disclaimer: This might not be the 100% best way to do this and it might be considered bad practice by some.
I have used the below code in a production app and it works. I have however edited it (removed app specific references and code) into a basic sample that should give you a very good start.
The static mIsAppVisible variable can be called anywhere (via your App class) in your app to check if code should run based on the condition that the app needs to be in focus/visible.
You can also check mIsAppInBackground in your activities that extend ParentActivity to see if the app is actually interactive, etc.
public class App extends Application {
public static boolean mIsAppVisible = false;
...
}
Create a "Parent" activity class, that all your other activities extend.
public class ParentActivity extends Activity {
public static boolean mIsBackPressed = false;
public static boolean mIsAppInBackground = false;
private static boolean mIsWindowFocused = false;
public boolean mFailed = false;
private boolean mWasScreenOn = true;
#Override
protected void onStart() {
applicationWillEnterForeground();
super.onStart();
}
#Override
protected void onStop() {
super.onStop();
applicationDidEnterBackground();
}
#Override
public void finish() {
super.finish();
// If something calls "finish()" it needs to behave similarly to
// pressing the back button to "close" an activity.
mIsBackPressed = true;
}
#Override
public void onWindowFocusChanged(boolean hasFocus) {
mIsWindowFocused = hasFocus;
if (mIsBackPressed && !hasFocus) {
mIsBackPressed = false;
mIsWindowFocused = true;
}
if (!mIsWindowFocused && mFailed)
applicationDidEnterBackground();
if (isScreenOn() && App.mIsAppVisible && hasFocus) {
// App is back in focus. Do something here...
// this can occur when the notification shade is
// pulled down and hidden again, for example.
}
super.onWindowFocusChanged(hasFocus);
}
#Override
public void onResume() {
super.onResume();
if (!mWasScreenOn && mIsWindowFocused)
onWindowFocusChanged(true);
}
#Override
public void onBackPressed() {
// this is for any "sub" activities that you might have
if (!(this instanceof MainActivity))
mIsBackPressed = true;
if (isTaskRoot()) {
// If we are "closing" the app
App.mIsAppVisible = false;
super.onBackPressed();
} else
super.onBackPressed();
}
private void applicationWillEnterForeground() {
if (mIsAppInBackground) {
mIsAppInBackground = false;
App.mIsAppVisible = true;
// App is back in foreground. Do something here...
// this happens when the app was backgrounded and is
// now returning
} else
mFailed = false;
}
private void applicationDidEnterBackground() {
if (!mIsWindowFocused || !isScreenOn()) {
mIsAppInBackground = true;
App.mIsAppVisible = false;
mFailed = false;
// App is not in focus. Do something here...
} else if (!mFailed)
mFailed = true;
}
private boolean isScreenOn() {
boolean screenState = false;
try {
PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);
screenState = powerManager.isInteractive();
} catch (Exception e) {
Log.e(TAG, "isScreenOn", e);
}
mWasScreenOn = screenState;
return screenState;
}
}
For your use you might want to create a method in your activity (code snippet assumes MainActivity) that handles the animation to call the t.cancel(); method that penguin suggested. You could then in the ParentActivity.applicationDidEnterBackground() method add the following:
if (this instanceof MainActivity) {
((MainActivity) this).cancelTimer();
}
Or you could add the timer to the ParentActivity class and then not need the instanceof check or the extra method.

Multiple click listeners on buttons

I want to know how to add multiple click events to buttons defined in XML, as previously, in Java, we implemented View.onClickListener interface and did the rest of the work in onClick method.
Example:
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.oneButton:
// do your code
break;
case R.id.twoButton:
// do your code
break;
case R.id.threeButton:
// do your code
break;
default:
break;
}
}
I'm making a basic calculator app with the new Kotlin but it seems Kotlin has no such provisions, instead my code looks too long and verbose, as I'm attaching events to all buttons individually.
Can someone tell me how to do the same way in Kotlin? Thanks
For multiple onClickListeners in kotlin (version:1.1.60), the following helped me. Hope it'll be useful to someone else too.
Implement OnClickListener to activity like:
class YourActivity : AppCompatActivity(), View.OnClickListener
set your button in onCreate():
val button = findViewById<Button>(R.id.buttonId)
and assign onclick to the button in onCreate():
button.setOnClickListener { onClick(button) }
and in the override method of onClick() :
override fun onClick(v: View) {
when (v.id) {
R.id.buttonId -> { //your code }
..
..
..
else -> { //your code }
}
}
Yes, in Kotlin you can do it like this:
view.setOnClickListener(object : View.OnClickListener {
override fun onClick(v: View?) {
when(v?.id) {
R.id.imgBack -> {/* do your code */}
R.id.twoButton -> {/* do your code */}
R.id.threeButton -> {/* do your code */}
else -> {/* do your code */}
}
}
}
You can try this following code:
class Testing:AppCompatActivity(), View.OnClickListener {
private val mButton1:Button
private val mButton2:Button
protected fun onCreate(savedInstanceState:Bundle) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_testing)
mButton1 = findViewById(R.id.btn_click) as Button
mButton2 = findViewById(R.id.btn_click1) as Button
mButton1.setOnClickListener(this)
mButton2.setOnClickListener(this)
}
fun onClick(view:View) {
when (view.getId()) {
R.id.btn_click -> {
Toast.makeText(this, "button 1", Toast.LENGTH_SHORT).show()
}
R.id.btn_click1 -> {
Toast.makeText(this, "button 2", Toast.LENGTH_SHORT).show()
}
else -> {}
}
}
}
I hope this is help you.
First of all implement OnClickListener in your Activity, like
class MainActivity : Activity , OnClickListener
then override its implementation like
func onClick(v:View) {
//use when here like
case R.id.youview -> {
// do your work on click of view
}
Don't forgot to set clicklistener on your View.
yourView.setOnClickListener(this)
Or for better understanding go step by step -
Implement OnClickListener in your Activity.
Compiler will ask you to implement overrided methods. Implement those.
Copy paste your java code which you wrote inside onClick method, that can be converted by kotlin itself or write down when conditions.
This code worked for me:
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
imgBack.setOnClickListener(this)
twoButton.setOnClickListener(this)
threeButton.setOnClickListener(this)
}
override fun onClick(view:View) {
when (view.id) {
R.id.imgBack -> {
Toast.makeText(this, "imgBack", Toast.LENGTH_SHORT).show()
}
R.id.twoButton -> {
Toast.makeText(this, "twoButton", Toast.LENGTH_SHORT).show()
}
else -> {}
}
}
Don't forget implement View.OnClickListener in your class.
you can create anonymous object from an inteface View.ClickListener and pass it to setOnClickListener function
private val clickListener = View.OnClickListener { p0 ->
when (p0.id) {
....
}
}
... setOnClickListener(clickListener)
Try below like this.
public class MainActivity extends Activity implements View.OnClickListener{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Button xyz = (Button) findViewById(R.id.xyz);
xyz.setOnClickListener(this);
}
#Override
public void onClick(View v) {
}}
More detailed information at https://androidacademic.blogspot.in/2016/12/multiple-buttons-onclicklistener-android.html

libgdx: InputAdapter does not work when resumed from browser

I have a Screen implementation with InputMultiplexer which is initialized in the show() method. The InputMultiplexer is initialized with InputAdapter and the Stage object.
The InputAdapter object listens for the back button.
class MyInputAdapter extends InputAdapter {
#Override
public boolean keyDown(int keycode) {
if (keycode == Keys.BACK) {
// do someting
return true;
}
return false;
}
}
class MyScreen implements Screen {
#Override
public void show() {
initInputProcessors();
}
private void initInputProcessors() {
if (backButtonInputProcessor != null) {
initInputMultiplexer();
Gdx.input.setCatchBackKey(true);
Gdx.input.setInputProcessor(inputMiltiplexer);
} else {
Gdx.input.setCatchBackKey(false);
Gdx.input.setInputProcessor(stage);
}
}
private void initInputMultiplexer() {
if (inputMiltiplexer == null) {
inputMiltiplexer = new InputMultiplexer();
inputMiltiplexer.addProcessor(backButtonInputProcessor);
inputMiltiplexer.addProcessor(stage);
}
}
}
All works fine, and the back button reacts without any problem.
The problem occurs, in the following scenario. I use admob. So when clicking an ad banner, this brings you to browser. When you are back from browser to the app, the back button is not intercepted and the application just exits.
I also tried calling the InitInputProcessors method inside the resume() method, same result.
The answer to my question on LibGDX forum has solved it. Following is the solution by skunktrader:
Try adding this to your android MainActivity
#Override
public void onResume() {
super.onResume();
theView.requestFocus();
theView.requestFocusFromTouch();
}
Where theView is the value returned from initializeForView().
Try to set your InputProcessor as null in hide() method. Like this:
#Override
public void hide() {
Gdx.input.setInputProcessor(null);
}

Observing an event in roboguice application in a custom view

Basing on the RoboGuice API for firing an event, inside my CustomButtonView implementation I have did like so:
#Override
public void onClick(View v) {
CommonApplication.getInstance().fireEvent(new InteractionButtonClicked());
// setSelected();
}
public class InteractionButtonClicked
{
public String getRef()
{
return (String)getTag();
}
}
// handle the click event
protected void handleClick(#Observes InteractionButtonClicked button) {
if (getTag().equals(button.getRef())) {
//do A
} else {
//do B
}
}
However, handleClick does not get called in this context=> when I set an #Observer in the main activity it's containing method does get called.
I'm trying to understand why, and if there is an option to observe the event in the Customview context...

Categories

Resources