how to keep tabs visible on every activity - android

I am very new to android programming and I am trying to implement tabs using fragments.
I am using this Tutorial. Everything goes fine but my problem is that I want to open a new activity and on this new activity I want to keep tab bar. I want tab bar visible on every new activity which opens inside tab. I have following code..
public class Tab1Fragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if (container == null) {
return null;
}
LinearLayout theLayout = (LinearLayout) inflater.inflate(
R.layout.tab_frag1_layout, container, false);
// Register for the Button.OnClick event
Button b = (Button) theLayout.findViewById(R.id.btn_startActivity);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(Tab1Fragment.this.getActivity(),
"open new activity with tab bar", Toast.LENGTH_LONG).show();
//Here I want to start new activity with tab bar
}
});
return theLayout;
// return (LinearLayout)inflater.inflate(R.layout.tab_frag1_layout,
// container, false);
}
}

Here is Main Activity.
package com.example.tabs;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TabHost;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.TextView;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.sample.fragments.R;
public class FragmentTabs extends SherlockFragmentActivity implements FragmentChangeListener
{
private TabHost mTabHost;
private int mContainerId;
private FragmentTransaction fragmentTransaction;
private FragmentManager fragmentManager;
private View tabIndicator1;
private View tabIndicator2;
private View tabIndicator3;
#Override
protected void onCreate(final Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_tabs);
mTabHost = (TabHost)findViewById(android.R.id.tabhost);
mTabHost.setup();
mContainerId=R.id.realtabcontent;
fragmentManager = getSupportFragmentManager();
tabIndicator1 = LayoutInflater.from(this).inflate(R.layout.tab, mTabHost.getTabWidget(), false);
tabIndicator2 = LayoutInflater.from(this).inflate(R.layout.tab, mTabHost.getTabWidget(), false);
tabIndicator3 = LayoutInflater.from(this).inflate(R.layout.tab, mTabHost.getTabWidget(), false);
TextView tv1=(TextView)tabIndicator1.findViewById(R.id.txt);
TextView tv2=(TextView)tabIndicator2.findViewById(R.id.txt);
TextView tv3=(TextView)tabIndicator3.findViewById(R.id.txt);
tv1.setText("Tab1");
tv2.setText("Tab2");
tv3.setText("Tab3");
mTabHost.addTab(mTabHost.newTabSpec("1")
.setContent(new DummyTabFactory(this))
.setIndicator(tabIndicator1)
);
mTabHost.addTab(mTabHost.newTabSpec("2")
.setContent(new DummyTabFactory(this))
.setIndicator(tabIndicator2)
);
mTabHost.addTab(mTabHost.newTabSpec("3")
.setContent(new DummyTabFactory(this))
.setIndicator(tabIndicator3)
);
mTabHost.setOnTabChangedListener(new OnTabChangeListener()
{
#Override
public void onTabChanged(String selectedTabID)
{
int tabIndex=Integer.valueOf(selectedTabID);
switch(tabIndex)
{
case 1:
selectedTabID= tabIndicator1.getTag()==null?"Fragment1":tabIndicator1.getTag().toString();
break;
case 2:
selectedTabID= tabIndicator2.getTag()==null?"Fragment2":tabIndicator2.getTag().toString();
break;
case 3:
selectedTabID= tabIndicator3.getTag()==null?"Fragment3":tabIndicator3.getTag().toString();
break;
};
Fragment fragment=fragmentManager.findFragmentByTag(selectedTabID);
if(fragment==null)
{
fragment=getFragment(selectedTabID);
}
replaceFragment(fragment,selectedTabID);
}
});
renderDefaultTab();
}
public void clickMe(final View view)
{
Fragment fragment=new AnotherFragment();
replaceFragment(fragment,"AnotherFragment");
}
#Override
public void replaceFragment(final Fragment fragment, final String tag)
{
fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(mContainerId, fragment,tag);
fragmentTransaction.addToBackStack(tag);
fragmentTransaction.commit();
}
public void renderDefaultTab()
{
Fragment fragment=getFragment("Fragment1");
replaceFragment(fragment,"Fragment1");
}
public Fragment getFragment(final String tag)
{
Fragment fragment=null;
if(tag.equalsIgnoreCase("Fragment1"))
fragment=new Fragment1();
else if(tag.equalsIgnoreCase("Fragment2"))
fragment=new Fragment2();
else if(tag.equalsIgnoreCase("Fragment3"))
fragment=new Fragment3();
return fragment;
}
#Override
public void addToTab1Navigation(final String tag)
{
tabIndicator1.setTag(tag);
}
#Override
public void addToTab2Navigation(final String tag)
{
tabIndicator2.setTag(tag);
}
#Override
public void addToTab3Navigation(final String tag)
{
tabIndicator3.setTag(tag);
}
#Override
public void onBackPressed()
{
String name=fragmentManager.getBackStackEntryAt(fragmentManager.getBackStackEntryCount()-1).getName();
Fragment fragment=fragmentManager.findFragmentByTag(name);
if(fragment instanceof BaseFragment){
String tag=((BaseFragment)fragment).getPreceddingFragmentTag();
if(tag.equalsIgnoreCase("exit"))
System.exit(0);
else
{
fragment=fragmentManager.findFragmentByTag(tag);
replaceFragment(fragment, tag);
}
}
}
}
and layout of this MainActivity.
<?xml version="1.0" encoding="utf-8"?>
<TabHost
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#android:id/tabhost"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout
android:id="#android:id/tabcontent"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_weight="0"/>
<FrameLayout
android:id="#+android:id/realtabcontent"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"/>
<TabWidget
android:id="#android:id/tabs"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="0"
android:layout_gravity="bottom"/>
</LinearLayout>
</TabHost>
Fragment1:
package com.example.tabs;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import com.actionbarsherlock.sample.fragments.R;
public class Fragment1 extends BaseFragment
{
#Override
public void onCreate(final Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
}
public String toString(){
return "Fragment1";
}
#Override
public View onCreateView(final LayoutInflater inflater, final ViewGroup container, final Bundle savedInstanceState)
{
View view=inflater.inflate(R.layout.fragment1, container, false);
return view;
}
#Override
public void onViewCreated(final View view, final Bundle savedInstanceState)
{
super.onViewCreated(view, savedInstanceState);
CustomAdapter adapt=new CustomAdapter(getActivity(),0);
ListView lv=(ListView)view.findViewById(R.id.mylistview);
lv.setAdapter(adapt);
FragmentChangeListener fc=(FragmentChangeListener)getActivity();
fc.addToTab1Navigation(this.toString());
lv.setOnItemClickListener(new OnItemClickListener()
{
#Override public void onItemClick(final AdapterView<?> arg0, final View arg1, final int position, final long arg3)
{
Fragment fr=new CustomFragment();
Bundle bundle=new Bundle();
bundle.putString("response", "Option "+(position+1));
fr.setArguments(bundle);
FragmentChangeListener fc=(FragmentChangeListener)getActivity();
fc.replaceFragment(fr,"CustomFragment");
}
});
}
#Override
public String getPreceddingFragmentTag()
{
return "exit";
}
}
Fragment2:
package com.example.tabs;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.actionbarsherlock.sample.fragments.R;
public class Fragment2 extends BaseFragment
{
#Override
public void onCreate(final Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
}
public String toString(){
return "Fragment2";
}
#Override
public View onCreateView(final LayoutInflater inflater, final ViewGroup container, final Bundle savedInstanceState)
{
View view=inflater.inflate(R.layout.fragment2, container, false);
FragmentChangeListener fc=(FragmentChangeListener)getActivity();
fc.addToTab2Navigation(this.toString());
return view;
}
#Override
public String getPreceddingFragmentTag()
{
return "exit";
}
}
Fragment3:
package com.example.tabs;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.actionbarsherlock.sample.fragments.R;
public class Fragment3 extends BaseFragment
{
#Override
public void onCreate(final Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
}
public String toString(){
return "Fragment3";
}
#Override
public View onCreateView(final LayoutInflater inflater, final ViewGroup container, final Bundle savedInstanceState)
{
View view=inflater.inflate(R.layout.fragment3, container, false);
FragmentChangeListener fc=(FragmentChangeListener)getActivity();
fc.addToTab3Navigation(this.toString());
return view;
}
#Override
public String getPreceddingFragmentTag()
{
return "exit";
}
}
FragmentChangeListener Interface.
package com.example.tabs;
import android.support.v4.app.Fragment;
public interface FragmentChangeListener
{
public void replaceFragment(final Fragment fragment, final String tag);
public void addToTab1Navigation(String tag);
public void addToTab2Navigation(String tag);
public void addToTab3Navigation(String tag);
}
DummyTabFactory:
package com.example.tabs;
import android.content.Context;
import android.view.View;
import android.widget.TabHost;
class DummyTabFactory implements TabHost.TabContentFactory
{
private final Context mContext;
public DummyTabFactory(final Context context)
{
mContext = context;
}
#Override
public View createTabContent(final String tag)
{
View v = new View(mContext);
v.setMinimumWidth(0);
v.setMinimumHeight(0);
return v;
}
}
CustomFragemnt:
package com.example.tabs;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.actionbarsherlock.sample.fragments.R;
public class CustomFragment extends BaseFragment
{
#Override
public void onCreate(final Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
}
public String toString(){
return "CustomFragment";
}
#Override
public View onCreateView(final LayoutInflater inflater, final ViewGroup container, final Bundle savedInstanceState)
{
FragmentChangeListener fc=(FragmentChangeListener)getActivity();
fc.addToTab1Navigation(this.toString());
View view=inflater.inflate(R.layout.custom_fragment, container, false);
TextView tv=(TextView)view.findViewById(R.id.response);
tv.setText("You Clicked "+getArguments().getString("response"));
return view;
}
#Override
public String getPreceddingFragmentTag()
{
return "Fragment1";
}
}
CustomAdapter:
package com.example.tabs;
import com.actionbarsherlock.sample.fragments.R;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import android.app.Activity;
public class CustomAdapter extends ArrayAdapter<String>
{
Context mcontext;
public CustomAdapter(final Context context, final int textViewResourceId)
{
super(context, textViewResourceId);
mcontext=context;
}
#Override
public int getCount()
{
return 50;
}
#Override
public View getView(final int position, final View convertView, final ViewGroup parent)
{
View row;
if(convertView==null)
{
LayoutInflater inflater = ((Activity)mcontext).getLayoutInflater();
row = inflater.inflate(R.layout.row, parent, false);
}
else
{
row=convertView;
}
TextView tv=(TextView)row.findViewById(R.id.textView1);
tv.setText("Option "+(position+1));
return row;
}
}
BaseFragment:
package com.example.tabs;
import com.actionbarsherlock.app.SherlockFragment;
public abstract class BaseFragment extends SherlockFragment
{
public abstract String getPreceddingFragmentTag();
}
AnotherFragment:
package com.example.tabs;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.actionbarsherlock.sample.fragments.R;
public class AnotherFragment extends BaseFragment
{
#Override
public void onCreate(final Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(final LayoutInflater inflater, final ViewGroup container, final Bundle savedInstanceState)
{
FragmentChangeListener fc=(FragmentChangeListener)getActivity();
fc.addToTab1Navigation(this.toString());
View view=inflater.inflate(R.layout.another_fragment, container, false);
return view;
}
#Override
public String toString()
{
return "AnotherFragment";
}
#Override
public String getPreceddingFragmentTag()
{
return "CustomFragment";
}
}
Layout for AnotherFragment.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/response"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="#string/another"
android:textAppearance="?android:attr/textAppearanceLarge" />
</RelativeLayout>
Layout for CustomFragment:
*<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/response"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:textAppearance="?android:attr/textAppearanceLarge" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/response"
android:text="#string/another_fragment"
android:onClick="clickMe" />
</RelativeLayout>*
Layout for Frament1:
<?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="vertical">
<ListView
android:id="#+id/mylistview"
android:layout_width="match_parent"
android:layout_height="match_parent">
</ListView>
</LinearLayout>
Layout for Fragment2:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="#string/some_text"
android:textAppearance="?android:attr/textAppearanceLarge" />
</RelativeLayout>
Layout for Fragment3:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:src="#drawable/icon"
android:contentDescription="#string/desc" />
</RelativeLayout>
Layout for Row.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=".MainActivity" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:textAppearance="?android:attr/textAppearanceLarge"
android:padding="5dp" />
</RelativeLayout>
Tab.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
tools:context=".MainActivity"
android:layout_margin="3dp"
android:background="#drawable/two_state_button"
android:layout_weight="1">
<ImageView
android:id="#+id/img"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_compose_inverse"
android:layout_centerHorizontal="true"
android:contentDescription="#string/desc"/>
<TextView
android:id="#+id/txt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/img"
android:layout_centerHorizontal="true"/>
</RelativeLayout>
<menu xmlns:android="http://schemas.android.com/apk/res/android"></menu>

My suggestion is you should you fragments instead on using new activity. Fragment will be displayed withing your current activity and you don't need to take care about tabs.
but if your need is to use Activity then Create tabhost in newActivity layout as well as you made in this Activity's Layout.
and while creating intent of another activity, send the current Tab number in extras to new Activity.
Intent i = new Intent(Activity.this, NewActivity.Class);
i.putIntExtra("CurrentVisibleTab", currentTabIndex);
startActivity(i).
In New Activity.
tabHost.setDefault(getIntent().getIntExtra("CurrentVisibleTab"));
Hope this will helpful.

Related

Use Single Fragment Class for Multiple tabs layouts of ViewPager

In TabsDemoApp I trying to use one Fragment and switch between three XML layouts,
I see these questions
"How to know which tab is active in onCreateView function?"
"Use Single Fragment in Multiple tabs of ViewPager"
I have tried to understand it and apply it to this example
here's the full code
TabLayoutAdapter
package com.example.tabsdemoapp;
import java.util.ArrayList;
import java.util.List;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentStatePagerAdapter;
public class TabLayoutAdapter extends FragmentStatePagerAdapter {
int mNumOfTabs;
public TabLayoutAdapter(#NonNull FragmentManager fm, int mNumOfTabs) {
super(fm, mNumOfTabs);
this.mNumOfTabs = mNumOfTabs;
}
#NonNull
#Override
public Fragment getItem(int position) {
return TabFragment.newInstance(position);
}
#Override
public int getCount() {
return mNumOfTabs;
}
}
TabFragment
package com.example.tabsdemoapp;
import android.content.Context;
import android.os.Bundle;
import android.provider.SyncStateContract;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
public class TabFragment extends Fragment {
private static String ARG_POSITION = "position";
private static int fragmentId = 0;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater,
#Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
if(container.getId() == R.id.tab1) {
return inflater.inflate(R.layout.tab1, container, false);
}else if(container.getId() == R.id.tab2){
return inflater.inflate(R.layout.tab2, container, false);
}else {
return inflater.inflate(R.layout.tab3, container, false);
}
}
public static TabFragment newInstance(int position) {
TabFragment fragment = new TabFragment();
Bundle bundle = new Bundle();
bundle.putInt(ARG_POSITION, position);
fragment.setArguments(bundle);
return fragment;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
fragmentId = getArguments().getInt(ARG_POSITION,fragmentId);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
assert getTargetFragment() != null;
getChildFragmentManager().beginTransaction().
replace(R.id.container, getTargetFragment()).
commit();
}
#Override
public void onAttach(#NonNull Context context) {
super.onAttach(context);
}
#Override
public void onDetach() {
super.onDetach();
}
}
main_activity.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:id="#+id/rootView"
tools:context=".MainActivity">
<com.google.android.material.tabs.TabLayout
android:id="#+id/myTabLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
tools:layout_editor_absoluteX="1dp"
tools:layout_editor_absoluteY="186dp">
</com.google.android.material.tabs.TabLayout>
<androidx.viewpager.widget.ViewPager
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/viewPager"
app:elevation="5dp"
>
</androidx.viewpager.widget.ViewPager>
</LinearLayout>
MainActivity Class
public class MainActivity extends AppCompatActivity {
TabLayout tabLayout;
ViewPager viewPager;
TabLayoutAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tabLayout = findViewById(R.id.myTabLayout);
viewPager = findViewById(R.id.viewPager);
tabLayout.setupWithViewPager(viewPager);
adapter = new TabLayoutAdapter(getSupportFragmentManager(), tabLayout.getTabCount());
viewPager.setAdapter(adapter);
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
switch (tab.getPosition()) {
case 0:
viewPager.setCurrentItem(tab.getPosition());
break;
case 1:
viewPager.setCurrentItem(tab.getPosition());
break;
case 2:
viewPager.setCurrentItem(tab.getPosition());
break;
default:
viewPager.setCurrentItem(tab.getPosition());
}
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
}
and there's a three XML for each tab, tab1, tab2, tab3
tab1.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:id="#+id/tab1"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="Tab one"
android:textAppearance="?android:attr/textAppearanceLarge"/>
</RelativeLayout>
tab2.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:id="#+id/tab2"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="Tab two"
android:textAppearance="?android:attr/textAppearanceLarge"/>
</RelativeLayout>
tab3.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">
<TextView
android:id="#+id/tab3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="Tab three"
android:textAppearance="?android:attr/textAppearanceLarge"/>
</RelativeLayout>
after running the app I see a blank page, there's no ViewPager and TabLayout
Make title for TabLayout, your TabLayoutAdapter should override getPageTitle
#Override
public CharSequence getPageTitle(int position) {
return "Tab " + position;
}
You wrong here container pass to onCreateView always is "#+id/viewPager"
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater,
#Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
if(container.getId() == R.id.tab1) {
return inflater.inflate(R.layout.tab1, container, false);
}else if(container.getId() == R.id.tab2){
return inflater.inflate(R.layout.tab2, container, false);
}else {
return inflater.inflate(R.layout.tab3, container, false);
}
}
Change this code to
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater,
#Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
if(fragmentId == 0) {
return inflater.inflate(R.layout.tab1, container, false);
}else if(fragmentId == 1){
return inflater.inflate(R.layout.tab2, container, false);
}else {
return inflater.inflate(R.layout.tab3, container, false);
}
}
Init TabLayoutAdapter by total fragments instead of by tabLayout.getTabCount() because now tabLayout doesn't have child tab it will be return 0.
adapter = new TabLayoutAdapter(getSupportFragmentManager(), 3);

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;
}

My ViewPager is empty

I've created an about activity in my Android application, with a ViewPager. But I can't see any content
My AboutActivity.java:
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v13.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.loloof64.android.chess_positions_archiver.R;
/**
* The about activity
*/
public class AboutActivity extends Activity {
static final int NUM_ITEMS = 2;
AboutDialogFragmentPagerAdapter pagerAdapter;
ViewPager viewPager;
static String pagesContents [] = new String[NUM_ITEMS];
public void exit(View view){
finish();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.about_dialog_layout);
pagesContents[0] = getString(R.string.this_app_manual);
pagesContents[1] = getString(R.string.about_resources_content);
pagerAdapter = new AboutDialogFragmentPagerAdapter(getFragmentManager(),
new String[]{
"Chess Positions Archiver",
getString(R.string.about_resources_title)
});
viewPager = (ViewPager) findViewById(R.id.about_dialog_pager);
viewPager.setAdapter(pagerAdapter);
viewPager.setCurrentItem(0);
}
public static class AboutDialogFragmentPagerAdapter extends FragmentStatePagerAdapter {
private String [] titles;
public AboutDialogFragmentPagerAdapter(FragmentManager fragmentManager, String [] titles){
super(fragmentManager);
this.titles = titles;
}
#Override
public Fragment getItem(int position) {
return AboutDialogSingleFragment.newInstance(position);
}
#Override
public int getCount() {
return NUM_ITEMS;
}
#Override
public CharSequence getPageTitle(int position) {
return titles[position];
}
}
public static class AboutDialogSingleFragment extends Fragment {
static String PAGE_TEXT_KEY = "PageTextKey";
private String pageText;
static AboutDialogSingleFragment newInstance(int position){
AboutDialogSingleFragment fragment = new AboutDialogSingleFragment();
Bundle arguments = new Bundle();
arguments.putString(PAGE_TEXT_KEY, pagesContents[position]);
fragment.setArguments(arguments);
return fragment;
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.about_dialog_single_page_layout, container, false);
TextView pageTextView = (TextView) view.findViewById(R.id.about_dialog_page_textview);
pageTextView.setText(pageText);
container.addView(view);
return view;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
pageText = getArguments() != null ? getArguments().getString(PAGE_TEXT_KEY) : getResources().getString(R.string.about_dialog_content_error);
}
}
}
My about_dialog_layout.xml :
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/about_dialog_tabs"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v4.view.ViewPager
android:id="#+id/about_dialog_pager"
android:layout_width="match_parent"
android:layout_height="0px"
android:layout_weight="1">
</android.support.v4.view.ViewPager>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:text="#string/quit_about"
android:onClick="exit" />
</RelativeLayout>
My about_dialog_single_page_layout.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">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/about_dialog_page_textview"/>
</LinearLayout>
I am using the support library 13.
So, what is my programming error ?
android:layout_weight="1" works only with LinearLayout (it is a property of LinearLayout). Since the ViewPager's parent is a RelativeLayout the property is ignored, and your ViewPager has height 0, which explain why you are not see anything

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;
}
}

Refresh Fragment View inside itself

I have a big request for any of You. I would like to create a third Fragment in my simple application. Everything works fine, no error. I would like to make the last Fragment it is: "TestFragment" when I click that button inside that Fragment I'd like to refresh its View (on click button) and load another view inside this fragment (the same fragment). Please help me do this, show how to get it. I have read in Google but can not find the solution appropriate for this application.
Here is simple code:
MAIN ACTIVITY:
package com.example.viewpagerexample;
import com.example.viewpagerexample.R;
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.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
public class MainActivity extends FragmentActivity {
private MyAdapter mAdapter;
private ViewPager mPager;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAdapter = new MyAdapter(getSupportFragmentManager());
mPager = (ViewPager) findViewById(R.id.pager);
mPager.setAdapter(mAdapter);
}
public static class MyAdapter extends FragmentPagerAdapter {
public MyAdapter(FragmentManager fm) {
super(fm);
}
#Override
public int getCount() {
return 2;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new TestFragment();
// case 1:
// return new ImageFragment();
case 1:
return new TestFragment();
//
default:
return null;
}
}
}
}
TEST FRAGMENT:
package com.example.viewpagerexample;
import com.example.viewpagerexample.R;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class TestFragment extends Fragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.e("Test", "hello");
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.test, container, false);
// TextView textView = (TextView) view.findViewById(R.id.detailsText);
// textView.setText("Testing");
return view;
}
}
TEST LAYOUT:
<?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="QUIZ IMPORTANT TAKE A LOOK AT THIS!!!!!"
android:textSize="30dp" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button"
android:layout_marginLeft="30dp" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="asdjiasdjasoldjasjdasjdlasjdksahfkadshfalidshfladshfladsfhlasdfgjl;adkglkafdgnklfdsgjpfasmga.dsnvlkasdnvkldsnflkdasjflkasdnvlkadjvodsijfosdjv;lasdvlasdjvladosijao" />
DETAILS FRAGMENT:
package com.example.viewpagerexample;
import com.example.viewpagerexample.R;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class Details extends Fragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.e("Test", "hello");
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.details, container, false);
TextView textView = (TextView) view.findViewById(R.id.detailsText);
textView.setText("Testing");
return view;
}
}
ACTIVITY_MAIN LAYOUT:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</LinearLayout>
DETAILS LYOUT:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</LinearLayout>
How to do this refresh inside the same fragment?

Categories

Resources