Raj
Raj

Reputation: 506

how to keep tabs visible on every activity

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

}

Upvotes: 3

Views: 3738

Answers (2)

Ahmad Raza
Ahmad Raza

Reputation: 2850

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>

Upvotes: 3

Ahmad Raza
Ahmad Raza

Reputation: 2850

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.

Upvotes: 0

Related Questions