Monday, 12 August 2019

Android View Pager with tab layout example


activity_main.xml File-


<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout     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:id="@+id/main_content"
   
android:layout_width="match_parent"
   
android:layout_height="match_parent"
   
android:fitsSystemWindows="true"
   
tools:context="com.activities.MainActivity">

    <
android.support.design.widget.AppBarLayout
       
android:id="@+id/appbar"
       
android:layout_width="match_parent"
       
android:layout_height="wrap_content"
       
android:paddingTop="@dimen/appbar_padding_top"
       
android:theme="@style/AppTheme.AppBarOverlay">

        <
include
           
android:id="@+id/toolbar"
           
layout="@layout/app_bar" />

        <
android.support.design.widget.TabLayout
           
android:id="@+id/tabs"
           
android:layout_width="match_parent"
           
android:layout_height="wrap_content"
           
android:background="@color/cb_grey"
           
app:tabGravity="fill"
           
app:tabMode="fixed"
           
app:tabSelectedTextColor="@color/black"
           
app:tabTextColor="@color/black_gray">

            <
android.support.design.widget.TabItem
               
android:id="@+id/tabItem_all_leads"
               
android:layout_width="wrap_content"
               
android:layout_height="wrap_content"
               
android:text="@string/tab_all_leads" />

            <
android.support.design.widget.TabItem
               
android:id="@+id/tabItem_incoming"
               
android:layout_width="wrap_content"
               
android:layout_height="wrap_content"
                
android:text="@string/tab_incoming" />

            <
android.support.design.widget.TabItem
               
android:id="@+id/tabItem_outgoing"
               
android:layout_width="wrap_content"
               
android:layout_height="wrap_content"
               
android:text="@string/tab_outgoing" />

        </
android.support.design.widget.TabLayout>

    </
android.support.design.widget.AppBarLayout>

    <
android.support.v4.view.ViewPager
       
android:id="@+id/container"
        
android:layout_width="match_parent"
       
android:layout_height="match_parent"
       
app:layout_behavior="@string/appbar_scrolling_view_behavior" />

</
android.support.design.widget.CoordinatorLayout>


MainActivity.java-

public class MainActivity extends AppCompatActivity implements TabLayout.OnTabSelectedListener {

private SectionsPagerAdapter mSectionsPagerAdapter;

private TabLayout tabLayout;

private ViewPager mViewPager;

private MyModel mData;



@Override

protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_main);

    Toolbar toolbar = findViewById(R.id.toolbar);

    tabLayout = findViewById(R.id.tabs);

    Intent intent = getIntent();
 
//** IF YOU WANT TO SELECT SPECIFIC TAB  */
 

    String tag = intent.getStringExtra("tag");

    if (tag.equalsIgnoreCase(MyFirebaseMessagingService.TAG)) {
        tabLayout.getTabAt(2).select();

    } 
 
    toolbar.setTitle(getString(R.string.txt_my_toolbar, tag));

    setSupportActionBar(toolbar);

    Objects.requireNonNull(getSupportActionBar()).setDisplayHomeAsUpEnabled(true);

    // Create the adapter that will return a fragment for each of the three

    // primary sections of the activity.



    tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);

    mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager(),   tabLayout.getTabCount());

    mViewPager = findViewById(R.id.container);

    mViewPager.setAdapter(mSectionsPagerAdapter);



   /* mViewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));

    tabLayout.addOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(mViewPager));*/



    tabLayout.setSelectedTabIndicatorColor(getResources().getColor(R.color.sky_blue));

    tabLayout.setSelectedTabIndicatorHeight((int) (3 * getResources().getDisplayMetrics().density));

    tabLayout.setTabTextColors(Color.parseColor("#727272"), Color.parseColor("#ffffff"));



    tabLayout.setTabTextColors(

            ContextCompat.getColor(this, R.color.black_alpha_40),

            ContextCompat.getColor(this, R.color.black)

    );



    tabLayout.addOnTabSelectedListener(this);

    mViewPager.addOnPageChangeListener(new   TabLayout.TabLayoutOnPageChangeListener(tabLayout));



}
 
@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();

    if (id == android.R.id.home) {

        onBackPressed();

        return true;

    }

    return super.onOptionsItemSelected(item);

}



@Override

public void onTabSelected(TabLayout.Tab tab) {

    mViewPager.setCurrentItem(tab.getPosition());

    mSectionsPagerAdapter.getItem(tab.getPosition());

}
 
@Override

    public void onTabUnselected(TabLayout.Tab tab) {

    }

    @Override

    public void onTabReselected(TabLayout.Tab tab) {

    }

    /**

     * A {@link FragmentPagerAdapter} that returns a fragment corresponding to

     * one of the sections/tabs/pages.

     */

    public class SectionsPagerAdapter extends FragmentStatePagerAdapter {

        int tabCount;



        public SectionsPagerAdapter(FragmentManager fm, int tabCount) {

            super(fm);

            this.tabCount = tabCount;

        }



        @Override

        public Fragment getItem(int position) {

            switch (position) {

                case 0:

                    return new AllLeadFragment();

                case 1:

                    return new IncomingFragment();

                case 2:

                    return new OutgoingFragment();

                default:

                    return null;

            }

        }


        @Override

        public int getCount() {

            return tabCount;

        }

    }

}
 
Fragmnt- 
 
public class AllLeadFragment extends Fragment {



    private static final String TAG = AllLeadFragment.class.getSimpleName();

    private ArrayList<MyModel> mAllLeads = new ArrayList<>();

    private RecyclerView.LayoutManager layoutManager;

    private RecyclerView recyclerView;

    private AllLeadsAdapter mAdapter = null;

    private ProgressDialog dialog;

    private Gson gson;

    private Type listType;

    private String mUserId;

    private Context mContext;


    public AllLeadFragment() {

        gson = new Gson();

        listType = new TypeToken<ArrayList<MyModel>>() {

        }.getType();

    }


    @Override

    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        mUserId = ((MainActivity) mContext).mId;

        if (!TextUtils.isEmpty(mLeadId))

            geAllLeads(mUserId);

    }



    @Override

    public void onActivityCreated(@Nullable Bundle savedInstanceState) {

        super.onActivityCreated(savedInstanceState);

        if (mContext == null) {

            mContext = getActivity();

        }

    }



    @Override

    public void onAttach(Context context) {

        super.onAttach(context);

        mContext = context;

    }



    @Override

    public void onDetach() {

        super.onDetach();

        mContext = null;

    }



    private void parseLeadsJson(JSONObject jsonObject) throws JSONException {

        JSONArray jsonArray = jsonObject.getJSONArray("data");

        mAllLeads = gson.fromJson(jsonArray.toString(), listType);

    }



    private void geAllLeads (final String mUserId) {

        dialog = new ProgressDialog(mContext);

        dialog.setMessage("Please wait...");

        dialog.show();

        StringRequest stringRequest = new StringRequest(Request.Method.POST, WEBAPI.getWEBAPI(APIType.MY_LEADS),

                new Response.Listener<String>() {

                    @Override

                    public void onResponse(String response) {

                        if (dialog.isShowing()) {

                            dialog.dismiss();

                        }

                        try {

                            if (response != null) {

                                JSONObject jsonObject = new JSONObject(response);

                                if (jsonObject.getBoolean("success") && jsonObject != null) {

                                    parseLeadsJson(jsonObject);

                                }

                                if (mAllLeads.size() > 0) {

                                  mAdapter = new AllLeadsAdapter(mContext, mAllLeads);

                                  recyclerView.setAdapter(mAdapter);

                                  if (mContext != null)

                                        recyclerView.addItemDecoration(new MyDividerItemDecoration(Objects.requireNonNull(mContext), LinearLayoutManager.VERTICAL, 5));

                                    recyclerView.setItemAnimator(new DefaultItemAnimator());

                                    layoutManager = new LinearLayoutManager(mContext);

                                    recyclerView.setLayoutManager(layoutManager);



                                    recyclerView.addOnItemTouchListener(new RecyclerTouchListener(mContext, recyclerView, new RecyclerTouchListener.ClickListener() {

                                        @Override

                                        public void onClick(View view, int position) {

                                            MyModel mData = mAllLeads.get(position);

                                            if (mData != null) {

                                                Intent intent = new Intent(mContext, LeadDetailsActivity.class);

                                                intent.putExtra("LEADS_MODEL", mData);

                                                startActivity(intent);

                                            }

                                        }



                                        @Override

                                        public void onLongClick(View view, int position) {



                                        }

                                    }));

                                } else {

                                    recyclerView.setBackgroundResource(R.drawable.no_lead);

                                }

                            } else {

                                Toast.makeText(getContext(), R.string.txt_some_thing_went, Toast.LENGTH_SHORT).show();

                            }

                        } catch (JSONException e) {

                        }

                    }

                },

                new Response.ErrorListener() {

                    @Override

                    public void onErrorResponse(VolleyError error) {

                        if (dialog.isShowing()) {

                            dialog.dismiss();

                        }

                        Log.d(TAG, "" + error);

                    }

                }

        ) {



            @Override

            protected Map<String, String> getParams() {

                Map<String, String> params = new HashMap<>();

                params.put(ParamsConstants.USER_ID, mUserId);

                return params;

            }



            @Override

            public Map<String, String> getHeaders() throws AuthFailureError {

                HashMap<String, String> headers = new HashMap();

                headers.put("Content-Type", WEBAPI.contentTypeFormData);

                return headers;

            }

        };

        stringRequest.setShouldCache(true);

        Application.getInstance().addToRequestQueue(stringRequest, "headerRequest");

    }



    @Override

    public View onCreateView(LayoutInflater inflater, ViewGroup container,

                             Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_all_leads, container, false);

        recyclerView = view.findViewById(R.id.recyclerView);

        return view;

    }
}
 


No comments:

Post a Comment