Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> Android分類列表菜單實現

Android分類列表菜單實現

編輯:關於Android編程

菜單功能是點擊按鈕彈出分類菜單

看看效果圖

\

先說一下實現原理,彈出菜單采用的是Fragment實現,很方便且高效,上面的三個按鈕是RadioButton。

新建一個項目FragmentMenu

主界面activity_main.xml

 



    

        
            android:gravity=center
            android:textSize=18sp />

        

        
            android:textSize=18sp />

        

        
            android:textSize=18sp />
    

    

    

    

布局文件我這裡說一下,RadioGroup裡面是RadioButton,使用這個主要是為了控制選中按鈕背景色,使用RadioGroup之後就不必在代碼中手動設置選中按鈕背景色。緊接著的一個空白的LinearLayout,它是個容器,後面的Fragment就是裝載這個裡面的。下面的是一個ListView,在這個例子中我沒有使用它。

 

selector_radio_back.xml

 



    
    

看一下MainActivity的主要代碼

 

 

/**
	 * 初始化控件
	 */
	private void init() {
		// TODO Auto-generated method stub
		group = (RadioGroup) findViewById(R.id.group);
		kindBtn = (RadioButton) findViewById(R.id.kind);
		kindBtn.setOnClickListener(this);
		distanceBtn = (RadioButton) findViewById(R.id.distance);
		distanceBtn.setOnClickListener(this);
		sortBtn = (RadioButton) findViewById(R.id.sort);
		sortBtn.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.kind:
			getSupportFragmentManager().beginTransaction()
					.replace(R.id.fragment_container, kindFragment).commit();
			fragment = kindFragment;
			break;
		case R.id.distance:
			getSupportFragmentManager().beginTransaction()
					.replace(R.id.fragment_container, distanceFragment)
					.commit();
			fragment = distanceFragment;
			break;
		case R.id.sort:
			getSupportFragmentManager().beginTransaction()
					.replace(R.id.fragment_container, sortFragment).commit();
			fragment = sortFragment;
			break;
		}
	}
在OnClick方法中把Fragment給加載出來,你在主界面所要做的幾乎就是這麼多,後面的菜單點擊事件就完全的交給各個Fragment來實現,這樣做各個Fragment之間結構泾渭分明,不易出錯,也易於以後的維護。

 

MainActivity全部代碼

 

package com.example.fragmentmenu;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

public class MainActivity extends FragmentActivity implements OnClickListener {
	private RadioGroup group;
	private RadioButton kindBtn, distanceBtn, sortBtn;
	private KindFragment kindFragment;
	private DistanceFragment distanceFragment;
	private SortFragment sortFragment;
	private Fragment fragment;

	/**
	 * 用於接收從Fragment中發送來的消息
	 */
	private Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			super.handleMessage(msg);
			switch (msg.what) {
			case 0:// 分類發來的消息
				Toast.makeText(MainActivity.this, msg.obj.toString(),
						Toast.LENGTH_SHORT).show();
				getSupportFragmentManager().beginTransaction().remove(fragment)
						.commit();
				fragment = null;
				group.clearCheck();
				break;
			case 1:// 范圍發來的消息
				Toast.makeText(MainActivity.this, msg.obj.toString(),
						Toast.LENGTH_SHORT).show();
				getSupportFragmentManager().beginTransaction().remove(fragment)
						.commit();
				fragment = null;
				group.clearCheck();
				break;
			case 2:// 排序發來的消息
				Toast.makeText(MainActivity.this, msg.obj.toString(),
						Toast.LENGTH_SHORT).show();
				getSupportFragmentManager().beginTransaction().remove(fragment)
						.commit();
				fragment = null;
				group.clearCheck();
				break;
			}
		}

	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		kindFragment = new KindFragment();
		kindFragment.setHandler(handler);
		distanceFragment = new DistanceFragment();
		distanceFragment.setHandler(handler);
		sortFragment = new SortFragment();
		sortFragment.setHandler(handler);
		init();
	}

	/**
	 * 初始化控件
	 */
	private void init() {
		// TODO Auto-generated method stub
		group = (RadioGroup) findViewById(R.id.group);
		kindBtn = (RadioButton) findViewById(R.id.kind);
		kindBtn.setOnClickListener(this);
		distanceBtn = (RadioButton) findViewById(R.id.distance);
		distanceBtn.setOnClickListener(this);
		sortBtn = (RadioButton) findViewById(R.id.sort);
		sortBtn.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.kind:
			getSupportFragmentManager().beginTransaction()
					.replace(R.id.fragment_container, kindFragment).commit();
			fragment = kindFragment;
			break;
		case R.id.distance:
			getSupportFragmentManager().beginTransaction()
					.replace(R.id.fragment_container, distanceFragment)
					.commit();
			fragment = distanceFragment;
			break;
		case R.id.sort:
			getSupportFragmentManager().beginTransaction()
					.replace(R.id.fragment_container, sortFragment).commit();
			fragment = sortFragment;
			break;
		}
	}

	/**
	 * 監控手機返回按鍵,如果此時Fragment存在就把它移除,不存在就直接關閉界面
	 */
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		if (keyCode == KeyEvent.KEYCODE_BACK
				&& event.getAction() == KeyEvent.ACTION_DOWN) {
			if (fragment != null) {
				getSupportFragmentManager().beginTransaction().remove(fragment)
						.commit();
				fragment = null;
				group.clearCheck();
			} else
				finish();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

}
關於Activity與Fragment的數據交互,有很多中實現方式,我這裡是使用了Handler來實現數據交互,在Fragment中處理完點擊事件之後會將處理結果發送到MainActivity以便於MainActivity繼續下面的操作(比如說給ListView賦值)。

 

看第一Fragment,也是這裡面最復雜的一個Fragment、新建一個Fragment名字叫KindFragment。

 

package com.example.fragmentmenu;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.os.Bundle;
import android.os.Handler;
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;

public class KindFragment extends Fragment implements OnItemClickListener {
	private ListView listView, detailListView;
	private List list = new ArrayList(),
			detaillist = new ArrayList();
	private KindAdapter listAdapter, detailAdapter;
	private Map map = new HashMap();

	//用於保存選中的列表索引值
	private int listSelect = -1, detailSelect = -1;

	private Handler handler;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		View view = inflater.inflate(R.layout.fragment_kind, null);
		initData();
		init(view);

		return view;
	}

	/**
	 * 初始化數據
	 */
	private void initData() {
		// TODO Auto-generated method stub
		map.put(快餐, R.array.kind_kuaichan);
		map.put(中餐, R.array.kind_zhongchan);
		map.put(西餐, R.array.kind_xichan);

		if (list != null && list.size() > 0)
			list.clear();
		for (Map.Entry entry : map.entrySet())
			list.add(entry.getKey().toString());
	}

	/**
	 * 初始化控件
	 * 
	 * @param view
	 */
	private void init(View view) {
		// TODO Auto-generated method stub
		listView = (ListView) view.findViewById(R.id.kind_list);
		listAdapter = new KindAdapter(getActivity());
		listAdapter.setList(list);
		listAdapter.setClickItem(listSelect);
		listView.setAdapter(listAdapter);
		listView.setOnItemClickListener(this);
		detailListView = (ListView) view.findViewById(R.id.kind_detil_list);
		detailAdapter = new KindAdapter(getActivity());
		detailAdapter.setList(detaillist);
		detailAdapter.setClickItem(detailSelect);
		detailListView.setAdapter(detailAdapter);
		detailListView.setOnItemClickListener(this);
	}

	/**
	 * 加載子列表數據
	 * 
	 * @param key
	 * @return
	 */
	private boolean addDetailList(String key) {
		if (detaillist != null && detaillist.size() > 0)
			detaillist.clear();
		String[] detailArray = getResources().getStringArray(map.get(key));
		if (detailArray.length <= 0)
			return false;
		for (String str : detailArray)
			detaillist.add(str);
		return true;
	}

	/**
	 * ListView點擊事件
	 */

	@Override
	public void onItemClick(AdapterView parent, View view, int position,
			long id) {
		// TODO Auto-generated method stub
		if (parent.getId() == R.id.kind_list) {
			listAdapter.setClickItem(position);
			listAdapter.notifyDataSetChanged();

			listSelect = position;
			detailSelect = -1;

			boolean hasDetail = addDetailList(list.get(position));
			detailAdapter.setClickItem(-1);
			detailAdapter.notifyDataSetChanged();
			if (!hasDetail)// 將點擊結果發送到主界面
				handler.obtainMessage(0, list.get(position)).sendToTarget();
		} else if (parent.getId() == R.id.kind_detil_list) {
			detailAdapter.setClickItem(position);
			detailAdapter.notifyDataSetChanged();
			detailSelect = position;
			//將點擊結果發送到主界面
			handler.obtainMessage(0, detaillist.get(position)).sendToTarget();

		}

	}

	public void setHandler(Handler handler) {
		this.handler = handler;
	}

}
這個Fragment在這個項目裡是最復雜的Fragment,這也只是相對來說,從上面的代碼看,它並不復雜,之所以說它最復雜是因為後面的兩個Fragment更簡單。相關代碼我都有注釋,需要特別提出的一點是在adapter中添加了一個方法用於設置選中列表項的顏色。

 

 

private int clickItem = -1;;

	public void setClickItem(int clickItem) {
		this.clickItem = clickItem;
	}
KindAdapter完整代碼

 

 

package com.example.fragmentmenu;

import java.util.List;

import android.content.Context;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

public class KindAdapter extends BaseAdapter {
	private List list;
	private LayoutInflater inflater;

	public KindAdapter(Context context) {
		inflater = (LayoutInflater) context
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
	}

	@Override
	public int getCount() {
		// TODO Auto-generated method stub
		return list == null ? 0 : list.size();
	}

	public List getList() {
		return list;
	}

	public void setList(List list) {
		this.list = list;
	}

	@Override
	public Object getItem(int position) {
		// TODO Auto-generated method stub
		return list == null ? null : list.get(position);
	}

	@Override
	public long getItemId(int position) {
		// TODO Auto-generated method stub
		return list == null ? -1 : position;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		// TODO Auto-generated method stub
		ViewHolder holder;
		if (convertView == null) {
			holder = new ViewHolder();
			convertView = inflater
					.inflate(R.layout.adapter_fragment_list, null);
			holder.text = (TextView) convertView
					.findViewById(R.id.adapter_kind_text);
			convertView.setTag(holder);
		} else
			holder = (ViewHolder) convertView.getTag();
		if (position != clickItem) {
			convertView.setBackgroundColor(Color.WHITE);
		} else {
			convertView.setBackgroundColor(Color.LTGRAY);
		}
		holder.text.setText(list.get(position));
		return convertView;
	}

	private int clickItem = -1;;

	public void setClickItem(int clickItem) {
		this.clickItem = clickItem;
	}

	class ViewHolder {
		TextView text;
	}
}
看一下布局文件

 

adapter_fragment_list.xml

 



    

    

 

KindFragment布局文件
fragment_kind.xml

 



    

    

很簡單,只有兩個ListView。

 

後面的兩個Fragment實現方式與之類似,我直接把代碼貼出來

DistanceFragment

 

package com.example.fragmentmenu;

import java.util.ArrayList;
import java.util.List;

import android.os.Bundle;
import android.os.Handler;
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;

public class DistanceFragment extends Fragment implements OnItemClickListener {
	private ListView listView;
	private KindAdapter listAdapter;
	private List list = new ArrayList();

	private int listSelect = -1;

	private Handler handler;

	public void setHandler(Handler handler) {
		this.handler = handler;
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		View view = inflater.inflate(R.layout.fragment_distance, null);
		initData();
		init(view);
		return view;
	}

	private void initData() {
		// TODO Auto-generated method stub
		if (list != null && list.size() > 0)
			list.clear();
		for (int i = 100; i < 105; i++)
			list.add(String.valueOf(i));
	}

	private void init(View view) {
		// TODO Auto-generated method stub
		listView = (ListView) view.findViewById(R.id.diatnce_list);
		listAdapter = new KindAdapter(getActivity());
		listAdapter.setList(list);
		listAdapter.setClickItem(listSelect);
		listView.setAdapter(listAdapter);
		listView.setOnItemClickListener(this);

	}

	@Override
	public void onItemClick(AdapterView parent, View view, int position,
			long id) {
		// TODO Auto-generated method stub
		listAdapter.setClickItem(position);
		listAdapter.notifyDataSetChanged();

		listSelect = position;
		handler.obtainMessage(1, list.get(position)).sendToTarget();
	}

}
fragment_distance.xml

 

 


SortFragment

 

 

package com.example.fragmentmenu;

import java.util.ArrayList;
import java.util.List;

import android.os.Bundle;
import android.os.Handler;
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;

public class SortFragment extends Fragment implements OnItemClickListener {
	private ListView listView;
	private KindAdapter listAdapter;
	private List list = new ArrayList();

	private int listSelect = -1;

	private Handler handler;

	public void setHandler(Handler handler) {
		this.handler = handler;
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		View view = inflater.inflate(R.layout.fragment_sort, null);
		initData();
		init(view);
		return view;
	}

	private void initData() {
		// TODO Auto-generated method stub
		if (list != null && list.size() > 0)
			list.clear();
		for (int i = 0; i < 5; i++)
			list.add(String.valueOf(i));
	}

	private void init(View view) {
		// TODO Auto-generated method stub
		listView = (ListView) view.findViewById(R.id.sort_list);
		listAdapter = new KindAdapter(getActivity());
		listAdapter.setList(list);
		listAdapter.setClickItem(listSelect);
		listView.setAdapter(listAdapter);
		listView.setOnItemClickListener(this);
	}

	@Override
	public void onItemClick(AdapterView parent, View view, int position,
			long id) {
		// TODO Auto-generated method stub
		listAdapter.setClickItem(position);
		listAdapter.notifyDataSetChanged();

		listSelect = position;
		handler.obtainMessage(2, list.get(position)).sendToTarget();
	}

}

fragment_sort.xml

 

 



相關資源colors.xml

 

 


 #d3d3d3 


 


corner_arrow.9.png
\

 





 

 

 

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved