Creating Tabs inside Fragment - android

I'm getting a fragment from mother activity. Now i want to create tabs in this fragment. But tabHost.setup() method showing error. I don't get it so need a clue about error.
//
FragmentOne.java
package com.example.sharelocationui;
import android.app.Fragment;
import android.os.Bundle;
import android.support.v4.app.FragmentTabHost;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView.FindListener;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.TabHost;
public class FragmentOne extends Fragment {
private FragmentTabHost tabHost;
public FragmentOne() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
View v = inflater.inflate(R.layout.fragment_layout_one, container,
false);
tabHost = (FragmentTabHost) v.findViewById(R.id.testtabhost1);
tabHost = new FragmentTabHost(getActivity());
tabHost.setup(getActivity(),getChildFragmentManager(),R.id.testtabhost1);
tabHost.addTab(tabHost.newTabSpec("tab_test1").setIndicator("TAB1"));
tabHost.addTab(tabHost.newTabSpec("tab_test2").setIndicator("TAB2"));
tabHost.addTab(tabHost.newTabSpec("tab_test3").setIndicator("TAB3"));
tabHost.setCurrentTab(0);
return v;
}
#Override
public void onDestroyView() {
super.onDestroyView();
tabHost = null;
}
}
//fragment_layout_one
<android.support.v4.app.FragmentTabHost
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/testtabhost1"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TabWidget
android:id="#android:id/tabs"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<FrameLayout
android:id="#android:id/tabcontent"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
</FrameLayout>
</LinearLayout>
</android.support.v4.app.FragmentTabHost>
Error showing
'The method setup(Context, FragmentManager, int) in the type FragmentTabHost is not applicable for the arguments (Activity, FragmentManager, int)'

This is perfect for your Question
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.comfortstay.R;
public class TabFragment extends Fragment {
public static TabLayout tabLayout;
public static ViewPager viewPager;
public static int int_items = 2;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
/**
*Inflate tab_layout and setup Views.
*/
View v = inflater.inflate(R.layout.fragment_tab_layout, container, false);
tabLayout = (TabLayout) v.findViewById(R.id.tabs);
viewPager = (ViewPager) v.findViewById(R.id.viewpager);
/**
*Set an Apater for the View Pager
*/
viewPager.setAdapter(new MyAdapter(getChildFragmentManager()));
/**
* Now , this is a workaround ,
* The setupWithViewPager dose't works without the runnable .
* Maybe a Support Library Bug .
*/
tabLayout.post(new Runnable() {
#Override
public void run() {
tabLayout.setupWithViewPager(viewPager);
}
});
return v;
}
class MyAdapter extends FragmentPagerAdapter {
public MyAdapter(FragmentManager fm) {
super(fm);
}
/**
* Return fragment with respect to Position .
*/
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new DashboardFragment();
case 1:
return new DashboardFragment();
}
return null;
}
#Override
public int getCount() {
return int_items;
}
/**
* This method returns the title of the tab according to the position.
*/
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
String recent_news = "My Order";
return recent_news;
case 1:
String category = "Popular Items";
return category;
}
return null;
}
}
}
and layout is:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:ads="http://schemas.android.com/apk/res-auto"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/tab_background_color"
android:elevation="4dp"
app:tabGravity="fill"
app:tabIndicatorColor="#color/tabIndicatorColor"
app:tabIndicatorHeight="5dp"
app:tabMode="fixed"
app:tabSelectedTextColor="#color/tabSelectedTextColor"
app:tabTextColor="#color/tabTextColor"></android.support.design.widget.TabLayout>
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/tabs">
</android.support.v4.view.ViewPager>
</RelativeLayout>

Your problem is you are importing
android.app.Fragment
not
android.support.v4.app.Fragment

In th onCreateView method just change and remove the
View v = inflater.inflate(R.layout.fragment_layout_one, container,
false);
return v;
to
return tabhost
UPDATE:
You have not initialized the FragmentTabHost.
mTabHost = new FragmentTabHost(getActivity());
for reference check the official example

But how to call fragment when importing android.support.v4.app.Fragment.
It is part of MainActivity.java :
Button b = (Button) findViewById(R.id.buttonGoTab);
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Fragment fragment = null;
FragmentManager fragmentManager =getFragmentManager();
FragmentTransaction fragmentTransaction =fragmentManager.beginTransaction();
fragment= new HelloTab(); //Here is error
fragmentTransaction.replace(android.R.id.content, fragment).commit();
}
});
It is a part of HelloTab.java :
import android.app.LocalActivityManager;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTabHost;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TabHost;
import android.widget.TabHost.TabSpec;
public class HelloTab extends Fragment {
private FragmentTabHost mTabHost;
public Context context;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.hellotablay,container, false);
context= getActivity().getApplicationContext();
mTabHost = (FragmentTabHost)rootView.findViewById(android.R.id.tabhost);
// #SuppressWarnings("deprecation")
LocalActivityManager mLocalActivityManager = new LocalActivityManager(this.getActivity(), false);
mLocalActivityManager.dispatchCreate(savedInstanceState);
mTabHost.setup(getActivity(),getChildFragmentManager(),android.R.id.tabcontent);
mTabHost.addTab(mTabHost.newTabSpec("fragmentb").setIndicator("Fragment B"),
Tab11.class, null);
mTabHost.addTab(mTabHost.newTabSpec("fragmentc").setIndicator("Fragment C"),
Tab11.class, null);
mTabHost.addTab(mTabHost.newTabSpec("fragmentd").setIndicator("Fragment D"),
Tab11.class, null);
enter code here
return rootView;
}
}

Related

Setting viewpager with same fragment is not working as expected

I am trying to set up a view pager containing three tab with same fragment.
But its not working as expected. I wanted to show individual tab with different background color and textview showing its ID based on the ID that I am providing using bundle and argument.
I am providing the code and pictures to understand better.
MainActivity.xml
<?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="com.bdtask.myapplication.MainActivity">
<LinearLayout
android:id="#+id/tabviewholder"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<android.support.design.widget.TabLayout
android:id="#+id/viewpagertab"
android:layout_width="match_parent"
android:layout_height="48dp"
android:background="#android:color/white"
/>
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#id/viewpagertab" />
</LinearLayout>
BlankFragment.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:id="#+id/container"
android:layout_height="match_parent"
tools:context="com.bdtask.myapplication.BlankFragment">
<!-- TODO: Update blank fragment layout -->
<TextView
android:gravity="center"
android:textSize="40sp"
android:id="#+id/textview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="#string/hello_blank_fragment" />
MainActivity.java
package com.bdtask.myapplication;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TabHost;
import android.widget.TableLayout;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ViewPagerAdapter viewPagerAdapter = new
ViewPagerAdapter(getSupportFragmentManager());
ViewPager viewPager = findViewById(R.id.viewpager);
TabLayout tabLayout = findViewById(R.id.viewpagertab);
for(int i = 0 ; i<3 ; i++){
Bundle bundle = new Bundle();
bundle.putString("id",String .valueOf(i));
BlankFragment blankFragment = new BlankFragment();
blankFragment.setArguments(bundle);
viewPagerAdapter.getFragments(blankFragment, "tab "+i);
}
viewPager.setAdapter(viewPagerAdapter);
tabLayout.setupWithViewPager(viewPager);
}
}
BlankFragment.java
package com.bdtask.myapplication;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.TextView;
/**
* A simple {#link Fragment} subclass.
*/
public class BlankFragment extends Fragment {
TextView textView;
FrameLayout frameLayout;
String id;
public BlankFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
//
id = getArguments().getString("id");
return inflater.inflate(R.layout.fragment_blank, container, false);
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
frameLayout = getActivity().findViewById(R.id.container);
textView = getActivity().findViewById(R.id.textview);
setbackgroundandtext();
}
public void setbackgroundandtext() {
if(id.equals("0")){
frameLayout.setBackgroundColor(Color.parseColor("#ab44ab"));
textView.setText(id);
}
if(id.equals("1")){
frameLayout.setBackgroundColor(Color.parseColor("#ea32ea"));
textView.setText(id);
}
if(id.equals("2")){
frameLayout.setBackgroundColor(Color.parseColor("#67ae34"));
textView.setText(id);
}
}
}
ViewPagerAdapter.java
package com.bdtask.myapplication;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import java.util.ArrayList;
/**
* Created by Jibunnisa on 5/20/2017.
*/
public class ViewPagerAdapter extends FragmentStatePagerAdapter {
ArrayList<Fragment> fragments = new ArrayList<Fragment>();
ArrayList<String> titles = new ArrayList<String>();
public ViewPagerAdapter(FragmentManager fm) {
super(fm);
}
public void getFragments(Fragment fragment, String title) {
this.fragments.add(fragment);
this.titles.add(title);
}
#Override
public Fragment getItem(int position) {
return fragments.get(position);
}
#Override
public int getCount() {
return fragments.size();
}
#Override
public CharSequence getPageTitle(int position) {
return titles.get(position);
}
}
output:
You're setting id here to be 0,1,2:
for(int i = 0 ; i<3 ; i++) {
Bundle bundle = new Bundle();
bundle.putString("id",String .valueOf(i));
BlankFragment blankFragment = new BlankFragment();
blankFragment.setArguments(bundle);
viewPagerAdapter.getFragments(blankFragment, "tab "+i);
}
But here you're checking if it is 1,2,3:
public void setbackgroundandtext() {
if(id.equals("1")){
frameLayout.setBackgroundColor(Color.parseColor("#ab44ab"));
textView.setText(id);
}
if(id.equals("2")){
frameLayout.setBackgroundColor(Color.parseColor("#ea32ea"));
textView.setText(id);
}
if(id.equals("3")){
frameLayout.setBackgroundColor(Color.parseColor("#67ae34"));
textView.setText(id);
}
}
So check if if it is 0,1,2 instead.
EDIT:
You need to find the views inside the fragment, not through the activity, move the findViewById code from onActivityCreated to onCreateView.
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
//
id = getArguments().getString("id");
View v =inflater.inflate(R.layout.fragment_blank, container, false);
frameLayout = v.findViewById(R.id.container);
textView = v.findViewById(R.id.textview);
return v;
}

SlidingTabLayout not displaying on output

I am using Android Studio 1.2.2 and trying to implement tabs for one of my activities. I have added all the code but don't seem to be getting any output on the phone. I do not need ActionBar, just SlidingTabLayout, but it doesn't show anything other than a blank screen when I run.
Iphone6Activity.java
package com.hashmi.omar.vodafonestore;
import android.app.Activity;
import android.graphics.Typeface;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.ActionBarActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class Iphone6Activity extends Activity {
private ViewPager mPager;
private SlidingTabLayout mTabs;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_iphone6);
//Sets font for text
//Typeface vodaLt = Typeface.createFromAsset(getAssets(), "VODAFONELT.TTF");
//TextView vodaHeading = (TextView) findViewById(R.id.textView10);
// vodaHeading.setTypeface(vodaLt);
mPager = (ViewPager) findViewById(R.id.ip6pager);
//mPager.setAdapter(new MyPagerAdapter(getSupportFragmentManager()));
mTabs = (SlidingTabLayout) findViewById(R.id.ip6tabs);
mTabs.setViewPager(mPager);
}
class MyPagerAdapter extends FragmentPagerAdapter{
String[] tabs;
public MyPagerAdapter(FragmentManager fm) {
super(fm);
tabs=getResources().getStringArray(R.array.tabs);
}
#Override
public Fragment getItem(int position) {
MyFragment myFragment=MyFragment.getInstance(position);
return myFragment;
}
#Override
public CharSequence getPageTitle(int position){
return tabs[position];
}
#Override
public int getCount() {
return 3;
}
}
public static class MyFragment extends Fragment{
private TextView textView;
public static MyFragment getInstance(int position){
MyFragment myFragment = new MyFragment();
Bundle args = new Bundle();
args.putInt("position", position);
myFragment.setArguments(args);
return myFragment;
}
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View layout=inflater.inflate(R.layout.fragment_my, container, false);
textView= (TextView) layout.findViewById(R.id.position);
Bundle bundle=getArguments();
if(bundle!=null)
{
textView.setText("The page selected is "+bundle.getInt("position"));
}
return layout;
}
}
}
activity_iphone6.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/iphone6"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.hashmi.omar.vodafonestore.Iphone6Activity"
android:background="#ffffffff">
<com.hashmi.omar.vodafonestore.SlidingTabLayout
android:id="#+id/ip6tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
<android.support.v4.view.ViewPager
android:id="#+id/ip6pager"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
/>
</LinearLayout>
fragment_my.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
</LinearLayout>
You are not using MyPagerAdapter class. Uncomment out this line to set an adapter for your ViewPager:
//mPager.setAdapter(new MyPagerAdapter(getSupportFragmentManager()));

Can't change tag of fragment Page

can somebody help me??
I use a view pager and one fragment in it. in my adapter i create a list of fragment and attach them to view pager. I want to add one page at the start of view pager. list.add(position,pageObj); but I face this error: java.lang.IllegalStateException: Can't change tag of fragment Page
Try this
Create a tab_one.xml file
<?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" >
<TextView
android:id="#+id/register_btn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:gravity="center"
android:text="#string/tab_1" />
</RelativeLayout>
create more fragments like this.
Create a fragment class file
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class TabOne extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.tab_one, null);
return rootView;
}
}
create more fragment class files.
Create TabFragmentPage adapter class
package com.example.tabfragment;
import java.util.List;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
public class TabFragmentPageAdapter extends FragmentPagerAdapter {
private Bundle args;
private List<Fragment> fragments;
public TabFragmentPageAdapter(FragmentManager fm, List<Fragment> fragments,
Bundle args) {
super(fm);
this.fragments = fragments;
this.args = args;
}
#Override
public Fragment getItem(int position) {
Fragment fragment = fragments.get(position);
fragment.setArguments(args);
return fragment;
}
#Override
public int getCount() {
return fragments.size();
}
#Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
}
Create tabhost xml file
<?xml version="1.0" encoding="utf-8"?>
<TabHost xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:ts="http://schemas.android.com/apk/res-auto"
android:id="#android:id/tabhost"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TabWidget
android:id="#android:id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fadingEdge="none"
android:background="#394c58"
android:tabStripEnabled="false" />
<FrameLayout
android:id="#android:id/tabcontent"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</FrameLayout>
</LinearLayout>
</TabHost>
Create TabFragment Class
package com.example.tabfragment;
import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TabHost;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.TabHost.TabContentFactory;
import android.widget.TabHost.TabSpec;
import android.widget.TextView;
public class TabFragments extends Fragment implements OnPageChangeListener,
OnTabChangeListener {
private TabHost tabHost;
private int currentTab = 0;
private ViewPager viewPager;
private TabFragmentPageAdapter pageAdapter;
private List<Fragment> fragments;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_home, null);
tabHost = (TabHost) rootView.findViewById(android.R.id.tabhost);
viewPager = (ViewPager) rootView.findViewById(R.id.viewpager);
viewPager.setOnPageChangeListener(this);
fragments = new ArrayList<Fragment>();
fragments.add(new TabOne());
fragments.add(new TabTwo());
fragments.add(new TabThree());
fragments.add(new TabFour());
return rootView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setRetainInstance(true);
pageAdapter = new TabFragmentPageAdapter(getChildFragmentManager(),
fragments, getArguments());
pageAdapter.notifyDataSetChanged();
viewPager.setAdapter(pageAdapter);
setupTabs();
}
private void setupTabs() {
tabHost.setup();
tabHost.addTab(newTab(R.string.tab_1));
tabHost.addTab(newTab(R.string.tab_2));
tabHost.addTab(newTab(R.string.tab_3));
tabHost.addTab(newTab(R.string.tab_4));
for (int i = 0; i < tabHost.getTabWidget().getChildCount(); i++) {
tabHost.getTabWidget().getChildAt(i)
.setBackgroundColor(Color.parseColor("#304c58"));
// tabHost.setBackgroundResource(R.drawable.tab_selector);
final View view = tabHost.getTabWidget().getChildTabViewAt(i);
final View textView = view.findViewById(android.R.id.title);
((TextView) textView).setTextColor(Color.parseColor("#e2ebf0"));
((TextView) textView).setSingleLine(true);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
tabHost.getTabWidget().getChildAt(i)
.findViewById(android.R.id.icon);
tabHost.getTabWidget().getChildAt(i).getLayoutParams().height = 75;
} else {
if (view != null) {
// reduce height of the tab
view.getLayoutParams().height *= 0.77;
if (textView instanceof TextView) {
((TextView) textView).setGravity(Gravity.CENTER);
textView.getLayoutParams().height = ViewGroup.LayoutParams.MATCH_PARENT;
textView.getLayoutParams().width = ViewGroup.LayoutParams.WRAP_CONTENT;
}
}
}
}
tabHost.setOnTabChangedListener(TabFragments.this);
tabHost.setCurrentTab(currentTab);
}
private TabSpec newTab(int titleId) {
TabSpec tabSpec = tabHost.newTabSpec(getString(titleId));
tabSpec.setIndicator(getString(titleId));
tabSpec.setContent(new TabFactory(getActivity()));
return tabSpec;
}
#Override
public void onPageScrollStateChanged(int position) {
}
#Override
public void onPageScrolled(int position, float arg1, int arg2) {
}
#Override
public void onPageSelected(int position) {
tabHost.setCurrentTab(position);
}
#Override
public void onTabChanged(String tabId) {
currentTab = tabHost.getCurrentTab();
viewPager.setCurrentItem(currentTab);
updateTab();
}
#SuppressWarnings("unused")
private void updateTab() {
switch (currentTab) {
case 0:
TabOne login = (TabOne) fragments.get(currentTab);
break;
case 1:
TabTwo register = (TabTwo) fragments
.get(currentTab);
break;
case 2:
TabThree tabThree = (TabThree) fragments.get(currentTab);
break;
case 3:
TabFour tabFour = (TabFour) fragments
.get(currentTab);
break;
}
}
class TabFactory implements TabContentFactory {
private final Context context;
public TabFactory(Context context) {
this.context = context;
}
#Override
public View createTabContent(String tag) {
View v = new View(context);
v.setMinimumHeight(0);
v.setMinimumWidth(0);
return v;
}
}
}
Create MainActivity.class
package com.example.tabfragment;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
public class MainActivity extends ActionBarActivity {
Fragment fragment = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fragment = new TabFragments();
Log.i("fragment", "" + fragment.getId());
if (fragment != null) {
FragmentManager fm = getSupportFragmentManager();
fm.beginTransaction().replace(R.id.frame_container, fragment)
.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE)
.commit();
}
}
}
Create activity_main.xml file
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<FrameLayout
android:id="#+id/frame_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</android.support.v4.widget.DrawerLayout>

How to move next page in android fragment tab using view pager?

I have two tabs.Login and Register fragment. I have register button click in login tab and when I click, it should move to register fragment
I used this method in LoginActivity
public void setCurrentItem(int item, boolean smoothScroll) {
mPager.setCurrentItem(item, smoothScroll);
}
and I get that method in Login fragment but it displays error.
My code is as follows:
public class LoginActivity extends SherlockFragmentActivity {
private ViewPager mPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get the view from activity_main.xml
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.loginpager);
PagerSlidingTabStrip tabs = (PagerSlidingTabStrip) findViewById(R.id.tabs);
tabs.setIndicatorColor(Color.BLUE);
tabs.setIndicatorHeight(5);
mPager = (ViewPager) findViewById(R.id.pager);
ViewPagerAdapter adapter = new ViewPagerAdapter(fm);
mPager.setAdapter(adapter);
tabs.setViewPager(mPager);
}
public void setCurrentItem(int item, boolean smoothScroll) {
mPager.setCurrentItem(item, smoothScroll);
}
public class ViewPagerAdapter extends FragmentPagerAdapter {
public ViewPagerAdapter(android.support.v4.app.FragmentManager fm) {
super(fm);
}
private final String[] TITLES = { "LOG IN", "REGISTER" };
#Override
public CharSequence getPageTitle(int position) {
return TITLES[position];
}
#Override
public SherlockFragment getItem(int arg0) {
switch (arg0) {
// Open LoginFragment
case 0:
LoginFragment loginfragment = new LoginFragment();
return loginfragment;
// Open RegisterFragment
case 1:
RegisterFragment registerfragment= new RegisterFragment();
return registerfragment;
}
return null;
}
#Override
public int getCount() {
return TITLES.length;
}
}
}
LoginFragment:
public class LoginFragment extends SherlockFragment implements OnClickListener {
private LoginActivity loginActivity;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Get the view from fragmenttab3.xml
View view = inflater.inflate(R.layout.login, container, false);
SpannableString spannableString = new SpannableString(text);
spannableString.setSpan(new ForegroundColorSpan(Color.BLACK), 24, 32, 0);
ClickableSpan clickableSpan = new SpaceAdjust(text) {
#Override
public void onClick(View textView) {
loginActivity = new LoginActivity();
loginActivity.setCurrentItem(2, true); // here i am getting error. How to swipe to RegisterFragment
}
};
spannableString.setSpan(clickableSpan, 24, 32, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
dontHaveAccountRegister.setText(spannableString);
dontHaveAccountRegister.setMovementMethod(LinkMovementMethod.getInstance());
return view;
}
}
Error :
12-12 00:41:53.906: E/AndroidRuntime(1580): FATAL EXCEPTION: main
12-12 00:41:53.906: E/AndroidRuntime(1580): Process: com.a.b, PID: 1580
12-12 00:41:53.906: E/AndroidRuntime(1580): java.lang.NullPointerException
12-12 00:41:53.906: E/AndroidRuntime(1580): at com.a.b.LoginActivity.setCurrentItem(LoginActivity.java:148)
12-12 00:41:53.906: E/AndroidRuntime(1580): at com.a.b.views.LoginFragment$5.onClick(LoginFragment.java:250)
12-12 00:41:53.906: E/AndroidRuntime(1580): at android.text.method.LinkMovementMethod.onTouchEvent(LinkMovementMethod.java:217)
12-12 00:41:53.906: E/AndroidRuntime(1580): at android.widget.TextView.onTouchEvent(TextView.java:7724)
12-12 00:41:53.906: E/AndroidRuntime(1580): at android.view.View.dispatchTouchEvent(View.java:7690)
12-12 00:41:53.906: E/AndroidRuntime(1580): at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2216)
12-12 00:41:53.906: E/AndroidRuntime(1580): at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:1959)
12-12 00:41:53.906: E/AndroidRuntime(1580): at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2216)
Try this it's working fine
Create a layout file login_layout.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" >
<Button
android:id="#+id/register_btn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:gravity="center"
android:text="#string/register_here" />
</RelativeLayout>
Create a layout file register_layout.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" >
<TextView
android:id="#+id/textview"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:gravity="center"
android:text="#string/register_layout" />
</RelativeLayout>
create a layout for tabhost fragment_home.xml
<?xml version="1.0" encoding="utf-8"?>
<TabHost xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:ts="http://schemas.android.com/apk/res-auto"
android:id="#android:id/tabhost"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TabWidget
android:id="#android:id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fadingEdge="none"
android:background="#394c58"
android:tabStripEnabled="false" />
<FrameLayout
android:id="#android:id/tabcontent"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</FrameLayout>
</LinearLayout>
</TabHost>
change your main activity file
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<FrameLayout
android:id="#+id/frame_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</android.support.v4.widget.DrawerLayout>
create a class file LoginFragment.java
package com.example.tabfragment;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
public class LoginFragment extends Fragment {
ViewPager viewPager;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.login_layout, null);
Button registerButton = (Button) rootView
.findViewById(R.id.register_btn);
registerButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
viewPager = (ViewPager) getActivity().findViewById(
R.id.viewpager);
viewPager.setCurrentItem(1);
}
});
return rootView;
}
}
create a class file RegisterFragment.java
package com.example.tabfragment;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class RegisterFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.register_layout, null);
return rootView;
}
}
create a class file TabFragments.java
package com.example.tabfragment;
import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TabHost;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.TabHost.TabContentFactory;
import android.widget.TabHost.TabSpec;
import android.widget.TextView;
public class TabFragments extends Fragment implements OnPageChangeListener,
OnTabChangeListener {
public static final int TAB_LOGIN = 0;
public static final int TAB_REG = 1;
private TabHost tabHost;
private int currentTab = TAB_LOGIN;
private ViewPager viewPager;
private TabFragmentPageAdapter pageAdapter;
private List<Fragment> fragments;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_home, null);
tabHost = (TabHost) rootView.findViewById(android.R.id.tabhost);
viewPager = (ViewPager) rootView.findViewById(R.id.viewpager);
viewPager.setOnPageChangeListener(this);
fragments = new ArrayList<Fragment>();
fragments.add(new LoginFragment());
fragments.add(new RegisterFragment());
return rootView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setRetainInstance(true);
pageAdapter = new TabFragmentPageAdapter(getChildFragmentManager(),
fragments, getArguments());
pageAdapter.notifyDataSetChanged();
viewPager.setAdapter(pageAdapter);
setupTabs();
}
private void setupTabs() {
tabHost.setup();
tabHost.addTab(newTab(R.string.login));
tabHost.addTab(newTab(R.string.register));
for (int i = 0; i < tabHost.getTabWidget().getChildCount(); i++) {
tabHost.getTabWidget().getChildAt(i)
.setBackgroundColor(Color.parseColor("#304c58"));
// tabHost.setBackgroundResource(R.drawable.tab_selector);
final View view = tabHost.getTabWidget().getChildTabViewAt(i);
final View textView = view.findViewById(android.R.id.title);
((TextView) textView).setTextColor(Color.parseColor("#e2ebf0"));
((TextView) textView).setSingleLine(true);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
tabHost.getTabWidget().getChildAt(i)
.findViewById(android.R.id.icon);
tabHost.getTabWidget().getChildAt(i).getLayoutParams().height = 75;
} else {
if (view != null) {
// reduce height of the tab
view.getLayoutParams().height *= 0.77;
if (textView instanceof TextView) {
((TextView) textView).setGravity(Gravity.CENTER);
textView.getLayoutParams().height = ViewGroup.LayoutParams.MATCH_PARENT;
textView.getLayoutParams().width = ViewGroup.LayoutParams.WRAP_CONTENT;
}
}
}
}
tabHost.setOnTabChangedListener(TabFragments.this);
tabHost.setCurrentTab(currentTab);
}
private TabSpec newTab(int titleId) {
TabSpec tabSpec = tabHost.newTabSpec(getString(titleId));
tabSpec.setIndicator(getString(titleId));
tabSpec.setContent(new TabFactory(getActivity()));
return tabSpec;
}
#Override
public void onPageScrollStateChanged(int position) {
}
#Override
public void onPageScrolled(int position, float arg1, int arg2) {
}
#Override
public void onPageSelected(int position) {
tabHost.setCurrentTab(position);
}
#Override
public void onTabChanged(String tabId) {
currentTab = tabHost.getCurrentTab();
viewPager.setCurrentItem(currentTab);
updateTab();
}
#SuppressWarnings("unused")
private void updateTab() {
switch (currentTab) {
case TAB_LOGIN:
LoginFragment login = (LoginFragment) fragments.get(currentTab);
break;
case TAB_REG:
RegisterFragment register = (RegisterFragment) fragments
.get(currentTab);
break;
}
}
class TabFactory implements TabContentFactory {
private final Context context;
public TabFactory(Context context) {
this.context = context;
}
#Override
public View createTabContent(String tag) {
View v = new View(context);
v.setMinimumHeight(0);
v.setMinimumWidth(0);
return v;
}
}
}
create a class file TabFragmentPageAdapter .java
import java.util.List;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
public class TabFragmentPageAdapter extends FragmentPagerAdapter {
private Bundle args;
private List<Fragment> fragments;
public TabFragmentPageAdapter(FragmentManager fm, List<Fragment> fragments,
Bundle args) {
super(fm);
this.fragments = fragments;
this.args = args;
}
#Override
public Fragment getItem(int position) {
Fragment fragment = fragments.get(position);
fragment.setArguments(args);
return fragment;
}
#Override
public int getCount() {
return fragments.size();
}
#Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
}
Finaly change your mainactivity.java class
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.ActionBarActivity;
public class MainActivity extends ActionBarActivity {
Fragment fragment = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fragment = new TabFragments();
if (fragment != null) {
FragmentManager fm = getSupportFragmentManager();
fm.beginTransaction().replace(R.id.frame_container, fragment)
.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE)
.commit();
}
}
}
You should not Create Activity's instance to access its method. It is Fragment's Parent Activity.
So you can directly access it as :
((LoginActivity)getActivity()).setCurrentItem(2, true);
Hope it helps ツ

Android fragment activity change content after change page

I have fragment activity that have view pager, I want every changing page the content is change programmatically. `
package com.idroid.splashscreen;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.widget.TextView;
import android.widget.Toast;
public class ScreenSlidePagerActivity extends FragmentActivity {
private static final int NUM_PAGES = 5;
private ViewPager mPager;
private PagerAdapter mPagerAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_screen_slide);
mPager = (ViewPager) findViewById(R.id.pager);
mPagerAdapter = new ScreenSlidePagerAdapter(getSupportFragmentManager());
mPager.setAdapter(mPagerAdapter);
OnPageChangeListener pageChangeListener=null;
pageChangeListener = new OnPageChangeListener() {
#Override
public void onPageScrollStateChanged(int arg0) { }
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) { }
#Override
public void onPageSelected(int position) {
Toast.makeText(getApplicationContext()
.getApplicationContext(),
"page "+position,
Toast.LENGTH_LONG).show();
TextView txt=(TextView) findViewById(R.id.txtcoba);
txt.setText("page "+position);
}
};
mPager.setOnPageChangeListener(pageChangeListener);
}
#Override
public void onBackPressed() {
if (mPager.getCurrentItem() == 0) {
super.onBackPressed();
} else {
mPager.setCurrentItem(mPager.getCurrentItem() - 1);
}
}
private class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter {
public ScreenSlidePagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return new ScreenSlidePageFragment();
}
#Override
public int getCount() {
return NUM_PAGES;
}
}
}
`
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/content"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="#+id/txtcoba"
style="?android:textAppearanceMedium"
android:padding="16dp"
android:lineSpacingMultiplier="1.2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="coba" />
</ScrollView>
I change it on page selected method and change the content of text view. for the toast it's work but for the text doesn't change. but on page 4 when I back to page 3, the page 3 show the page. but the other page not.
what should I do ? thanks before. this is the ScreenSlidePageFragment class
package com.idroid.splashscreen;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class ScreenSlidePageFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
ViewGroup rootView = (ViewGroup) inflater.inflate(
R.layout.fragment_screen_slide_page, container, false);
return rootView;
}
}
this is fragment_screen_slide_page.xml
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/content"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="#+id/txtcoba"
style="?android:textAppearanceMedium"
android:padding="16dp"
android:lineSpacingMultiplier="1.2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="coba" />
</ScrollView>
this is activity_screen_slide.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" />
Issue is your trying to set the TextView of Fragment layout.
As per your code your TextView is in the ScreenSlidePageFragment layout.
Remove the 'TextView' setText in onPageeSelcted
Change your ScreenSlidePageFragment like this
private class ScreenSlidePageFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View row = inflater.inflate(R.layout.activity_screen_slide, container, false);
TextView txt=(TextView) row.findViewById(R.id.txtcoba);
txt.setText("page using fragment");
return row;
}
}

Categories

Resources