What will I learn?
- Using Tab layout
- User Viewpager
- Displaying list of static user in the fragment
Requirement
- A PC/laptop with any Operating system such as Linux, Mac OSX, Windows OS
- Preinstalled Android Studio, Android SDK, and JDK
Note: This tutorial is performed in Android Studio on the laptop with Windows 10 Home, 64 bit OS
Difficulty
Anybody with basic knowledge of Android can grasp the tutorial
Tutorial Content
In the previous tutorial we made login system, one time login and we also retrieved the data from firebase database. Now in this tutorial we will be learning to setup view for our MainActivity. We will be using Viewpager and TabLayout. User will be able to view all the list of user, chats and online user in their MainActivity. In order to use TabLayout we have to implement google support library in our gradle file
implementation 'com.android.support:design:26.1.0'
As we already have added the dependency for google’s support library.Now, let us open content_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:orientation="vertical"
android:layout_height="match_parent"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:context="com.programminghub.simplechat.MainActivity"
tools:showIn="@layout/activity_main">
<android.support.design.widget.TabLayout
android:id="@+id/tab_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabTextAppearance="@android:style/TextAppearance.Widget.TabWidget"
app:tabGravity="fill"/>
<android.support.v4.view.ViewPager
android:id="@+id/main_viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
Here tablyout is used to display the tabs just below the toolbar and viewpager is used to allow the user to swipe left and right to navigate between the tabs. As we set up the layout we will be needing separate fragment to represent each tab.
We will be creating a blank fragment.
And we will name it ShowUserListFragment.
We will be commenting some of the code of our ShowUserListFragment and I will be explain those codes for later section. Now the ShowUserListFragment looks like this:
public class ShowUserListFragment extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
// private OnFragmentInteractionListener mListener;
public ShowUserListFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment ShowUserListFragment.
*/
// TODO: Rename and change types and number of parameters
public static ShowUserListFragment newInstance(String param1, String param2) {
ShowUserListFragment fragment = new ShowUserListFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_show_user_list, container, false);
}
// TODO: Rename method, update argument and hook method into UI event
/* public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}*/
@Override
public void onAttach(Context context) {
super.onAttach(context);
/* if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}*/
}
@Override
public void onDetach() {
super.onDetach();
// mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
/* public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}*/
}
As we successfully created the fragment now let us set up our viewpager and tablayout to make our UI functionable. So, let us open MainActivity.java
In order to allow user to swipe smoothly using ViewPager we will have to write a class called VIewPagerAdapter so that we can define which fragment can be shown of each page. Here getCount() returns the total no of fragments we will be using and getItem returns the particular fragment whereas addFragment adds the fragment in the list.
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
@Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
@Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
@Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
Now we have to set up the custom adapter to the viewpager and finally we have to set up our tablayout with the viewpager.
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
// adapter.addFragment(new CuriosityModeFeatured(),"Featured");
adapter.addFragment(new ShowUserListFragment(), "Users");
adapter.addFragment(new ShowUserListFragment(),"Chats");
adapter.addFragment(new ShowUserListFragment(),"Online");
viewPager.setAdapter(adapter);
tabLayout.setupWithViewPager(viewPager);
}
Here initially we are calling the constructor of the VIewPagerAdapter and passing fragmentmanager as argument. After that we are adding fragment by calling addFragment method of ViewPagerAdapter and we are setting up our viewpager the adapter by valling viewpage.setAdapter() and finally we are setting up our tablayout with the viewpager so that the tab also changes as we swipe left/right. The final code of MainActivity looks like this:
public class MainActivity extends AppCompatActivity {
TabLayout tabLayout;
ViewPager viewPager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
defineView();
bindView();
}
private void defineView(){
tabLayout=findViewById(R.id.tab_layout);
viewPager=findViewById(R.id.main_viewpager);
}
private void bindView(){
setupViewPager(viewPager);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
// adapter.addFragment(new CuriosityModeFeatured(),"Featured");
adapter.addFragment(new ShowUserListFragment(), "Users");
adapter.addFragment(new ShowUserListFragment(),"Chats");
adapter.addFragment(new ShowUserListFragment(),"Online");
viewPager.setAdapter(adapter);
tabLayout.setupWithViewPager(viewPager);
}
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
@Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
@Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
@Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
}
Now let us run our application
We will get our output like this:
Here we can see that we successfully created three tabs names users, chats and online. The swipe is also working perfectly.
Now we successfully set up our main landing page layout. In all the three tabs we will be showing is list of users. So we will be using RecyclerView to show list of uses. As all the layout will be showing same view we shouldn’t write three separate fragment that is the reason why we only made one fragment.
Now let us open fragment_show_user_list.xml and add RecyclerView there
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.programminghub.simplechat.ShowUserListFragment">
<android.support.v7.widget.RecyclerView
android:id="@+id/show_userL_list"
android:layout_width="match_parent"
android:layout_height="match_parent">
</android.support.v7.widget.RecyclerView>
</FrameLayout>
Now open ShowUserListFragment.java and we will be displaying some static values in our recycler view.
private List<User> setUpUserList(){
List<User> userList=new ArrayList<>();
userList.add(new User("[email protected]","1",""));
userList.add(new User("[email protected]","1",""));
userList.add(new User("[email protected]","1",""));
return userList;
}
Here we have set up some static list values to show it in our RecyclerVIew. We will be needing adapter for recyclerview to show individual user. We will also be needing a view to define how individual user will look like. So le us create a new layout called item_user.xml.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<ImageView
android:id="@+id/show_user_profile"
android:layout_width="80dp"
android:layout_height="80dp"
android:src="@drawable/ic_add_profile"/>
<TextView
android:id="@+id/show_user_email"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
Here we have defined one imageview to display user image and one Textview to display user email. Now let us write corresponding adapter for this view. We will name it UserListAdapter. It looks like this:
public class UserListAdapter extends RecyclerView.Adapter<UserListAdapter.ViewHolder> {
List<User> userList;
public UserListAdapter(List<User> userList) {
this.userList = userList;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return new ViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_user,null));
}
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.bindView(userList.get(position));
}
@Override
public int getItemCount() {
return userList.size();
}
class ViewHolder extends RecyclerView.ViewHolder{
TextView email;
public ViewHolder(View itemView) {
super(itemView);
email=itemView.findViewById(R.id.show_user_email);
}
public void bindView(User user){
email.setText(user.getEmailAddress());
}
}
}
Now as we have set up the adapter now let us open our SHowUserListFragment and write below code to display users in recycler view
LinearLayoutManager layoutManager=new LinearLayoutManager(getContext());
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
showUserList.setLayoutManager(layoutManager);
UserListAdapter listAdapter=new UserListAdapter(setUpUserList());
showUserList.setAdapter(listAdapter);
}
This is it. Now let us run our application
We will get output like this:
We successfully got the list of user. Here the list of users show in static. That is they are not from our firebase database. In our next session we will be displaying the user list from firebase and removing these static list.
All above codes are available in my Github. Click here to download.
Curriculam
Using firebase Database to create a chat application in Android : Part I
Using Firebase Database to create a chat application in Android : Part II
Using Firebase Database to create a chat application in Android : Part III
Posted on Utopian.io - Rewarding Open Source Contributors
Hey @programminghub, your contribution was rejected by the supervisor @jestemkioskiem because he found out that it did not follow the Utopian rules.
Upvote this comment to help Utopian grow its power and help other Open Source contributions like this one. Do you want to chat? Join me on Discord.
Downvoting a post can decrease pending rewards and make it less visible. Common reasons:
Submit
Your contribution cannot be approved because it does not follow the Utopian Rules.
I appreciate your tutorial, it's of high quality, but the repository you've chosen is not strictly related to the project you're writing about. Please, fix that issue and contact me for an another review.
You can contact us on Discord.
[utopian-moderator]
Downvoting a post can decrease pending rewards and make it less visible. Common reasons:
Submit
@jestemkioskiem I updated the github repo that may best suite for this tutorial please rereview it or update if you find better one. Thank You
Downvoting a post can decrease pending rewards and make it less visible. Common reasons:
Submit
Hey! Sorry to miss this comment, I was not available due to personal issues. I've asked our developer to manually upvote your comment instead. Again, sorry for the inconvenience.
Downvoting a post can decrease pending rewards and make it less visible. Common reasons:
Submit
@jestemkioskiem thanks
Downvoting a post can decrease pending rewards and make it less visible. Common reasons:
Submit
@jestemkioskeim At the first part of this series I kept github repo as https://github.com/aosp-mirror/platform_dalvik and then one of the moderator changed it to android/android-studio-poet , from then I 'm using it as github repo, if this is also the wrong repo, please update it what seems to be accurate repo for this tutorial as supervisor or moderator has access to change the github repo.
Downvoting a post can decrease pending rewards and make it less visible. Common reasons:
Submit
Hey @jestemkioskiem, I just gave you a tip for your hard work on moderation. Upvote this comment to support the utopian moderators and increase your future rewards!
Downvoting a post can decrease pending rewards and make it less visible. Common reasons:
Submit
Thank you for the contribution. It has been approved.
You can contact us on Discord.
[utopian-moderator]
Downvoting a post can decrease pending rewards and make it less visible. Common reasons:
Submit
Hey @rdvn, I just gave you a tip for your hard work on moderation. Upvote this comment to support the utopian moderators and increase your future rewards!
Downvoting a post can decrease pending rewards and make it less visible. Common reasons:
Submit