ActionBar的用法

1. 使用自定义的View填充ActionBar

package com.example.searchviewdemos;

import java.util.ArrayList;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SearchView;

public class MainActivity extends Activity implements SearchView.OnQueryTextListener{

	ListView mListView;
	SearchView mSearchView;
	Object[] mNames;
	ArrayAdapter<String> adapter;
	ArrayList<String> mAllList = new ArrayList<String>();
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		initActionbar();
		mNames = loadData();
		mListView = (ListView) findViewById(R.id.list);
		mListView.setAdapter(new ArrayAdapter<Object>(getApplicationContext(),
				android.R.layout.simple_expandable_list_item_1, mNames));

		mListView.setTextFilterEnabled(true);
		mSearchView.setOnQueryTextListener(this);//监听输入框字符串变化
		mSearchView.setSubmitButtonEnabled(false);//不显示查询提交按钮
	}

	/**
	 * 当输入框内容变化时,会回调该方法,例如用户通过键盘在搜索框中输入该字符时,该方法就回回调,arg0为输入的内容。
	 * return false-表示查询的动作已经由该监听器处理完毕;
	 *        true-让SearchView执行默认的动作
	 */
	@Override
	public boolean onQueryTextChange(String arg0) {
		// TODO Auto-generated method stub
		Object[] obj = searchItem(arg0);
		updateLayout(obj);
		Log.d("yxf","onQueryTextChange, arg0 = " + arg0);
		/*
		if (TextUtils.isEmpty(arg0)) {
			// Clear the text filter.
			mListView.clearTextFilter();
		} else {
			// Sets the initial value for the text filter.
			//过该函数可以一方面进行数据的过滤,另一方面显示一个PopupWindow,提示用户输入了那种过滤条件。
			mListView.setFilterText(arg0.toString());
		}
		*/	
		return false;
	}

	public Object[] searchItem(String name) {
		ArrayList<String> mSearchList = new ArrayList<String>();
		for (int i = 0; i < mAllList.size(); i++) {
			int index = mAllList.get(i).indexOf(name);
			// 存在匹配的数据
			if (index != -1) {
				mSearchList.add(mAllList.get(i));
			}
		}
		return mSearchList.toArray();
	}

	public void updateLayout(Object[] obj) {
		mListView.setAdapter(new ArrayAdapter<Object>(getApplicationContext(),
				android.R.layout.simple_expandable_list_item_1, obj));
	}
    
	/*
	 * 当用户通过键盘提交输入的内容时,会调用该方法。(non-Javadoc)
	 * @see android.widget.SearchView.OnQueryTextListener#onQueryTextSubmit(java.lang.String)
	 * return false--表示改监听器已经处理完查询的请求;
	 *        treu-让SearchView执行默认的查询操作。
	 */
	@Override
	public boolean onQueryTextSubmit(String arg0) {
		// TODO Auto-generated method stub
		Log.d("yxf","onQueryTextSubmit, arg0 = " + arg0);
		return false;
	}
	
	public void initActionbar() {
		//是否显示应用的home图标,它是activity的logo或icon,如果为false,则只有标题,没有图标。
		getActionBar().setDisplayShowHomeEnabled(true);

		getActionBar().setDisplayShowTitleEnabled(true);

		//给左上角加上一个返回的图标 ,默认为“<”,对应ActionBar.DISPLAY_HOME_AS_UP。点击它可以返回上一个Activity.
		getActionBar().setDisplayHomeAsUpEnabled(true); 
		// 使自定义的普通View能在title栏显示,即actionBar.setCustomView能起作用,对应ActionBar.DISPLAY_SHOW_CUSTOM
		getActionBar().setDisplayShowCustomEnabled(true);
		LayoutInflater mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		/*使用inflate(int resource, ViewGroup root)时会出现该SearchView填不满ActionBar的问题*/
//		View mTitleView = mInflater.inflate(R.layout.custom_action_bar_layout,
//				null);
		View mTitleView = mInflater.inflate(R.layout.custom_action_bar_layout,
				new LinearLayout(this),false);
		getActionBar().setCustomView(mTitleView);
		mSearchView = (SearchView) mTitleView.findViewById(R.id.search_view);
	}
	
	public Object[] loadData() {
		mAllList.add("aa");
		mAllList.add("ab");
		mAllList.add("ddfa");
		mAllList.add("qw");
		mAllList.add("sd");
		mAllList.add("fd");
		mAllList.add("cf");
		mAllList.add("re");
		return mAllList.toArray();
	}
}

res/layout/activity_main.xml

<LinearLayout 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" >

    <ListView
        android:id="@+id/list"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#969696" />
</LinearLayout>
res/layout/custom_action_bar_layout.xml

<?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="horizontal" >
    
    <SearchView
        android:id="@+id/search_view"
        android:layout_width="0px"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:iconifiedByDefault="true"
        android:inputType="textFilter"
        android:queryHint="@string/title_search_hint" >
    </SearchView>
    
    <Button 
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="自定义按钮"/>

</LinearLayout>
2.使用Spinner

package com.example.spinneroptions;

import android.os.Bundle;
import android.app.ActionBar;
import android.app.Activity;
import android.app.Fragment;
import android.view.Menu;
import android.widget.ArrayAdapter;
import android.widget.SpinnerAdapter;

public class SpinnerOptionsActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_spinner_options);
        
        SpinnerAdapter spinnerAdapter = ArrayAdapter.createFromResource(this, R.array.action_list,
        		android.R.layout.simple_spinner_dropdown_item);
        getActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
        ActionBar.OnNavigationListener mOnNavigationListener = new ActionBar.OnNavigationListener() {  
        	  
            @Override  
            public boolean onNavigationItemSelected(int position, long itemId) {  
                Fragment newFragment = null;  
                switch (position) {  
                case 0:  
                    //newFragment = new Fragment1();  
                    break;  
                case 1:  
                    //newFragment = new Fragment2();  
                    break;  
                case 2:  
                    //newFragment = new Fragment3();  
                    break;  
                default:  
                    break;  
                }  
                return true;  
            }  
        };  
        getActionBar().setListNavigationCallbacks(spinnerAdapter,  
                mOnNavigationListener);  
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.spinner_options, menu);
        return true;
    }
    
}

3.以Tab形式显示

需要实现接口ActionBar.TabListener,它有以下三个方法:

//Called when a tab that is already selected is chosen again by the user.
public abstract void onTabReselected (ActionBar.Tab tab, FragmentTransaction ft);
//Called when a tab enters the selected state.
public abstract void onTabSelected (ActionBar.Tab tab, FragmentTransaction ft);
//Called when a tab exits the selected state.
public abstract void onTabUnselected (ActionBar.Tab tab, FragmentTransaction ft);

然后,调用actionBar的setTabListener(ActionBar.TabListener listene)r方法

package com.example.actionbartabs;

import android.os.Bundle;
import android.app.ActionBar;
import android.app.Activity;
import android.app.FragmentTransaction;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.Fragment;
import android.view.Menu;

public class ActionBarTabs extends FragmentActivity implements  
ActionBar.TabListener {  
    private ActionBar actionBar;  

    @Override  
    protected void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);  
        setContentView(R.layout.activity_action_bar_tabs);  
        actionBar = getActionBar();  
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);// 导航模式必须设为NAVIGATION_MODE_Tabs  

        // For each of the sections in the app, add a tab to the action bar.  

        actionBar.addTab(actionBar.newTab().setText(R.string.title_section1)  
            .setTabListener(this));  
        actionBar.addTab(actionBar.newTab().setText(R.string.title_section2)  
            .setTabListener(this));  
        actionBar.addTab(actionBar.newTab().setText(R.string.title_section3)  
            .setTabListener(this));
    }


    @Override  
    public void onTabSelected(ActionBar.Tab tab,  
        FragmentTransaction fragmentTransaction) { 
    	// When the given tab isselected, show the tabcontents in the  
    	// //container view.  
    	Fragment fragment3 = null;  
    	Fragment fragment1 = null;  
    	Fragment fragment2 = null;  
    	switch (tab.getPosition()) {  
    	case 0:  
    	    if (fragment1 == null) {  
    	        fragment1 = new Fragment();  
    	    }  
    	    getSupportFragmentManager().beginTransaction().replace(R.id.container, fragment1).commit();  
    	    break;  
    	case 1:  
    	    if (fragment2 == null) {  
    	        fragment2 = new Fragment();  
    	    }  
    	    getSupportFragmentManager().beginTransaction().replace(R.id.container, fragment2).commit();
    	    break;  
    	case 2:  
    	    if (fragment3 == null) {
    	        fragment3 = new Fragment();  
    	    }  
    	    getSupportFragmentManager().beginTransaction().replace(R.id.container, fragment3).commit();  
    	    break;  

    	default:  
    	    break;  
    	}  

    }  

    @Override  
    public void onTabUnselected(ActionBar.Tab tab,  
        FragmentTransaction fragmentTransaction) {  
    }  

    @Override  
    public void onTabReselected(ActionBar.Tab tab,  
        FragmentTransaction fragmentTransaction) {  
    }  

}

package com.example.actionbartabs;

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.TextView;

public class TabContentFragment extends Fragment{
	private String mText;
	public TabContentFragment(String text) {
		mText = text;
	}
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		View fragment = inflater.inflate(R.layout.action_bar_tab_content,container,false);
		TextView text = (TextView) fragment.findViewById(R.id.text);
		text.setText(mText);
		return fragment;
	}
	
	public String getText() {
		return mText;
	} 
}

activity_action_bar_tabs.xml:

<pre name="code" class="html"><FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"  
    xmlns:tools="http://schemas.android.com/tools"  
    android:id="@+id/container"  
    android:layout_width="match_parent"  
    android:layout_height="match_parent"  
    tools:context=".ActionBarTabs"  
    tools:ignore="MergeRootFrame" /> <span style="font-family: Arial, Helvetica, sans-serif;"> </span>
 

action_bar_tab_content.xml

<?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" >

    <FrameLayout
        android:id="@+id/fragment_content"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0dip"
        android:layout_weight="1"
        android:orientation="vertical" >

        <Button
            android:id="@+id/btn_add_tab"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:onClick="onAddTab"
            android:text="Add Tab" />

        <Button
            android:id="@+id/btn_remove_tab"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:onClick="onRemoveTab"
            android:text="Remove Tab" />

        <Button
            android:id="@+id/btn_toggle_tabs"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:onClick="onToggleTabs"
            android:text="Toggle Tabs" />

        <Button
            android:id="@+id/btn_remove_all_tabs"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:onClick="onRemoveAllTabs"
            android:text="Remove all tabs" />
    </LinearLayout>
</LinearLayout> 

另外一种方案是:

单独定义一个MyTabListener,实现ActionBar.TabListener,在它里面添加一个Fragment的对象,通过该fragment的OnCreateView生成布局。

实例如下:

public class ActionBarTabs extends Activity{
    private ActionBar actionBar;  
    @Override  
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);  
        setContentView(R.layout.activity_action_bar_tabs);  
        actionBar = getActionBar();  
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);// 导航模式必须设为NAVIGATION_MODE_Tabs  

        // For each of the sections in the app, add a tab to the action bar.  
        actionBar.addTab(actionBar.newTab().setText(R.string.title_section1)  
            .setTabListener(new MyTabListener(new TabContentFragment(getResources().getString(R.string.title_section1)))));  
        actionBar.addTab(actionBar.newTab().setText(R.string.title_section2)  
            .setTabListener(new MyTabListener(new TabContentFragment(getResources().getString(R.string.title_section2)))));  
        actionBar.addTab(actionBar.newTab().setText(R.string.title_section3)  
            .setTabListener(new MyTabListener(new TabContentFragment(getResources().getString(R.string.title_section3)))));
    }
    
    /*在TabListener中放置一个fragment,通过在该fragment中的onCreateView()生成相应的布局。
     * 注意:如果每个tab上要显示一个fragment,这种方案每个Tab下的fragment布局是一样的。
     */
    class MyTabListener implements ActionBar.TabListener {
    	private static final String TAG = "yxf";
		private TabContentFragment mFragment;
    	
    	public MyTabListener(TabContentFragment fragment) {  
    		mFragment = fragment;  
        }  
    	
    	@Override
    	public void onTabReselected(Tab tab, FragmentTransaction ft) {
    		// TODO Auto-generated method stub
    		Log.d(TAG,"onTabReselected");
    		
    	}

    	@Override
    	public void onTabSelected(Tab tab, FragmentTransaction ft) {
    		// TODO Auto-generated method stub
    		Log.d(TAG,"onTabSelected");
    	}

    	@Override
    	public void onTabUnselected(Tab tab, FragmentTransaction ft) {
    		// TODO Auto-generated method stub
    		Log.d(TAG,"onTabUnselected");
    		Toast.makeText(ActionBarTabs.this, "Reselected!", Toast.LENGTH_SHORT).show();
    	}
    }
}

4.显示搜索框

package com.example.actionbaractivity;

import android.os.Bundle;
import android.app.ActionBar;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.SearchView;
import android.widget.Toast;

public class MainActivity extends Activity {

	private SearchView mSearchView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d("yxf","onCreate");
        setContentView(R.layout.activity_main);
        ActionBar actionBar = this.getActionBar(); 
        actionBar.setDisplayHomeAsUpEnabled(true); 
        
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
    	Log.d("yxf","onCreateOptionsMenu");
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        mSearchView = (SearchView) menu.findItem(R.id.item1).getActionView();
        mSearchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
			
			@Override
			public boolean onQueryTextSubmit(String arg0) {
				// TODO Auto-generated method stub
				Log.d("yxf","onQueryTextSubmit, arg0 = " + arg0);
				return false;
			}
			
			@Override
			public boolean onQueryTextChange(String arg0) {
				// TODO Auto-generated method stub
				Log.d("yxf","onQueryTextSubmit, arg0 = " + arg0);
				return false;
			}
		});
        return true;
    }
}
res/menu/main.xml

<menu xmlns:android="http://schemas.android.com/apk/res/android" >

    <item 
        android:id="@+id/item1" 
        android:orderInCategory="1" 
        android:showAsAction="ifRoom"
        android:actionViewClass="android.widget.SearchView" 
        android:icon="@drawable/ic_launcher"
        android:title="search"/> 

</menu>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值