Android 4.0中的标签栏应用程序

时间:2013-04-12 06:34:28

标签: android android-actionbar android-webview android-tabs

我将在Android 4.0中开发一个Android应用程序,如下图所示。

ActionBar with Tab

我必须动态创建这些标签,动态调用addTab()方法并动态创建标签栏。 ActionBarWithTab 是否符合我的要求。?以正确的方式指导我。请提供教程。

编辑1:我需要在ActionBar中创建的单独标签栏中加载webview。

EIDT 2:为了使用TabHost创建标签栏,首先我为TabHost创建了ViewGroup,并添加了标签栏项,如下面的代码。在标签栏项目中,我创建了布局,在布局内部创建了一个webview,并将动态URL加载到标签栏项目中。最后,我将viewgroup设置为contentview();

    sTabHost = new TabHost(context,null);
    sTabHost.setLayoutParams(
            new LinearLayout.LayoutParams(
                    LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));


    TabWidget tabWidget = new TabWidget(context);
    tabWidget.setId(android.R.id.tabs);
    sTabHost.addView(tabWidget, new LinearLayout.LayoutParams(
              LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT)); 


    FrameLayout frameLayout = new FrameLayout(context);
    frameLayout.setId(android.R.id.tabcontent);
    final float scale = context.getResources().getDisplayMetrics().density;
    int paddingtop = (int) (64 * scale + 0.5f);
    frameLayout.setPadding(0, paddingtop, 0, 0);
    sTabHost.addView(frameLayout, new LinearLayout.LayoutParams(
              LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));         

    sTabHost.setup();        

然后我添加了如下所示的标签项。

 public void addTabItem(final String url, String tabTitle, Drawable tabIcon)
{    
    TabSpec ts1 = sTabHost.newTabSpec(tabTitle); 
    if(tabTitle.equals(""))
    {
        int childcount=sTabHost.getChildCount();
        tabTitle="Tab" + String.valueOf(childcount+1);          
    }
    if(tabIcon==null)
        ts1.setIndicator(tabTitle);
    else
        ts1.setIndicator(tabTitle,tabIcon);        
    ts1.setContent(new TabHost.TabContentFactory(){
         public View createTabContent(String tag)
         {               
                LinearLayout panel = new LinearLayout(sActiveContext);
                panel.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, 
                        LayoutParams.WRAP_CONTENT));
                panel.setOrientation(LinearLayout.VERTICAL);
                FrameLayout layout=new FrameLayout();
                    // Here I am creating the webview loaded with the url within the layout and placed into the above FrameLayout.                  
                panel.addView(layout);
                return panel;
         }  
    }); 
    sTabHost.addTab(ts1);
    sTabHost.setOnTabChangedListener(this);
  }

现在,我如何在动作栏中实现这一点,就像我添加的图像一样。?

我创建了操作栏,其中包含以下代码的标签。

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    final ActionBar actionBar = getActionBar();
    actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

    Tab tabA = actionBar.newTab();
    tabA.setText("Tab A");
    tabA.setTabListener(new TabListener<MyFragmentA>(this, "Tag A", MyFragmentA.class));
    actionBar.addTab(tabA);
}

TabListener类如下所示。

public static class TabListener<T extends Fragment> 
    implements ActionBar.TabListener{

    private final Activity myActivity;
    private final String myTag;
    private final Class<T> myClass;

    public TabListener(Activity activity, String tag, Class<T> cls) {
        myActivity = activity;
        myTag = tag;
        myClass = cls;
    }

    @Override
    public void onTabSelected(Tab tab, FragmentTransaction ft) {

        Fragment myFragment = myActivity.getFragmentManager().findFragmentByTag(myTag);

        // Check if the fragment is already initialized
        if (myFragment == null) {
            // If not, instantiate and add it to the activity
            myFragment = Fragment.instantiate(myActivity, myClass.getName());
            ft.add(android.R.id.content, myFragment, myTag);
        } else {
            // If it exists, simply attach it in order to show it
            ft.show(myFragment);
        }

    }

    @Override
    public void onTabUnselected(Tab tab, FragmentTransaction ft) {

        Fragment myFragment = myActivity.getFragmentManager().findFragmentByTag(myTag);

        if (myFragment != null) {
            // Detach the fragment, because another one is being attached
            ft.hide(myFragment);
        }

    }

    @Override
    public void onTabReselected(Tab tab, FragmentTransaction ft) {
        // TODO Auto-generated method stub
    }

}

Fragment类如下。

  @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    View myFragmentView = inflater.inflate(R.layout.fragment_c, container, false);

    WebView webview = (WebView) myFragmentView.findViewById(R.id.webview);
    webview.setWebViewClient(new MyWebViewClient());
    webview.getSettings().setJavaScriptEnabled(true);
    webview.getSettings().setPluginsEnabled(true);
    webview.getSettings().setBuiltInZoomControls(false); 
    webview.getSettings().setSupportZoom(false);
    webview.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);   
    webview.getSettings().setAllowFileAccess(true); 
    webview.getSettings().setDomStorageEnabled(true); 
    webview.loadUrl("http://jquerymobile.com/demos/1.2.1/");

    return myFragmentView;
}

public class MyWebViewClient extends WebViewClient {        
    /* (non-Java doc)
     * @see android.webkit.WebViewClient#shouldOverrideUrlLoading(android.webkit.WebView, java.lang.String)
     */


    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        if (url.endsWith(".mp4")) 
        {
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setDataAndType(Uri.parse(url), "video/*");

            view.getContext().startActivity(intent);
            return true;
        } 
        else {
            return super.shouldOverrideUrlLoading(view, url);
        }
    }
}

在上面的实现中,我创建了布局和单独的片段类。而不是像这样创建如何在不创建xml布局和单独的片段类的情况下实现此目的。这就像我为TabHost标签栏发布的代码。

编辑3:我创建了操作栏和标签项,如下面的代码。

 public void addTabBar(Context context)
{       
    sActiveContext=context;
    sActionBar = getActionBar();
    sActionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
}

public void addTabItem(final String url, String tabTitle)
{   
    Tab tab = sActionBar.newTab();
    if(tabTitle.equals(""))
    {
        int childcount=sActionBar.getTabCount();
        tabTitle="Tab" + String.valueOf(childcount+1);          
    }
    tab.setText(tabTitle);
     //Here I need to create the Layout with the webview and loaded into the created tab.
    tab.setTabListener(this);
    sActionBar.addTab(tab);
}

如何使用给定网址将webview加载到特定标签。?

3 个答案:

答案 0 :(得分:3)

带有碎片的操作栏

试试这个,这很好..

在清单文件中,

<uses-sdk
        android:minSdkVersion="11"/>
<application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
<activity
            android:name="packageName.ActionBarFragmentActivity"
            android:configChanges="orientation"
            android:theme="@android:style/Theme.Holo.Light"
            android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
</application>
<!--change  packageName -->

ActionBarFragmentActivity.java

@SuppressLint("NewApi")
public class ActionBarFragmentActivity extends FragmentActivity implements TabListener{
    private ActionBar actionBar=null;
    private Fragment1 fragment1=null;
    private Fragment2 fragment2=null;
    private Fragment3 fragment3=null;
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.main_layout);
        actionBar=getActionBar();
        actionBar.setDisplayShowHomeEnabled(true);
        actionBar.setDisplayShowTitleEnabled(false);
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

        actionBar.addTab(actionBar.newTab().setTag("first").setText("First").setTabListener(this));
        actionBar.addTab(actionBar.newTab().setTag("second").setText("Second").setTabListener(this));
        actionBar.addTab(actionBar.newTab().setTag("third").setText("Third").setTabListener(this));

        fragment1=new Fragment1();
        fragment2=new Fragment2();
        fragment3=new Fragment3();

        getSupportFragmentManager().beginTransaction().replace(R.id.frameLayout,fragment1);
    }

    @Override
    public void onTabReselected(Tab tab, FragmentTransaction ft) {
    }
    @Override
    public void onTabSelected(Tab tab, FragmentTransaction ft) {
        if(tab.getPosition()==0)
        {
            getSupportFragmentManager().beginTransaction().replace(R.id.frameLayout,fragment1).commit();
            fragment1.onUpdateView();
        }
        else if(tab.getPosition()==1)
        {
            getSupportFragmentManager().beginTransaction().replace(R.id.frameLayout,fragment2).commit();
            fragment2.onUpdateView();
        }
        else if(tab.getPosition()==2)
        {
            getSupportFragmentManager().beginTransaction().replace(R.id.frameLayout,fragment3).commit();
            fragment3.onUpdateView();
        }
    }
    @Override
    public void onTabUnselected(Tab tab, FragmentTransaction ft) {
    }
}

main_layout.xml

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/frameLayout"
    android:orientation="vertical" >
</FrameLayout>

webview_layout.xml

<WebView 
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:id="@+id/webView"
    android:layout_height="match_parent" >
</WebView>

Fragment1.java

public class Fragment1 extends android.support.v4.app.Fragment{
    private WebView webView=null;
    public void onCreate(Bundle savedInstanceState) 
    { 
        super.onCreate(savedInstanceState); 
    } 
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) 
    {
          View view = inflater.inflate(R.layout.webview_layout, container, false);
          webView=(WebView)view.findViewById(R.id.webView);
          return view;
    }
    @Override
    public void onStart()
    {
        super.onStart();
    }
    @Override
    public void onPause()
    {
        super.onPause();
    }
    @Override
    public void onResume()
    {
        super.onResume();
    }
    @Override
    public void onStop()
    {
        super.onStop();
    }
    @Override
    public void onDestroy()
    {
        super.onDestroy();
    }
    @Override
    public void onSaveInstanceState(Bundle outState) 
    {
        super.onSaveInstanceState(outState);
    }
    @Override
    public void onActivityCreated(Bundle bundle)
    {
        super.onActivityCreated(bundle);
        onUpdateView();
    }
    public void onUpdateView()
    {
        webView.getSettings().setJavaScriptEnabled(true);
        webView.loadUrl("https://docs.google.com/viewer?url=http://121.242.120.82:8090/iSmartDM/DC/KIMS_Hospital_28/KIMS_hospital_Default_29" +
                "/Physician_2_37/DOC/stamos-5644-00@gs138a-[01062006]-[160859]-[ds4000]-[].rtf");
    }
}

Fragmet2.java

public class Fragment2 extends android.support.v4.app.Fragment{
    private WebView webView=null;
    public void onCreate(Bundle savedInstanceState) 
    { 
        super.onCreate(savedInstanceState); 
    } 
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) 
    {
          View view = inflater.inflate(R.layout.webview_layout, container, false);
          webView=(WebView)view.findViewById(R.id.webView);
          return view;
    }
    @Override
    public void onStart()
    {
        super.onStart();
    }
    @Override
    public void onPause()
    {
        super.onPause();
    }
    @Override
    public void onResume()
    {
        super.onResume();
    }
    @Override
    public void onStop()
    {
        super.onStop();
    }
    @Override
    public void onDestroy()
    {
        super.onDestroy();
    }
    @Override
    public void onSaveInstanceState(Bundle outState) 
    {
        super.onSaveInstanceState(outState);
    }
    @Override
    public void onActivityCreated(Bundle bundle)
    {
        super.onActivityCreated(bundle);
    }
    public void onUpdateView()
    {
        webView.getSettings().setJavaScriptEnabled(true);
        webView.loadUrl("http://www.google.co.in/");
    }
}

Fragment3.java

public class Fragment3 extends android.support.v4.app.Fragment{
    private WebView webView=null;
    public void onCreate(Bundle savedInstanceState) 
    { 
        super.onCreate(savedInstanceState); 
    } 
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) 
    {
          View view = inflater.inflate(R.layout.webview_layout, container, false);
          webView=(WebView)view.findViewById(R.id.webView);
          return view;
    }
    @Override
    public void onStart()
    {
        super.onStart();
    }
    @Override
    public void onPause()
    {
        super.onPause();
    }
    @Override
    public void onResume()
    {
        super.onResume();
    }
    @Override
    public void onStop()
    {
        super.onStop();
    }
    @Override
    public void onDestroy()
    {
        super.onDestroy();
    }
    @Override
    public void onSaveInstanceState(Bundle outState) 
    {
        super.onSaveInstanceState(outState);
    }
    @Override
    public void onActivityCreated(Bundle bundle)
    {
        super.onActivityCreated(bundle);
    }
    public void onUpdateView()
    {
        webView.getSettings().setJavaScriptEnabled(true);
        webView.loadUrl("http://www.youtube.com/?gl=IN&tab=w1");
    }
}

编辑-------------“动态布局”------------------- 活动:-     的onCreate();

FrameLayout frameLayout=new FrameLayout(this);
    setContentView(frameLayout);
    frameLayout.setId(1111);

片段交易......

getSupportFragmentManager().beginTransaction().replace(1111,fragment1).commit();

片段: -

@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) 
    {
        webView=new WebView(getActivity());
        webView.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT));
        return webView;
    }

答案 1 :(得分:1)

回答编辑3: - 试试这个,

@SuppressLint("ValidFragment")
public class Sample extends FragmentActivity implements TabListener{
    private ActionBar mActionBar=null;
    private ArrayList<String> arrayList=null;
    private LinearLayout linearLayout=null;
    private WebView webView=null;
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        linearLayout=new LinearLayout(this);
        linearLayout.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT)); 
        linearLayout.setOrientation(LinearLayout.VERTICAL); 
        setContentView(linearLayout);
        mActionBar=getActionBar();
        mActionBar.setDisplayShowHomeEnabled(true);
        mActionBar.setDisplayShowTitleEnabled(false);
        mActionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
            webView=new WebView(this);
        linearLayout.addView(webView);
        arrayList=new ArrayList<String>();
        addTab(0,"https://docs.google.com/viewer?url=http://121.242.120.82:8090/iSmartDM/DC/KIMS_Hospital_28/KIMS_hospital_Default_29" +
                    "/Physician_2_37/DOC/stamos-5644-00@gs138a-[01062006]-[160859]-[ds4000]-[].rtf");
        addTab(1,"https://www.google.co.in");
        addTab(2,"http://stackoverflow.com/questions/15964641/tab-bar-app-in-android-4-0/16009038?noredirect=1#comment22832140_16009038");
    }
    private void addTab(int position,String URL)
    {
mActionBar.addTab(mActionBar.newTab().setTag("tab"+String.valueOf(position)).
                    setText("Tab "+String.valueOf(position)).setTabListener(this));
            arrayList.add(URL);
        }
        @Override
        public void onTabReselected(Tab tab, FragmentTransaction ft) {
        }
        @Override
        public void onTabSelected(Tab tab, FragmentTransaction ft) {
    webView.getSettings().setJavaScriptEnabled(true);
                for (int i = 0; i < arrayList.size(); i++) {
                    if(tab.getPosition()==i)
                    {
                        webView.loadUrl(arrayList.get(i));
                        System.out.println(arrayList.get(i));
                        break;
                    }
                }
        }
        @Override
        public void onTabUnselected(Tab tab, FragmentTransaction ft) {
            //if(webView!=null)
                //linearLayout.removeView(webView);
        }
    }

答案 2 :(得分:0)

我认为This对你有用,可以处理Action Bar。另请访问this以了解Action Bar的用途。示例和详细说明here

您可以对片段(子选项卡)中的选项卡使用Tab Host控件。当你需要的时候 片段上的子选项卡,然后将该片段的布局用作

sub_tab_fragment.xml,

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="vertical"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent">
    <TabHost
        android:id="@android:id/tabhost"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        >
        <LinearLayout
            android:orientation="vertical"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            >

            <TabWidget
                android:id="@android:id/tabs"
                android:orientation="horizontal"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_weight="0"
                />

            <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="fill_parent"
                android:layout_height="0dp"
                android:layout_weight="1"/>
        </LinearLayout>
    </TabHost>
</LinearLayout> 

然后在片段里面,

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) 
{   
     View view = inflater.inflate(R.layout.sub_tab_fragment, container, false);
     mTabHost=(TabHost)v.findViewById(android.R.id.tabhost);
     return v;
}
@Override
public void onActivityCreated(Bundle bundle)
{
    super.onActivityCreated(bundle);
    mTabHost.setup();

    View tabview = createTabView(mTabHost.getContext(), "First");
        mTabHost.addTab(mTabHost.newTabSpec("First").setIndicator(tabview).setContent(R.id.realtabcontent));

    View tabview1 = createTabView(mTabHost.getContext(), "Second");
        mTabHost.addTab(mTabHost.newTabSpec("Second").setIndicator(tabview1).setContent(R.id.realtabcontent));

    View tabview2 = createTabView(mTabHost.getContext(), "Third");
        mTabHost.addTab(mTabHost.newTabSpec("Third").setIndicator(tabview2).setContent(R.id.realtabcontent));

    View tabview3 = createTabView(mTabHost.getContext(), "Fourth");
        mTabHost.addTab(mTabHost.newTabSpec("Fourth").setIndicator(tabview3).setContent(R.id.realtabcontent));

    View tabview4 = createTabView(mTabHost.getContext(), "Fifth");
        mTabHost.addTab(mTabHost.newTabSpec("Fifth").setIndicator(tabview4).setContent(R.id.realtabcontent));


  mTabHost.setOnTabChangedListener(mTabListener);
}

然后,您将实现/处理选项卡的内容(Action Bar中使用的相同方法)。

已编辑----- addTabItem(final String url,String tabTitle,Drawable tabIcon) * ****

public void addTabItem(final String url, String tabTitle, Drawable tabIcon)
{    
    WebView webView=null;
    TabSpec ts1 = sTabHost.newTabSpec(tabTitle); 
    if(tabTitle.equals(""))
    {
        int childcount=sTabHost.getChildCount();
        tabTitle="Tab" + String.valueOf(childcount+1);          
    }
    if(tabIcon==null)
        ts1.setIndicator(tabTitle);
    else
        ts1.setIndicator(tabTitle,tabIcon);        
    ts1.setContent(new TabHost.TabContentFactory(){
         public View createTabContent(String tag)
         {               
               webView=new WebView(sActiveContext);
           webView.setLayoutParams(new android.view.ViewGroup.LayoutParams(android.view.ViewGroup.LayoutParams.FILL_PARENT, 
                android.view.ViewGroup.LayoutParams.WRAP_CONTENT));
                return webView;
         }  
    }); 
    sTabHost.addTab(ts1);
    sTabHost.setOnTabChangedListener(this);
    webView.getSettings().setJavaScriptEnabled(true);
        webView.loadUrl("https://docs.google.com/viewer?url=http://121.242.120.82:8090/iSmartDM/DC/KIMS_Hospital_28/KIMS_hospital_Default_29" +
                "/Physician_2_37/DOC/stamos-5644-00@gs138a-[01062006]-[160859]-[ds4000]-[].rtf");
  }