如何在每个活动上保持标签可见

时间:2013-07-29 07:24:07

标签: android android-fragments android-tabs

我是android编程的新手,我正在尝试使用片段实现制表符。 我正在使用此Tutorial。一切都很顺利,但我的问题是,我想打开一个新的活动,在这个新的活动,我想保持标签栏。我希望在标签内打开的每个新活动上都可以看到标签栏。我有以下代码..

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

}

2 个答案:

答案 0 :(得分:3)

这是主要活动。

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

}
}

以及此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>

片段1:

    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接口。

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

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>

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>*

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>

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>

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>

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>

答案 1 :(得分:0)

我的建议是你应该在使用新活动时分段。片段将与您当前的活动一起显示,您无需关注标签。

但是如果您需要使用Activity,那么在newActivity布局中创建tabhost以及在此Activity的布局中创建。 在创建另一个活动的意图时,将额外的当前标签号发送给新活动。

 Intent i = new Intent(Activity.this, NewActivity.Class);
 i.putIntExtra("CurrentVisibleTab", currentTabIndex);
 startActivity(i).

在新活动中。

tabHost.setDefault(getIntent().getIntExtra("CurrentVisibleTab"));

希望这会有所帮助。