Error while using ListFragement - java

I am developing an android app for online payment for which I want to display Lists of restaurants under the tab named Restaurants. Same as this some other tabs will have list below them and a few tabs will have form under them (if possible and not difficult otherwise I will stay with the lists only)
Here is the code I have written. It contains an error in the Adapter class and may be some logical errors which I am not sure about as this is my first ever android app.
Main.java File
package com.example.tabswithswipe;
import com.example.tabsswipe.adapter.TabsPagerAdapter;
import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.view.Menu;
public class MainActivity extends FragmentActivity implements
ActionBar.TabListener {
private ViewPager viewPager;
private TabsPagerAdapter mAdapter;
private ActionBar actionBar;
private String[] tabs = { "Retaurants", "Super Store", "Fuel Stations"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewPager = (ViewPager) findViewById(R.id.pager);
actionBar = getActionBar();
mAdapter = new TabsPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(mAdapter);
actionBar.setHomeButtonEnabled(false);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
for (String tab_name : tabs) {
actionBar.addTab(actionBar.newTab().setText(tab_name)
.setTabListener(this));
}
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
});
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
}
}
acivity_main.xml File
<android.support.v4.view.ViewPager
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent">
</android.support.v4.view.ViewPager>
items_list.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<ImageView
android:id="#+id/imageView1"
android:layout_width="50dp"
android:layout_height="50dp"
android:contentDescription="#string/app_name" />
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/app_name" />
</LinearLayout>
TabPagerAdapter.java Adapter File (Error in this file)
package com.example.tabsswipe.adapter;
import com.example.tabsswipe.*;
import android.app.ListFragment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
public class TabsPagerAdapter extends FragmentPagerAdapter {
public TabsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int index) {
switch (index) {
case 0:
return new SuperStoreFragment();
case 1:
return new FuelStationsFragment();
case 2:
return new RestaurantsFragment(); //Error Here
}
return null;
}
#Override
public int getCount() {
return 3;
}
}
RestaurantsFragment.java
package com.example.tabsswipe.adapter;
//import com.example.MainActivity.MyAdapter;
import com.example.tabswithswipe.R;
import android.app.ListFragment;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class RestaurantsFragment extends ListFragment {
LayoutInflater inflater;
ViewGroup container;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_main);
this.inflater = inflater;
View rootView = inflater.inflate(R.layout.list_items, container, false);
setListAdapter(new MyAdapter(getActivity(), android.R.layout.simple_list_item_1, R.id.textView1, getResources().getStringArray(R.array.items)));
return rootView;
}
private class MyAdapter extends ArrayAdapter<String>
{
public MyAdapter(Context context, int resource, int textViewResourceId,
String[] strings) {
super(context, resource, textViewResourceId, strings);
// TODO Auto-generated constructor stub
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
// LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View row = inflater.inflate(R.layout.list_items, container, false);
String [] items = getResources().getStringArray(R.array.items);
ImageView iv = (ImageView) row.findViewById(R.id.imageView1);
TextView tv = (TextView) row.findViewById(R.id.textView1);
tv.setText(items[position]);
if(items[position].equals("kfc"))
{
iv.setImageResource(R.drawable.kfc);
}
else if(items[position].equals("pizzaHut"))
{
iv.setImageResource(R.drawable.pizzahut);
}
else if(items[position].equals("Domino"))
{
iv.setImageResource(R.drawable.dominos);
}
else if(items[position].equals("hardees") )
{
iv.setImageResource(R.drawable.hardees);
}
else if(items[position].equals("TuttiFrutti"))
{
iv.setImageResource(R.drawable.tuttifrutti);
}
else if(items[position].equals("McDonalds"))
{
iv.setImageResource(R.drawable.mcdonalds);
}
else if(items[position].equals("21 Street"))
{
iv.setImageResource(R.drawable.ic_launcher);
}
return row;
}
}
// View rootView = inflater.inflate(R.layout.fragment_movies, container, false);
// return rootView;
// }
}
SuperStoreFragment.java
package com.example.tabsswipe.adapter;
import com.example.tabswithswipe.R;
import android.app.ListFragment;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class SuperStoreFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_super_stores, container, false);
return rootView;
}
}
fragment_super_stores.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#fa6a6a" >
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="Design Super Stores Screen"
android:textSize="20dp"
android:layout_centerInParent="true"/>
</RelativeLayout>
FuelStationsFragment.java
package com.example.tabsswipe.adapter;
import com.example.tabswithswipe.R;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class FuelStationsFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_fuel_stations, container, false);
return rootView;
}
}
fragment_fuel_stations.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#ff8400" >
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="Design Fuel Stations Screen"
android:textSize="20dp"
android:layout_centerInParent="true"/>
</RelativeLayout>
Please tell me how, where and what error occurred. Any kind of help will be really appreciated e.g. Tutorial, code example or even the error resolution of this code. Please ignore my silliness if any. Thank You.

Related

Fragment holding a RecyclerView not showing in the MainActivity

I'm trying to show a RecyclerView, in a fragment, in my main activity.
I'm not getting any errors, but the fragment remains empty, and I can't find the solution for this problem.
I simply have a fragment that has a recyclerview in it, I configure the recyclerview in HomeFragment.java, then in the MainParkActivity, I have a FrameLayout, which is replaced with the HomeFragment.
MainParkActivity
package com.example.ipark;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Log;;
public class MainParkActivity extends AppCompatActivity {
private static final String TAG = "MainParkActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate: started.");
Toolbar toolbar = findViewById(R.id.toolbar);
Fragment homeFragment = new HomeFragment();
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("iParc");
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, homeFragment).commit();
}
}
HomeFragment
package com.example.ipark;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import java.util.ArrayList;
public class HomeFragment extends Fragment {
private static final String TAG = "HomeFragment";
private ArrayList<String> mNames = new ArrayList<>();
private ArrayList<String> mImageUrls = new ArrayList<>();
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_home, container, false);
return rootView;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
RecyclerView recyclerView = view.findViewById(R.id.recycler_view);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
giveInformation();
RecyclerViewAdapter adapter = new RecyclerViewAdapter(getContext(), mNames, mImageUrls);
recyclerView.setAdapter(adapter);
}
private void giveInformation() {
mImageUrls.add("https://loremflickr.com/300/300/bmw");
mNames.add("BMW");
mImageUrls.add("https://loremflickr.com/300/300/bmw");
mNames.add("Audi");
mImageUrls.add("https://loremflickr.com/300/300/bmw");
mNames.add("Hyundai");
mImageUrls.add("https://loremflickr.com/300/300/bmw");
mNames.add("Mercedes");
mImageUrls.add("https://loremflickr.com/300/300/bmw");
mNames.add("BMW");
mImageUrls.add("https://loremflickr.com/300/300/bmw");
mNames.add("Audi");
mImageUrls.add("https://loremflickr.com/300/300/bmw");
mNames.add("Hyundai");
mImageUrls.add("https://loremflickr.com/300/300/bmw");
mNames.add("Mercedes");
}
}
RecyclerViewAdapter
package com.example.ipark;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import java.util.ArrayList;
import de.hdodenhof.circleimageview.CircleImageView;
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder>{
private static final String TAG = "RecyclerViewAdapter";
private ArrayList<String> mImageNames;
private ArrayList<String> mImages;
private Context mContext;
public RecyclerViewAdapter(Context mContext, ArrayList<String> mImageNames, ArrayList<String> mImages) {
this.mImageNames = mImageNames;
this.mImages = mImages;
this.mContext = mContext;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int i) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.layout_listitem, parent, false);
ViewHolder holder;
holder = new ViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, final int position) {
Log.d(TAG, "onBindViewHolder: called.");
Glide.with(mContext)
.asBitmap()
.load(mImages.get(position))
.into(holder.image);
holder.imageName.setText(mImageNames.get(position));
holder.parentLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "onClick: clicked on: " + mImageNames.get(position));
Toast.makeText(mContext, mImageNames.get(position), Toast.LENGTH_SHORT).show();
}
});
}
#Override
public int getItemCount() {
return mImageNames.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
CircleImageView image;
TextView imageName;
RelativeLayout parentLayout;
public ViewHolder(#NonNull View itemView) {
super(itemView);
image = itemView.findViewById(R.id.image);
imageName = itemView.findViewById(R.id.image_name);
parentLayout = itemView.findViewById(R.id.parent_layout);
}
}
}
}
XML for activity_main
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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:layout_height="match_parent"
tools:context=".MainParkActivity"
android:clipToPadding="false">
<include
android:id="#+id/toolbar"
layout="#layout/toolbar" />
<FrameLayout
android:id="#+id/fragment_container"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/toolbar">
</FrameLayout>
</android.support.constraint.ConstraintLayout>
XML for fragment_home
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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:layout_height="match_parent">
<android.support.v7.widget.RecyclerView
android:id="#+id/recycler_view"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_marginBottom="8dp"
app:layout_constraintBottom_toTopOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
In your fragment_home.xml, your Recyclerview has layout_height and layout_width 0dp. Change it to match_parent. Everything else in your code is correct. I'd have commented it, but I currently do not have commenting privileges! Accept it if you found it helpful!
In your activity_main layout, you have app:layout_constraintBottom_toTopOf="parent"
It should be app:layout_constraintBottom_toBottomOf="parent"
Your layout is currently displaying above the screen in your fragment.
use
adapter.notifyDataSetChanged();
after setting the adapter for RecycleView.

Recycler View not showing in fragment

I have three fragments: Fragment user, Fragment Home and Fragment Progress.
I'm trying to implement a recylcer view in the homefragment that can recycle images in the recycler view nothing is happening and no error is showing in logcat, i don't know what i'm doing wrong.
1.This is my Custom Adapter:
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.Collections;
import java.util.List;
public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.MyViewHolder>{
#NonNull
private LayoutInflater inflator;
List<Information> data= Collections.emptyList();
public CustomAdapter(Context context, List<Information> data){
inflator= LayoutInflater.from(context);
}
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view=inflator.inflate(R.layout.customlayout, parent,false);
MyViewHolder holder=new MyViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, int position) {
Information current=data.get(position);
holder.icon.setImageResource(current.images);
holder.title.setText(current.title);
}
#Override
public int getItemCount() {
return 0;
}
class MyViewHolder extends RecyclerView.ViewHolder{
ImageView icon;
TextView title;
public MyViewHolder(View itemView) {
super(itemView);
icon = (ImageView) itemView.findViewById(R.id.listicon);
title = (TextView) itemView.findViewById(R.id.textView);
}
}
}
This is my Fragment
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class HomeFragment extends Fragment {
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
private CustomAdapter adapter;
int[] IMAGES = {R.drawable.abs,R.drawable.arms,R.drawable.back,R.drawable.chest,R.drawable.full,R.drawable.legs};
private RecyclerView recyclerView;
ArrayList<HashMap<String, String>> data;
private String mParam1;
private String mParam2;
public HomeFragment() {
}
public static HomeFragment newInstance(String param1, String param2) {
HomeFragment fragment = new HomeFragment();
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);
}
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View layout = inflater.inflate(R.layout.fragment_home, container, false);
recyclerView =(RecyclerView) layout.findViewById(R.id.drawerList);
adapter = new CustomAdapter(getActivity(), getData());
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
return layout;
}
public static List<Information> getData(){
List<Information> data = new ArrayList<>();
int [] icons = {R.drawable.abs,R.drawable.arms,R.drawable.back,R.drawable.chest,R.drawable.full,R.drawable.legs};
String[] titles={"Abs","Arms","Back","Chest","full","legs"};
for (int i=0; i<icons.length && i<titles.length;i++){
Information current = new Information();
current.images=icons[i];
current.title=titles[i];
data.add(current);
}
return data;
}
}
I can't see to find what I'm doing wrong.
fragmenthome.xml
<?xml version="1.0" encoding="utf-8"?>
<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=".HomeFragment">
<android.support.v7.widget.RecyclerView
android:id="#+id/drawerList"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true">
</android.support.v7.widget.RecyclerView>
</FrameLayout>
4.Custom_layout.xml
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="#+id/listicon"
android:layout_width="match_parent"
android:layout_height="150dp"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
app:srcCompat="#mipmap/ic_launcher" />
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="62dp"
android:text="TextView" />
you didnt assign the data in your adapter's constructor
this.data = data;
then your item count should be
data.size();
should not be 0.

How to create android programming on layouts that have different ViewPager

How do I create android programming, If I click,
tab 1 - ViewPager1 Appears Fragment1 and ViewPager2 Appears Fragment1A
and
If I click,
tab 2 - ViewPager1 Appears Fragmen2 and ViewPager2 Appears Fragmen2A.
PagerAdapter.java
package com.papaozi.ground;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
public class PagerAdapter extends FragmentStatePagerAdapter {
int mNumOfTabs;
public PagerAdapter(FragmentManager fm, int NumOfTabs) {
super(fm);
this.mNumOfTabs = NumOfTabs;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
Satu tab1 = new Satu();
return tab1;
case 1:
Dua tab2 = new Dua();
return tab2;
default:
return null;
}
}
#Override
public int getCount() {
return mNumOfTabs;
}
}
ProfilActivity.java
package com.papaozi.ground;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.provider.ContactsContract;
import android.support.annotation.DrawableRes;
import android.support.design.widget.CoordinatorLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.text.Layout;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
public class ProfilActivity extends AppCompatActivity {
ViewPager simpleViewPager;
private TabLayout tabLayout, tabLayout2;
private ViewPager viewPager, viewPager2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profil);
viewPager = (ViewPager) findViewById(R.id.viewpager);
createViewPager(viewPager);
viewPager2 = (ViewPager) findViewById(R.id.viewpager2);
createViewPager2(viewPager2);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
tabLayout2 = (TabLayout) findViewById(R.id.tabs);
tabLayout2.setupWithViewPager(viewPager2);
createTabIcons();
}
private void createTabIcons() {
LinearLayout tabLinearLayout = (LinearLayout) LayoutInflater.from(this).inflate(R.layout.custom_tab, null);
TextView tabOne = (TextView) tabLinearLayout.findViewById(R.id.tabContent);
tabOne.setText("Paslon 1");
tabOne.setCompoundDrawablesWithIntrinsicBounds(R.drawable.icontoast, 0, 0, 0);
tabLayout2.getTabAt(0).setCustomView(tabOne);
tabLayout.getTabAt(0).setCustomView(tabOne);
LinearLayout tabLinearLayout2 = (LinearLayout) LayoutInflater.from(this).inflate(R.layout.custom_tab, null);
TextView tabTwo = (TextView) tabLinearLayout2.findViewById(R.id.tabContent);
tabTwo.setText("Paslon 2");
tabTwo.setCompoundDrawablesWithIntrinsicBounds(R.drawable.icontoast, 0, 0, 0);
tabLayout2.getTabAt(1).setCustomView(tabTwo);
tabLayout.getTabAt(1).setCustomView(tabTwo);
}
private void createViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFrag(new SatuA(), "Tab 1");
adapter.addFrag(new DuaA(), "Tab 2");
viewPager.setAdapter(adapter);
}
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 addFrag(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
private void createViewPager2(ViewPager viewPager2) {
ViewPagerAdapter2 adapter = new ViewPagerAdapter2(getSupportFragmentManager());
adapter.addFrag(new Satu(), "Tab 1");
adapter.addFrag(new Dua(), "Tab 2");
viewPager2.setAdapter(adapter);
}
class ViewPagerAdapter2 extends FragmentPagerAdapter {
private final List<Fragment> mSilit1 = new ArrayList<>();
private final List<String> mSempak1 = new ArrayList<>();
public ViewPagerAdapter2(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mSilit1.get(position);
}
#Override
public int getCount() {
return mSilit1.size();
}
public void addFrag(Fragment fragment, String title) {
mSilit1.add(fragment);
mSempak1.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mSempak1.get(position);
}
}
}
fragmen1.java
package com.papaozi.ground;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class Satu extends Fragment {
public Satu() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_dua, container, false);
}
}
fragmen2.java
package com.papaozi.ground;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class Dua extends Fragment {
public Dua() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_dua, container, false);
}
}
activity_profil.xml
<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/main_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true">
<android.support.v4.widget.NestedScrollView
android:id="#+id/nestedscrollview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/backgroudscrollgrid_color"
android:fillViewport="true"
app:layout_behavior="#string/appbar_scrolling_view_behavior">
<android.support.v4.view.ViewPager
android:id="#+id/viewpager2"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
</android.support.v4.widget.NestedScrollView>
<android.support.design.widget.AppBarLayout
android:id="#+id/appbar"
android:layout_width="match_parent"
android:layout_height="#dimen/app_bar_height"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
android:fitsSystemWindows="true">
<android.support.design.widget.CollapsingToolbarLayout
android:id="#+id/collapsing_toolbar"
android:layout_width="match_parent"
android:layout_height="206dip"
android:background="#color/background"
app:layout_scrollFlags="scroll|exitUntilCollapsed"
android:fitsSystemWindows="true"
app:contentScrim="#color/putih"
app:expandedTitleMarginStart="48dp"
app:expandedTitleMarginBottom="20dp"
app:expandedTitleMarginEnd="64dp">
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<ImageView
android:id="#+id/backdrop"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="centerCrop"
android:fitsSystemWindows="true"
app:layout_collapseMode="parallax" />
<TextView
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light"
app:layout_collapseMode="pin" />
</android.support.design.widget.CollapsingToolbarLayout>
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabBackground="#android:color/darker_gray"
app:tabIndicatorColor="#f00"
app:tabSelectedTextColor="#f00"
app:tabTextColor="#000" />
</android.support.design.widget.AppBarLayout>
</android.support.design.widget.CoordinatorLayout>
custom_tab.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="vertical"
android:gravity="center">
<TextView
android:id="#+id/tabContent"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:textAlignment="center"
android:textColor="#android:color/white"
android:gravity="center"/>
</LinearLayout>
fragmen1.xml and fragmen2.xml
<RelativeLayout 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="info.androidhive.materialtabs.fragments.OneFragment">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="Satu Fragment"
android:textColor="#color/putih"
android:textSize="40dp"
android:textStyle="bold" />
</RelativeLayout>
thanks for helpme.
There is a simple tutorial for your purpose. You can check this link.
But it replace fragments when normal button clicked. You can just simply move the codes into your tab's click event. Just like that : See the link
If you already added fragment1 and fragment2 into viewpager1 and fragment1A and fragment2A into viewpager2 and if you want to just simply switch the fragments programmatically when you clicked the tabs, then you can use viewpager1.setCurrentItem(1)
viewpager1.setCurrentItem(0) in tabs' click events.

How to display two fragments at the same time using TabLayout?

I use Android Tab Example with two tabs, view pager and fragments (structure on the image):
For get fragments i use the solution from this post.
When my device is rotation i want to display two fragments at the same time.
I the stackoverflow.com/questions/17970021 a similar problem, but I don't know how to apply the solution to my task, because i have TabLayout.
If you know idea, can you help me?
In activity_main.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="16dp"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:paddingTop="16dp"
>
<FrameLayout
android:id="#+id/main_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
</FrameLayout>
</FrameLayout>
In MainActivity.java
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.annotation.NonNull;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
replaceFragment(0);
}
public void replaceFragment(int position) {
Fragment fragment = null;
switch (position) {
case 0:
fragment = new TabOneFragment();
break;
case 1:
fragment = new TabTwoFragment();
break;
default:
break;
}
if (null != fragment) {
FragmentManager fragmentManager = MainActivity.this.getSupportFragmentManager();
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.replace(R.id.main_content, fragment);
transaction.addToBackStack(null);
transaction.commit();
}
}
}
in TabOneFragment.java
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
public class TabOneFragment extends Fragment {
private View inflatedView = null;
public TabOneFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
this.inflatedView = inflater.inflate(R.layout.fragment_tab_one, container, false);
return this.inflatedView;
}
}
in TabTwoFragment.java
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
public class TabTwoFragment extends Fragment {
private View inflatedView = null;
public TabTwoFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
this.inflatedView = inflater.inflate(R.layout.fragment_tab_two, container, false);
return this.inflatedView;
}
}

How to add dynamically several fragments

I create a little app with 3 static fragments and a view pager adapter. But what I want is to create Only one kind of fragment and with a button "add" , add other fragment which will be adapted by the view pager.. here is what i have done
FragmentTab1.java ; FragmentTab2 ; FragmentTab3 have the same code
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class FragmentTab2 extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Get the view from fragmenttab2.xml
View view = inflater.inflate(R.layout.fragmenttab2, container, false);
return view;
}
}
here is my MainActivity.java
import android.app.Fragment;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends FragmentActivity {
//Button adfg = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get the view from activity_main.xml
setContentView(R.layout.activity_main);
// Locate the viewpager in activity_main.xml
ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
// Set the ViewPagerAdapter into ViewPager
viewPager.setAdapter(new ViewPagerAdapter(getSupportFragmentManager()));
}
}
ViewPagerAdapter.java
import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
public class ViewPagerAdapter extends FragmentPagerAdapter {
final int PAGE_COUNT = 3;
// Tab Titles
private String tabtitles[] = new String[] { "Tab1", "Tab2", "Tab3" };
Context context;
public ViewPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public int getCount() {
return PAGE_COUNT;
}
#Override
public Fragment getItem(int position) {
switch (position) {
// Open FragmentTab1.java
case 0:
FragmentTab1 fragmenttab1 = new FragmentTab1();
return fragmenttab1;
// Open FragmentTab2.java
case 1:
FragmentTab2 fragmenttab2 = new FragmentTab2();
return fragmenttab2;
// Open FragmentTab3.java
case 2:
FragmentTab3 fragmenttab3 = new FragmentTab3();
return fragmenttab3;
}
return null;
}
#Override
public CharSequence getPageTitle(int position) {
return tabtitles[position];
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.view.ViewPager
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<android.support.v4.view.PagerTabStrip
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="top"
android:paddingBottom="10dp"
android:paddingTop="10dp"
android:textColor="#000000" />
</android.support.v4.view.ViewPager>
fragmenttab1.xml ; fragmenttab2.xml ; fragmenttab3.xml has the same code
<?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="vertical" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Fragment 1" />
<Button
android:id="#+id/bajou"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Ajouter fragment" />
</LinearLayout>
You need to create a method to add the fragment on the subclass of FragmentPagerAdapter, more or less like this :
//use those lists
private List<Fragment> listFragment = new ArrayList<Fragment>();
private List<String> listFragmentTitle = new ArrayList<String>();
private List<Integer> listFragmentIcon = new ArrayList<Integer>();
public void addTab(Fragment fragment,String title, int icon) {
listFragment.add(fragment);
listFragmentTitle.add(title);
listFragmentIcon.add(icon);
}
#Override
public Fragment getItem(int position) {
// TODO Auto-generated method stub
return listFragment.get(position);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return listFragment.size();
}
Then you just need to use it on the subclass of Activity, example :
//create a private method to set a new - dynamic fragment in the ACTIVITY
private Fragment setFragment(int pos)
{
MyFragment myFragment = new MyFragment();
Bundle data = new Bundle();
data.putString("test", "test");
myFragment.setArguments(data);
return myFragment;
}
Finally, add the fragment (for example, inside an onClickListener) :
//INSIDE an onClickListener
pagerAdapter.addTab(setFragment(position), getItem(position).getName(), R.drawable.ic_launcher);
this is my MainActivity.java class #BlazeTama
package com.light.frag;
import com.light.frag.R;
import com.light.frag.ViewPagerAdapter;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends FragmentActivity implements OnClickListener{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Locate the viewpager in activity_main.xml
ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
// Set the ViewPagerAdapter into ViewPager
viewPager.setAdapter(new ViewPagerAdapter(getSupportFragmentManager()));
Button ajou = (Button) findViewById(R.id.bajou);
ajou.setOnClickListener(this);
}
private Fragment setFragment(int pos)
{
MyFragment myFragment = new MyFragment();
Bundle data = new Bundle();
data.putString("test", "test");
myFragment.setArguments(data);
return myFragment;
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.bajou:
ViewPagerAdapter.addTab(setFragment(position), getItem(position).getName(), R.drawable.ic_launcher);
break;
}
}
}

Categories

Resources