- How to add «UP» back button in fragment (Fragment to Activity)
- 5 Answers 5
- how to go back to previous fragment on pressing manually back button of individual fragment?
- 10 Answers 10
- Update (and probably a better answer)
- Android Fragment handle back button press [duplicate]
- 25 Answers 25
- Back button fragments android
- Комментарии RSS по email OK
- Navigation Drawer back button in fragments
- 5 Answers 5
How to add «UP» back button in fragment (Fragment to Activity)
I want to go from fragment to activity using back button using toolbar back icon.
The fragment is my navigation drawer item & activity is my MainActivity.
5 Answers 5
You can use app:navigationIcon=»?attr/homeAsUpIndicator» for that back navigation icon.
Call this method in your fragment onCreateView
Try this worked for me :
Create an back arrow icon in drawable folder. Name it ‘ic_back_button’. Not sure how :-
just right click on drawable > new > ImageAsset > Clip Art > Search back > select > OK > Finish (don’t forget to change the name).
then Inside your fragment in onCreateView :
Add this xml code to your fragment and try
You can easily do that, if you are using a Custom back button that is placed on your Custom top app bar, in the button’s onClick() function you can call.. getActivity().onBackPressed(); it would work the same as if you have clicked the android navigation’s back button.
Источник
how to go back to previous fragment on pressing manually back button of individual fragment?
I have only one activity and multiple fragments in my application.
Two main fragment A(left) and B(right).
All fragments have individual back buttons.
So when I press back button of fragment A1, it should go back to A, similarly when Back button from B2 is pressed, B1 appears and from B1 to B and so on.
How to implement this type of functionality?
10 Answers 10
I have implemented the similar Scenario just now.
Activity ‘A’ -> Calls a Fragment ‘A1’ and clicking on the menu item, it calls the Fragment ‘A2’ and if the user presses back button from ‘A2’, this goes back to ‘A1’ and if the user presses back from ‘A1’ after that, it finishes the Activity ‘A’ and goes back.
See the Following Code:
Activity ‘A’ — OnCreate() Method:
Fragment : ‘A1’
I am replacing the existing fragment with the new Fragment when the menu item click action happens:
Activity ‘A’ — onBackPressed() Method:
Since all the fragments have one parent Activity (which is ‘A’), the onBackPressed() method lets you to pop fragments if any are there or just return to previous Activity.
If you are looking for Embedding Fragments inside Fragments, please refer the link: http://developer.android.com/about/versions/android-4.2.html#NestedFragments
@trueblue’s answer got me going with one minor but annoying issue. When there is only one fragment on the backstack and you press back button, that frame is removed and the app remains active with a blank screen. User needed to press back button one more time to exit the app. I modified the original code to the following in order to handle this situation
When there is only 1 fragment in the backstack, we are basically telling android to move the whole app to back.
Update (and probably a better answer)
So after doing some more reading around this, I found out that you can add fragment manager transactions to back stack and then android handles back presses automatically and in a desired way. The below code snippet shows how to do that
The last line shows how you add a transaction to back stack. This solves back press issue for fragments in most situations except for one. If you go on pressing back button, then eventually you will reach a point when there is only one fragment in the back stack. At this point, you will want to do one of the two things
- Remove the activity housing the fragment from the back stack of the task in which activity is running. This is because you do not want to end up with a blank activity
- If the activity is the only activity in the back stack of the task, then push the task in background.
In my case, it was the later, so I modified the overridden onBackPressed method from my previous answer to look like below
This code is simpler because it has less logic and it relies on framework than on our custom code. Unfortunately I did not manage to implement code for first situation as I did not need to.
Источник
Android Fragment handle back button press [duplicate]
I have some fragments in my activity
And on Back Button Press I must to return from [2] to [1] if current active fragment is [2], or do nothing otherwise.
What is the best practise to do that?
EDIT: Application must not return to [2] from [3]. [6]
25 Answers 25
When you are transitioning between Fragments, call addToBackStack() as part of your FragmentTransaction :
If you require more detailed control (i.e. when some Fragments are visible, you want to suppress the back key) you can set an OnKeyListener on the parent view of your fragment:
I’d rather do something like this:
if you overide the onKey method for the fragment view you’re gonna need :
Use addToBackStack method when replacing one fragment by another:
Then in your activity, use the following code to go back from a fragment to another (the previous one).
If you want to handle hardware Back key event than you have to do following code in your onActivityCreated() method of Fragment.
You also need to check Action_Down or Action_UP event. If you will not check then onKey() Method will call 2 times.
Also, If your rootview(getView()) will not contain focus then it will not work. If you have clicked on any control then again you need to give focus to rootview using getView().requestFocus(); After this only onKeydown() will call.
Источник
Back button fragments android
28 октября 2014
В Android-приложениях иногда требуется особым образом обработать нажатие кнопки back. Если у вас не используются фрагменты, всё просто. Перекрываем метод onBackPressed у Activity и делаем что нам нужно. Если же используются фрагменты и по нажатию back необходимо что-то поменять в фрагменте, обработку хочется сделать именно в нём.
Посмотрев ответы на эту тему на StackOverflow я был несколько удивлён. Предлагается либо ненадёжный способ через OnKeyListener , либо жёсткий хардкод. Попробуем сделать это более красиво и удобно.
Начнём с интерфейса для фрагментов. Готового в фреймворке нет, сделаем свой:
Далее перекроем метод onBackPressed в нашем FragmentActivity :
Вытаскиваем все фрагменты, которые у нас есть. Ищем первый попавшийся, который реализует наш интерфейс OnBackPressedListener . Тут можно было придумать что-то, чтобы работать с несколькими обработчиками, но чаще всего он один. Если есть фрагмент, который реализует OnBackPressedListener , вызываем его единственный метод. Если нет — обрабатываем back как обычно.
Ну и, наконец, сам фрагмент:
Плюс данного подхода в том, что можно, например, отнаследовать все наши activity от MyActivity и использовать OnBackPressedListener без каких-либо изменений в коде MyActivity .
Комментарии RSS по email OK
Александр, смотрю ты уже на Android перешел. Мобильная разработка всех поглощает? Или это просто хобби 🙂
Я не ограничиваю себя какой-то одной технологией или языком. В случае андройда это не хобби. Коммерческий проект.
Согласен. Я то в моб. разработке дальше ionicframework(cordova) не пошел пока.
Спасибо за ваш вариант. На основе вашего у меня родилось следующее решение:
Я новечек важно ваше мнение. Конструкция вроде работает. Но могут ли быть с ней проблемы?
Могут. Как минимум, стоит учитывать, что использоваться может более одного фрагмента в одном activity.
В ListActivity это выглядит примерно так:
А как такое сделать в ListFragment и обычном Activity?
Sam, а почему вы пишете «андроЙд»? Или вы с такой же ошибкой пишите слова «плазмоЙд», «гиперболоЙд», «стероЙд» и «планетоЙд»? Домашнее задание: попробуйте произнести вслух эти слова так, как они написаны — с буквой «Й». Постарайтесь при этом не завязать язык в узел.
Капитан О., описочка вышла. Кстати, произнести с «й» вполне получается и при этом ничего в узел не завязывается. Это сочетание звуков вполне характерно для английского.
Спасибо за статью! Очень наглядный пример как ловить onBackPressed в фрагментах)
Источник
Navigation Drawer back button in fragments
I started creating of app which use one activity (Navigation Drawer) and many fragments. But I unable to use toolbar back button to navigate back from fragments. Hardware back button works perfectly. I know that I need to override onOptionsItemSelected , catch android.R.id.home , check if there are something in back stack and than pop it. After changing fragment, «burger» button changes to «back arrow», but when I click on it onOptionsItemSelected never fired, just opens the NavigationDrawer menu.
Here the code from activity:
And how I change (replace) fragments from HomeFragment :
5 Answers 5
setNavigationOnClick() on the toolbar after setSupportActionBar(toolbar) :
I have made a small app for reference
I had the same issue.
I finally solved by adding this in the onCreate method.
Add below code in onCreate() method that’s work for me
Simplest solution for Kotlin Developers
Just add this in your root activity where fragments resist
Here, whenever setDisplayHomeAsUpEnabled is set true , I am showing back button. and on cliking it, I am calling super.onBackPressed() which is similar to what your back button does!
The thing that solved me the issue was this:
I used the code that came automatically with the NavigationDrawerActivity template, and it was something like this:
And I struggled a lot with many tricks and hacks, and nothing was working for me.
At some point, I have noticed that the fragments that I want to enable the back button are «being considered as top level destinations«, exactly what the comment says in the code above. Then I removed those sub-fragments and BOOM that was it, with not a single hack or line of code needed, this is provided out of the box, I just needed to pay attention to it.
So in my case, I changed to the below code:
Источник