Полный список
— создаем экран с вкладками
— используем иконку в названии вкладки
— используем обработчик перехода между вкладками
Вкладки помогают логически разделить содержимое экрана. Вместо того, чтобы бегать по разным экранам, вы можете сделать вкладки и переключаться между ними. В этом уроке создадим приложение с вкладками и посмотрим их основные возможности.
Project name: P0761_Tab
Build Target: Android 2.3.3
Application name: Tab
Package name: ru.startandroid.develop.p0761tab
Create Activity: MainActivity
Пропишем тексты в strings.xml:
Удалим все дефолтное с экрана main.xml и добавим туда компонент TabHost из вкладки Composite:
Компонент добавился и притащил с собой еще кучу всего. Давайте смотреть. TabHost – корневой элемент вкладок. В нем вертикальный LinearLayout, в котором расположены TabWidget и FrameLayout. TabWidget будет отображать заголовки вкладок, а FrameLayout – содержимое вкладок. В этом FrameLayout мы размещаем все View-компоненты, которые хотим отображать на вкладках. Позже мы (в коде) сообщим вкладке, какой именно компонент она должна показать (явно укажем id), вкладка выберет из этой общей кучи нужный ей компонент и отобразит его, как свое содержимое.
По дефолту во FrameLayout созданы три LinearLayout – они могут быть использованы, как контейнеры для содержимого вкладок. Т.е. вы их заполняете компонентами, как вам необходимо, а потом в коде просто указываете id нужного LinearLayout-а и он со всем содержимым отобразится на вкладке.
Нам сейчас не нужны LInearLayout, мы не будем делать вкладки с сложным содержимым, разместим во FrameLayout просто несколько TextView.
В итоге main.xml получился такой:
Создадим еще один layout-файл — tab_header.xml:
Этот layout мы используем как свой экран для заголовка вкладки. Тут просто TextView.
Создайте в папке res папку drawable, если ее нет. В ней создайте файл tab_icon_selector.xml:
Подробно об этом можно почитать тут. Этот xml-файл мы укажем как картинку для заголовка вкладки. И когда система будет прорисовывать заголовок вкладки, она обратится к этому файлу, чтобы понять какую картинку ей отображать. Этот код будет возвращать стандартную Android картинку star_on, если вкладка выбрана (state_selected=»true»). Иначе вернет star_off. Далее увидим это в приложении, и станет понятней.
Находим компонент TabHost. Обратите внимание, используется андроидный id. Он был таким по умолчанию при добавлении компонента в main.xml. В принципе, в нашем случае, этот id можно сменить на свой. Далее вызываем обязательный метод setup. Это первичная инициализация. В этом методе TabHost находит в себе TabWidget и FrameLayout. Вот их id в main.xml менять нельзя. Иначе TabHost будет ругаться, что не может их найти.
Далее создаем три вкладки. Для создания используется метод newTabSpec, на вход он берет тэг. Тэг – это просто некий строковый идентификатор вкладки. Позже увидим, где он используется. Для первой вкладки задаем название методом setIndicator. В метод setContent передаем id компонента (из FrameLayout), который мы хотели бы видеть в качестве содержимого вкладки. В нашем случае это TextView. Метод addTab присоединяет готовую вкладку к TabHost.
Вторая вкладка создается аналогично, только используем другую реализацию метода setIndicator. Заголовок вкладки может содержать не только текст, но и картинку. И здесь мы это используем – передаем в метод текст и xml вместо картинки. Тот самый xml, который определяет картинку по состоянию вкладки. Разумеется, если вам нужна статичная картинка, вы можете указать ее и не использовать xml вообще.
При создании третьей вкладки используем еще одну реализацию метода setIndicator, которая берет на вход View и его ставит как заголовок. Используем тут наш layout-файл tab_header.
Вкладки созданы. Устанавливаем (setCurrentTabByTag) вторую в качестве выбранной по умолчанию. И пропишем (setOnTabChangedListener) для TabHost обработчик, который срабатывает при переключении вкладок. Будем выводить сообщение с тэгом вкладки.
Все сохраним и запустим приложение.
Выбрана вторая вкладка, т.к. мы это определили методом setCurrentTabByTag. Ее содержимое – это TextView с как мы и указывали в коде в методе setContent при создании вкладки.
У третьей вкладки заголовок соответствует содержимому tab_header, т.к. мы использовали setIndicator, который принимает на вход View.
Выберем первую вкладку.
Сработал обработчик и появилось сообщение с тэгом выбранной вкладки. Содержимое первой вкладки – это TextView с из FrameLayout.
Обратите внимание, что сменилась картинка на заголовке второй вкладки. Это обеспечил selector из res/drawable/tab_icon_selector. В зависимости от состояния вкладки он выдает разные картинки.
На следующем уроке:
— используем Activity в качестве содержимого вкладки
— используем TabActivity
Присоединяйтесь к нам в Telegram:
— в канале StartAndroid публикуются ссылки на новые статьи с сайта startandroid.ru и интересные материалы с хабра, medium.com и т.п.
— в чатах решаем возникающие вопросы и проблемы по различным темам: Android, Kotlin, RxJava, Dagger, Тестирование
— ну и если просто хочется поговорить с коллегами по разработке, то есть чат Флудильня
— новый чат Performance для обсуждения проблем производительности и для ваших пожеланий по содержанию курса по этой теме
Источник
Полный список
— используем Activity в качестве содержимого вкладки
— используем TabActivity
В качестве вкладки можно использовать Activity. Для этого существует реализация метода setContent, которая принимает на вход Intent. А в Intent мы прописываем, какое Activity нам нужно.
При использовании Intent и вкладок есть нюанс. Наше основное Activity, которое содержит TabHost должно наследовать не android.app.Activity как обычно, а android.app.TabActivity. В этом случае нам не надо заморачиваться с дополнительной инициализацией для работы с Intent.
Project name: P0771_TabIntent
Build Target: Android 2.3.3
Application name: TabIntent
Package name: ru.startandroid.develop.p0771tabintent
Create Activity: MainActivity
Пропишем тексты в strings.xml:
Менять id у TabHost в случае использования android.app.TabActivity нельзя. Иначе система просто не найдет TabHost.
FrameLayout не заполняем, т.к. мы не будем использовать его компоненты для содержимого вкладок. Мы будем туда целые Activity грузить.
Создадим пару Activity.
Не забываем прописать их в манифесте.
Наше Activity наследует TabActivity. Это дает нам возможность получить TabHost методом getTabHost. Нам не нужно самим искать его на экране. Также этот замечательный метод выполняет за нас обычную инициализацию, нам не надо вызывать метод setup, как на прошлом уроке. И кроме обычной инициализации, этот метод выполняет подготовку для работы с Activity, как содержимым вкладок.
Ну а далее вам все знакомо с прошлого урока. Создаем вкладки, указываем имена. В методе setContent вместо содержимого из FrameLayout мы даем Intent, указывающий на необходимое нам Activity.
Все сохраняем и запускаем приложение.
Первая вкладка с OneActivity
Вторая вкладка с TwoActivity
А как отрабатывают события Activity LifeCycle? При первом показе первой вкладки срабатывают три метода OneActivity: onCreate, onStart, onResume. Переключаемся на вторую вкладку – срабатывает onPause в OneActivity, а потом три метода TwoActivity: onCreate, onStart, onResume. И далее при переключениях между вкладками одна уходит в onPause, другая возвращается в onResume.
На следующем уроке:
— вручную создаем содержимое вкладки
Присоединяйтесь к нам в Telegram:
— в канале StartAndroid публикуются ссылки на новые статьи с сайта startandroid.ru и интересные материалы с хабра, medium.com и т.п.
— в чатах решаем возникающие вопросы и проблемы по различным темам: Android, Kotlin, RxJava, Dagger, Тестирование
— ну и если просто хочется поговорить с коллегами по разработке, то есть чат Флудильня
— новый чат Performance для обсуждения проблем производительности и для ваших пожеланий по содержанию курса по этой теме
Источник
Haider Mushtaq
Oh Lord, Make me Brave and Make my Path Easy for me !
Tutorial for Creating Android Swiping Application using Tabbed Activity on Android Studio
Why make this Tutorial?
The reason I am making this tutorial is that I wanted to make an application in which the user could swipe through different images. When I decided to create a new application, I came across this “Tabbed Activity” icon. I thought that this could help guide me. Once I opened it up and wanted to make it work, I got stuck. I decide to get help from the internet but unfortunately discovered that there was little or no material concerning Tabbed Activity on the Internet. I then went through the code, line by line trying to understand how it works and finally got it to work. I thought that I should write a tutorial to help someone like me who is also stuck with Tabbed Activity.
NOTE: If you have ideas about what should I add or how to further make this tutorial complete, do inform me. Thanks for your consideration.
Setting it Up!
Start by creating a new Project in Android Studio:
Enter the Application name and press Next:
Choose the Platform i.e Phone and Tablet then press Next:
Now the wizard would ask you to Add and activity to Mobile, you have to select Tabbed Activity which in my case was located in the end. Press Next after selecting it.
This window allows us to Choose options for your new file, we will let it stay as is and press Finish. A thing to note here is that you can choose to change Navigation Style of your tabbed activity but we will stick with the default which in our case is Swipe View (ViewPager).
After you press Finish, it will take some time to set things up. If it pops up some error, something similar to the one I encountered, it means that you either need to update your Android Studio or need to install missing components, or both.
To upgrade, go to Toolbar’s: Help > Check for Updates…
Choose to update and Restart when the dialog appears.
Next, you can install the missing components by clicking on the blue: “Install Repository and sync project“. This is written next to the Error message.
It will show you a licence, just accept and press install:
Now that everything is in order, Just give it a test run. In order to actually see what is happening, we need to add something to the fragment_main.xml file because it is empty by default.
Open fragment_main.xml, located in app > res > layout > fragment_main.xml
Now add a TextView with “Hello World”:
You can do this by dragging Text View and changing text to “Hello World” or what ever you want:
Now try doing a test Run:
Understanding how it works !
Look at the code in
app > java > yourPakage > MainActivity.java
The code that follows is the one we are really interested in :
The SectionsPagerAdapter class is a sub class of MainActivity class.
The getItem() is the most important method, that needs to be configured in order for it to display the fragments that you need to display.
Simply put, the “Fragment” that this method will return would be the one displayed in the Activity. So you need to put all your “Fragment” classes here and return them in the order you want them displayed. If you are unable to understand this, no need to sweat, just follow this tutorial and you will, -God Willing- understand it all.
Just know this, that there are many ways you can do this, using if conditions etc… I will use switch(position) to return my desired Fragment. The default code is shown here, I will make the changes in the next section.
The getCount() method returns the Total number of pages or the “Tabs”. This is where you can set the number of tabs. In this case, its set to 3. This means that there will be 3 Tabs. If you need to increase or decrease the number of tabs – this method needs to return the total number of tabs – so you need to make appropriate change here. If for example you have 5 tabs, you will change the line:
return 3; to return 5;
I have extracted PlaceholderFragment class and made it a class on its own. I have placed it in app > java > yourPakage > PlaceholderFragment.java
This makes no difference it all, but it would help you understand to code much better.
We can use PlaceholderFragment class as a template for our Fragment classes, the things that we would need to replace, i have marked in blue
Modifying the code to our Will !
Alright, now lets make our own Fragment and integrate it with the Tabbed Activity.
Firs off we will start by making the layout for our fragment. Lets call it my_fragment.xml.
We will do this by creating a new xml file in the layouts folder. app > res > layout > my_fragment.xml
You can do this by right clicking the layouts folder and choosing to create new xml layout.
I threw in a Button and a TextView, and also changed the color or my background… You can make this as you like… Here is the XML code: (The code written in Blue needs to be the same as it is going to be used in our code.
To do this right click on your pakage, select new and choose create new Java Class. I made a new class in my java directory and named it MyFragment : app > java > yourPakage > MyFragment.java
The code is as follows, I have removed all the unnecessary lines of code…
The class needs to extend Fragment
The newInstance() method needs to return the correct reference to our fragment as follows:
The MyFragment is the constructor method of our class, let it stay empty and public.
Here I am creating two new variables, one of type Button, and the other of type TextView, I will need to link them to the Button and TextView in my layout for this fragment.
The following is the most important method of our fragment, this links the fragment to its layout and we can also connect our Button and TextViews here by using findViewById method as we used to do in Activity.
You can think of onCreateView() method as onCreate() method of an Activity except that it has to return a view in the end.
In this onCreateView method, we will connect our fragment to our layout, my_fragment as follows:
Now we will connect our Button and TextView to those in our layout as follows, keeping in mind that we can only use findViewById() method from rootView:
I have configured my OnClickListner with my button here as follows:
Finally we need to return our View, rootView in this case:
Now our Fragment is all set, Now we just need to set it up so that it can be called by our MainActivity.java
After you have opened the MainActivity.java located in app > java > yourPakage > MainActivity.java search for the SectionsPagerAdapter Class which is a subclass of MainActivity Class go to the method getItem() :
The position is provided by Android’s OS. The position is responsible for the fragment that shows up. The first position is 0, so the first page that you want to be displaced should be returned when position is 0. You should know that you need to return an instance of a fragment, you can do this in various ways, by using if-else conditions etc… I have used switch.
If you are wondering why are you using instance of fragments and not constructors. The problem is that if we do that, every time we swipe and then later come back to our fragment, it will be reset, which we do not want.
The next thing that we need to is to tell our Adapter how many pages in total are there… i.e set the Max Value of Position. To do this you need to edit your getCount() method:
Previously the getCount() method returned the value 3, since we only want 2 pages to appear in our activity, we would replace it by 2.
31 Comments
Hi, sorry for this question but from here, do you have any idea how to place the tab bar at the bottom of the screen?
Then you can specify the alignment of your TabWidget, to align it at the bottom:
I am a newbie too, but it looks like you can modify your look in mainActivity.xml. I think you can use design tab to modify your bar to be under your fragment placeholder (simple, drag&drop) or change ‘manually’ settings in Text tab.
Great tutorial got this fragments down now!
Great tutorial got this fragments down now!
Great tutorial bro! Keep up the good work!
Thanks for this great Tutorial, I worked through was happy that i understood everything but at the very end the Fragment getItem() does not accept the type “Myfragment” but does rather want a usual Fragment. Unfortuneately a cast i not possible. Any ideas?
misstype in “Myfragment”? if you have copied the code exactly then it should be “MyFragment”
Maybe you just imported the ‘android.app.Fragment’, but you need to import the ‘android.support.v4.app.Fragment’.
I had the same problem and with this it works, hope I could help you.
error showing can’t find symbol variable “pager” …what to do??
Very helpful….Thanks alot
Great tutorial! Thanks Haider 🙂
How to change the Title of Action Bar whenever the tab changed (for example the title of action bar for first tab is “A”, then second tab the action bar will be “B”)
Great tutorial. I’m getting an error, “could not resolve symbol”, for inflater, container and savedInstanceState. I have imported android.view.LayoutInflater;
What could possibly be the reason ?
Is it possible to get the whole project that you build at the end?
When will you upload your part-3 tutorial? I am not getting the Tab names. How can I get the Tab names?
Excellent article Haider. I have one query. Is there a way to perform some operation on the various tabs using the MainActivity class MenuItems? Lets say I have a ExpandableListView in each of the tabs and I want to expand or collapse the Groups from the MainActivity menu items. How do I do that?
Is there a way to find which tab we are in (which fragment tab is selected by the user) from the MainActivity class?
good tutorial thank you!
This is the best tutorial I’ve found regarding the swipe layout thx!
Good Job Bro,
Keep up the good work 🙂
Hi, I am inflating different 2 fragment_xml based on the Section No. inside onCreateView() method .
Good work bro , Go ahead !
Genial. Saludos desde Argentina.
Thanks. It helped me a lot.
Muchas gracias por el tutorial mi amigo, lo quiero aplicar en el siguiente caso -> la base de datos manda informacion a mi app, y esta debe ser repartida en “n” fragmentos, ..como generaria fragmentos automaticos?, hay alguna otra forma de hacerlo? , espero tu respuesta muchas gracias ¡¡
This was such a great help! I was stuck for a long time getting this to work. Thank you.
Thank you very much! I was stuck too. Un saludo desde México
Amazing tutorial. I was overthinking the functionality of the template but now I see your tutorial, it is a lot easier.
Great tutorial i’ve did all what you learned and it’s perfect except by one thing in one of the fragments i have a button and it doesn’t work
Источник