Android 사용자 정의 Menu(TabMenu)구현 방법

13648 단어 AndroidMenu
일반적으로 UCWEB-Android 버 전 을 사용 한 사람 은 특별한 menu 에 대해 어느 정도 인상 을 가 져 야 한다.menu 를 Tab-menu(페이지 를 나 누 는 Menu 지원)로 만 들 면 Android 의 전통 적 인 menu 보다 풍부 한 내용 을 수용 할 수 있다(Android 의 menu 가 6 개 를 넘 으 면[더 많은]리 로 요약 한다).본 고 는 인터넷 의 예 를 바탕 으로 예 를 간소화 하고 봉인 한다.복합 컨트롤 로 자신의 프레임 워 크 에 융합 시 킵 니 다.
먼저 본 프로그램의 운행 효 과 를 살 펴 보 겠 습 니 다.다음 그림 과 같 습 니 다.

TabMenu 자체 가 PopupWindow 이 고 PopupWindow 위 에 GridView 두 개가 놓 여 있 습 니 다.첫 번 째 GridView 는 페이지 라벨 입 니 다.PopupWindow 의 상단 에 있 고 두 번 째 GridView 는 메뉴 이 며 PopupWindow 의 주체 에 있 습 니 다.PopupWindow 의 팝 업/종료 애니메이션 효 과 를 실현 하기 위해 다음 과 같은 코드 를 사 용 했 습 니 다.
프로젝트 의 res 폴 더 에 anim 하위 디 렉 터 리 를 추가 하고 새 파일 popupenter.xml:

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
 <translate android:fromYDelta="100%p" android:toYDelta="0" android:duration="1000" />
 <alpha android:fromAlpha="0.0" android:toAlpha="1.0" android:duration="1000" />
</set> 

새 파일 popupexit.xml:

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
 <translate android:fromYDelta="0" android:toYDelta="100%p" android:duration="1000" />
 <alpha android:fromAlpha="1.0" android:toAlpha="0.0" android:duration="1000" />
</set> 

프로젝트 의 values 폴 더 에 새 파일 popupanimation.xml:

<?xml version="1.0" encoding="utf-8"?> 
<resources>   
  <style name="PopupAnimation" parent="android:Animation">
    <item name="android:windowEnterAnimation">@anim/popup_enter</item> 
    <item name="android:windowExitAnimation">@anim/popup_exit</item>  
  </style> 
</resources> 

main.xml 의 원본 코드 는 다음 과 같 습 니 다.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout android:id="@+id/LinearLayout01"
 android:layout_width="fill_parent" android:layout_height="fill_parent"
 xmlns:android="http://schemas.android.com/apk/res/android">
 <TextView android:id="@+id/TextView01" android:layout_height="wrap_content"
 android:layout_width="fill_parent" android:text="  Menu----hellogv"></TextView>
</LinearLayout>

TabMenu 의 패키지 클래스 TabMenu.java 의 원본 코드 는 다음 과 같 습 니 다.

package com.testTabMenu;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout.LayoutParams;
public class TabMenu extends PopupWindow{
 private GridView gvBody, gvTitle;
 private LinearLayout mLayout;
 private MenuTitleAdapter titleAdapter;
 public TabMenu(Context context,OnItemClickListener titleClick,OnItemClickListener bodyClick,
 MenuTitleAdapter titleAdapter,int colorBgTabMenu,int aniTabMenu){
 super(context);
 mLayout = new LinearLayout(context);
 mLayout.setOrientation(LinearLayout.VERTICAL);
 //     
 gvTitle = new GridView(context);
 gvTitle.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
 gvTitle.setNumColumns(titleAdapter.getCount());
 gvTitle.setStretchMode(GridView.STRETCH_COLUMN_WIDTH);
 gvTitle.setVerticalSpacing(1);
 gvTitle.setHorizontalSpacing(1);
 gvTitle.setGravity(Gravity.CENTER);
 gvTitle.setOnItemClickListener(titleClick);
 gvTitle.setAdapter(titleAdapter);
 gvTitle.setSelector(new ColorDrawable(Color.TRANSPARENT));//         
 this.titleAdapter=titleAdapter;
 //    
 gvBody = new GridView(context);
 gvBody.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT));
 gvBody.setSelector(new ColorDrawable(Color.TRANSPARENT));//         
 gvBody.setNumColumns(4);
 gvBody.setStretchMode(GridView.STRETCH_COLUMN_WIDTH);
 gvBody.setVerticalSpacing(10);
 gvBody.setHorizontalSpacing(10);
 gvBody.setPadding(10, 10, 10, 10);
 gvBody.setGravity(Gravity.CENTER);
 gvBody.setOnItemClickListener(bodyClick);
 mLayout.addView(gvTitle);
 mLayout.addView(gvBody);
 //     
 this.setContentView(mLayout);
 this.setWidth(LayoutParams.FILL_PARENT);
 this.setHeight(LayoutParams.WRAP_CONTENT);
 this.setBackgroundDrawable(new ColorDrawable(colorBgTabMenu));//   TabMenu    
 this.setAnimationStyle(aniTabMenu);
 this.setFocusable(true);// menu               menu            
 }
 public void SetTitleSelect(int index)
 {
 gvTitle.setSelection(index);
 this.titleAdapter.SetFocus(index);
 }
 public void SetBodySelect(int index,int colorSelBody)
 {
 int count=gvBody.getChildCount();
 for(int i=0;i<count;i++)
 {
  if(i!=index)
  ((LinearLayout)gvBody.getChildAt(i)).setBackgroundColor(Color.TRANSPARENT);
 }
 ((LinearLayout)gvBody.getChildAt(index)).setBackgroundColor(colorSelBody);
 }
 public void SetBodyAdapter(MenuBodyAdapter bodyAdapter)
 {
 gvBody.setAdapter(bodyAdapter);
 }
 /**
 *    Adapter,TabMenu        
 * 
 */
 static public class MenuBodyAdapter extends BaseAdapter {
 private Context mContext;
 private int fontColor,fontSize;
 private String[] texts;
 private int[] resID;
 /**
  *   TabMenu     
  * @param context        
  * @param texts           
  * @param resID            
  * @param fontSize       
  * @param color       
  */
 public MenuBodyAdapter(Context context, String[] texts,int[] resID, int fontSize,int fontColor) 
 {
  this.mContext = context;
  this.fontColor = fontColor;
  this.texts = texts;
  this.fontSize=fontSize;
  this.resID=resID;
 }
 public int getCount() {
  return texts.length;
 }
 public Object getItem(int position) {
  
  return makeMenyBody(position);
 }
 public long getItemId(int position) {
  return position;
 }
 private LinearLayout makeMenyBody(int position)
 {
  LinearLayout result=new LinearLayout(this.mContext);
  result.setOrientation(LinearLayout.VERTICAL);
  result.setGravity(Gravity.CENTER_HORIZONTAL|Gravity.CENTER_VERTICAL); 
  result.setPadding(10, 10, 10, 10);
  
  TextView text = new TextView(this.mContext);
  text.setText(texts[position]);
  text.setTextSize(fontSize);
  text.setTextColor(fontColor);
  text.setGravity(Gravity.CENTER);
  text.setPadding(5, 5, 5, 5);
  ImageView img=new ImageView(this.mContext);
  img.setBackgroundResource(resID[position]);
  result.addView(img,new LinearLayout.LayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT)));
  result.addView(text);
  return result;
 }
 public View getView(int position, View convertView, ViewGroup parent) {
  return makeMenyBody(position);
 }
 }
 /**
 *    Adapter,TabMenu       
 * 
 */
 static public class MenuTitleAdapter extends BaseAdapter {
 private Context mContext;
    private int fontColor,unselcolor,selcolor;
    private TextView[] title;
    /**
     *   TabMenu title
     * @param context        
     * @param titles           
     * @param fontSize     
     * @param fontcolor     
     * @param unselcolor         
     * @param selcolor        
     */
    public MenuTitleAdapter(Context context, String[] titles, int fontSize,
        int fontcolor,int unselcolor,int selcolor) {
      this.mContext = context;
      this.fontColor = fontcolor;
      this.unselcolor = unselcolor;
      this.selcolor=selcolor;
      this.title = new TextView[titles.length];
      for (int i = 0; i < titles.length; i++) {
        title[i] = new TextView(mContext);
        title[i].setText(titles[i]);
        title[i].setTextSize(fontSize);
        title[i].setTextColor(fontColor);
        title[i].setGravity(Gravity.CENTER);
        title[i].setPadding(10, 10, 10, 10);
      }
    }
    public int getCount() {
      return title.length;
    }
    public Object getItem(int position) {
      return title[position];
    }
    public long getItemId(int position) {
      return title[position].getId();
    }
    /**
     *        
     */
    private void SetFocus(int index)
    {
     for(int i=0;i<title.length;i++)
     {
     if(i!=index)
     {
      title[i].setBackgroundDrawable(new ColorDrawable(unselcolor));//        
          title[i].setTextColor(fontColor);//           
     }
     }
     title[index].setBackgroundColor(0x00);//        
      title[index].setTextColor(selcolor);//          
    }
    public View getView(int position, View convertView, ViewGroup parent) {
      View v;
      if (convertView == null) {
        v = title[position];
      } else {
        v = convertView;
      }
      return v;
    }
 }
}

testTabMenu 는 데이터 의 정의 와 TabMenu 의 사용 을 소 개 했 습 니 다.소스 코드 는 다음 과 같 습 니 다.

package com.testTabMenu;
import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.view.Gravity;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Toast;
public class testTabMenu extends Activity {
 TabMenu.MenuBodyAdapter []bodyAdapter=new TabMenu.MenuBodyAdapter[3];
 TabMenu.MenuTitleAdapter titleAdapter;
 TabMenu tabMenu;
 int selTitle=0;
 @Override
 public void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.main);
 //        
 titleAdapter = new TabMenu.MenuTitleAdapter(this, new String[] { "  ",
  "  ", "  " }, 16, 0xFF222222,Color.LTGRAY,Color.WHITE);
 //          
 bodyAdapter[0]=new TabMenu.MenuBodyAdapter(this,new String[] { "  1", "  2", }, 
   new int[] { R.drawable.menu_test,
  R.drawable.menu_bookmark},13, 0xFFFFFFFF);
 bodyAdapter[1]=new TabMenu.MenuBodyAdapter(this,new String[] { "  1", "  2",
   "  3"}, new int[] { R.drawable.menu_edit,
   R.drawable.menu_delete, R.drawable.menu_fullscreen},13, 0xFFFFFFFF);
 bodyAdapter[2]=new TabMenu.MenuBodyAdapter(this,new String[] { "  1", "  2",
   "  3", "  4" }, new int[] { R.drawable.menu_copy,
   R.drawable.menu_cut, R.drawable.menu_normalmode,
   R.drawable.menu_quit },13, 0xFFFFFFFF);
 tabMenu=new TabMenu(this,
   new TitleClickEvent(),
   new BodyClickEvent(),
   titleAdapter,
   0x55123456,//TabMenu     
   R.style.PopupAnimation);//        
  tabMenu.update();
  tabMenu.SetTitleSelect(0);
  tabMenu.SetBodyAdapter(bodyAdapter[0]);
 }
 class TitleClickEvent implements OnItemClickListener{
 @Override
 public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
  long arg3) {
  selTitle=arg2;
  tabMenu.SetTitleSelect(arg2);
  tabMenu.SetBodyAdapter(bodyAdapter[arg2]);
 }
 }
 class BodyClickEvent implements OnItemClickListener{
 @Override
 public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
  long arg3) {
  tabMenu.SetBodySelect(arg2,Color.GRAY);
  String str=" "+String.valueOf(selTitle)+" /n/r"
  +" "+String.valueOf(arg2)+" ";
  Toast.makeText(testTabMenu.this, str, 500).show();
 }
 }
 @Override
 /**
 *   MENU
 */
 public boolean onCreateOptionsMenu(Menu menu) {
 menu.add("menu");//       
 return super.onCreateOptionsMenu(menu);
 }
 @Override
 /**
 *   MENU
 */
 public boolean onMenuOpened(int featureId, Menu menu) {
 if (tabMenu != null) {
  if (tabMenu.isShowing())
  tabMenu.dismiss();
  else {
  tabMenu.showAtLocation(findViewById(R.id.LinearLayout01),
   Gravity.BOTTOM, 0, 0);
  }
 }
 return false;//    true      menu
 }
}
관심 이 있 는 독 자 는 본 논문 에서 말 한 사례 를 직접 테스트 하여 여러분 의 안 드 로 이 드 프로그램 개발 에 어느 정도 도움 이 될 것 이 라 고 믿 습 니 다.

좋은 웹페이지 즐겨찾기