Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

手寫菜單收起展開動畫:從 ExpandableListView 到自定義 Layout

編輯:關於 Android 程式設計

最近需求方聯合設計又對界面動了手腳,整體是華麗了不少,只是苦了我這個搬磚的。先看看新界面:

很經典的菜單設計。由於是版本更迭,不宜在原基礎上大改,菜單共分 4 個父菜單與若干子菜單,點擊父菜單要能收起子菜單,而且還得帶上展開收起的動畫。這讓我第一時間想到了 ExpandableListView,於是我先花幾分鐘寫個 demo 試試水。

先用 ExpandableListView 試水

布局代碼很簡單,這裡略過。接著定義一個實體類,裝下父子菜單必需的內容:

public class Bean {
    public Bean(String title, List childBeans) {
        this.title = title;
        this.childBeans = childBeans;
    }
    public Bean() {
    }
    public String getTitle() {
        return title;
    }
    public void setTitle(String title) {
        this.title = title;
    }
    public List getChildBeans() {
        return childBeans;
    }
    public void setChildBeans(List childBeans) {
        this.childBeans = childBeans;
    }
    private String title;
    private List childBeans;
    public static class childBean {
        private String title;
        public childBean(String title) {
            this.title = title;
        }
        public String getTitle() {
            return title;
        }
        public void setTitle(String title) {
            this.title = title;
        }
    }
}

這幾行一目了然,需要別的字段自己加即可。最後寫個自定義 adapter:

public class TestAdapter extends BaseExpandableListAdapter {
    private List groups;
    private Context context;
    public TestAdapter(Context context, List groups) {
        this.context = context;
        this.groups = groups;
    }
    @Override
    public int getGroupCount() {
        return groups.size();
    }
    @Override
    public int getChildrenCount(int groupPosition) {
        return groups.get(groupPosition).getChildBeans().size();
    }
    @Override
    public Object getGroup(int groupPosition) {
        return groups.get(groupPosition);
    }
    @Override
    public Object getChild(int groupPosition, int childPosition) {
        return groups.get(groupPosition).getChildBeans().get(childPosition);
    }
    @Override
    public long getGroupId(int groupPosition) {
        return groupPosition;
    }
    @Override
    public long getChildId(int groupPosition, int childPosition) {
        return childPosition;
    }
    @Override
    public boolean hasStableIds() {
        return false;
    }
    @Override
    public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
        View view = LayoutInflater.from(context).inflate(R.layout.item_a, null);
        TextView tv = (TextView) view.findViewById(R.id.a_text);
        tv.setText(groups.get(groupPosition).getTitle());
        return view;
    }
    @Override
    public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
        View view = LayoutInflater.from(context).inflate(R.layout.item_a, null);
        TextView tv = (TextView) view.findViewById(R.id.a_text);
        tv.setText(groups.get(groupPosition).getChildBeans().get(childPosition).getTitle());
        return view;
    }
    @Override
    public boolean isChildSelectable(int groupPosition, int childPosition) {
        return false;
    }
}

代碼很樸素,畢竟只是 demo。在 Activity 裡調用一下看看效果:

public class MainActivity extends AppCompatActivity {
    private ExpandableListView listView;
    private List mList = new ArrayList<>();
    private List childList = new ArrayList<>();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        listView = (ExpandableListView) findViewById(R.id.exlistview);
        Bean.childBean childBean;
        for (int j = 0; j < 3; j++) {
            childBean = new Bean.childBean("aaaa" + j);
            childList.add(childBean);
        }
        for (int i = 0; i < 3; i++) {
            mList.add(new Bean(i + "", childList));
        }
        TestAdapter adapter = new TestAdapter(MainActivity.this, mList);
        listView.setAdapter(adapter);
        listView.setGroupIndicator(null);
    }
}

效果太粗糙,而且沒有收起展開的動畫。無奈繼續搜索,找到一個叫 animationExpanedListView 的庫,不過它已經兩年沒更新了,想嘗試的朋友可以去這裡看看:https://github.com/idunnololz/AnimatedExpandableListView。

自己動手:自定義 SettingView

看來只能靠自己了。先理清楚思路:模仿 ListView 的效果來做,於是寫一個自定義 adapter:

public abstract class SettingsAdapter {
    private Context context;
    private List mList;
    public SettingsAdapter(Context context, List mList) {
        this.context = context;
        this.mList = mList;
    }
    public SettingsAdapter(T[] mDatas) {
        mList = new ArrayList(Arrays.asList(mDatas));
    }
    public int getCount() {
        return mList == null ? 0 : mList.size();
    }
    public T getItem(int position) {
        return mList.get(position);
    }
    public void notifyDataSetChanged() {
        onDataChanged.changed();
    }
    public abstract View getView(SettingView parent, int position);
    public interface onDataChanged {
        void changed();
    }
    public void setOnDataChanged(onDataChanged onDataChanged) {
        this.onDataChanged = onDataChanged;
    }
    public onDataChanged onDataChanged;
}

這段跟普通 adapter 沒什麼兩樣。接著實現子菜單的布局,由於菜單是自上而下排列的,我們選擇繼承 LinearLayout:

public class SettingView extends LinearLayout implements SettingsAdapter.onDataChanged {
    private Context context;
    private SettingsAdapter adapter;
    public SettingView(Context context) {
        this(context, null);
    }
    public SettingView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }
    public SettingView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        this.context = context;
        setOrientation(VERTICAL);
    }
    public void setAdapter(SettingsAdapter adapter) {
        this.adapter = adapter;
        changeAdapter();
    }
    private void changeAdapter() {
        removeAllViews();
        SettingsAdapter settingsAdapter = this.adapter;
        // 遍歷綁定每一個子項 View
    }
    public interface OnItemClick {
        void click(View v, int i);
    }
    public void setOnItemClick(OnItemClick onItemClick) {
        this.onItemClick = onItemClick;
    }
    private OnItemClick onItemClick;
    @Override
    public void changed() {
        changeAdapter();
    }
}

在 Activity 裡這樣用,第一步的自定義布局就實現了:

tv = (TextView) findViewById(R.id.tv1);
sv = (SettingView) findViewById(R.id.test_layout);
for (int i = 0; i < 5; i++) {
    mList.add(i + "");
}
SettingsAdapter adapter = new SettingsAdapter(MainActivity.this, mList) {
    @Override
    public View getView(SettingView parent, int position) {
        View view = getLayoutInflater().inflate(R.layout.item_a, null);
        TextView tv = (TextView) view.findViewById(R.id.a_text);
        tv.setText(mList.get(position));
        return view;
    }
};
sv.setAdapter(adapter);
sv.setOnItemClick(new SettingView.OnItemClick() {
    @Override
    public void click(View v, int i) {
        Toast.makeText(MainActivity.this, mList.get(i), Toast.LENGTH_SHORT).show();
    }
});

加入屬性動畫

布局有了,但還沒有任何點擊與動畫效果。這時候想到了屬性動畫。ObjectAnimator 裡沒有直接針對 View 高度的動畫,好在 ValueAnimator 可以勝任。先看代碼:

public static ValueAnimator DropAnim(final View view, int start, int end) {
    ValueAnimator animator = ValueAnimator.ofInt(start, end);
    animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
        @Override
        public void onAnimationUpdate(ValueAnimator animation) {
            int value = (Integer) animation.getAnimatedValue();
            ViewGroup.LayoutParams lp = view.getLayoutParams();
            lp.height = value;
            view.setLayoutParams(lp);
        }
    });
    return animator;
}

把目標 view 和起始、結束高度傳進來,再透過監聽器動態改變 view 高度即可。開合兩個方法如下:

public static void animatorOpen(final View view, int height) {
    view.setVisibility(View.VISIBLE);
    AnimatorSet set = new AnimatorSet();
    set.setDuration(1000);
    ValueAnimator animator = DropAnim(view, 0, height);
    ObjectAnimator oa = ObjectAnimator.ofFloat(view, View.ALPHA, 0.0f, 1.0f);
    set.playTogether(animator, oa);
    set.setDuration(1000);
    set.start();
}
public static void animatorClose(final View view, int height) {
    AnimatorSet set = new AnimatorSet();
    set.setDuration(1000);
    ValueAnimator animator = DropAnim(view, height, 0);
    ObjectAnimator oa = ObjectAnimator.ofFloat(view, View.ALPHA, 1.0f, 0.0f);
    set.addListener(new AnimatorListenerAdapter() {
        @Override
        public void onAnimationEnd(Animator animation) {
            super.onAnimationEnd(animation);
            view.setVisibility(View.GONE);
        }
    });
    set.start();
}

兩個方法思路一致,我們不僅實現了高度變化,還疊加了透明度漸變,你當然也能加入更多動畫。最後在點擊事件中,透過判斷子菜單的可見性來決定開合:

sv.post(new Runnable() {
    @Override
    public void run() {
        height = sv.getHeight();
    }
});
tv.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        if (sv.getVisibility() == View.VISIBLE) {
            AnimUtils.animatorClose(sv, height);
        } else {
            AnimUtils.animatorOpen(sv, height);
        }
    }
});

是不是挺炫的?最後留一個小坑:如何在 Fragment 裡獲取控件高度?起初我也傻傻地用 post 方法,結果並不奏效。最終找到答案——用 ViewTreeObserver 來獲取,並在點擊或初始化完成後記得移除監聽,否則它會一直掛在那裡。切記:移除監聽這步必須放在動畫之前,不然會有意想不到的「驚喜」。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved