Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> Android漸變標題欄的實現

Android漸變標題欄的實現

編輯:關於Android編程

Android4.4以上推出了Toolbar,改變程序的style屬性就可以給手機的標題欄填充顏色,可以是你設置好的系統的主題色,也可以是自己填充的顏色,其實這個效果在iOS早就有了,但在Android中還是很少見的。在iOS中,最常見的Navigationbar的效果就是一個轉場動畫(多出現於兩個界面切換的時候),一個就是隨著手勢滑動背景漸變(多出現於詳情頁)。今天我們就來實現下大多出現於詳情頁的這個漸變效果的標題欄。

 

接下來我們就來實現這個效果。

首先,我們要先把手機上面的狀態欄的顏色背景隱藏掉,在這裡會有一個坑,在小米和魅族手機裡,好想說是MIUI6以上,上面狀態欄上的時間啊什麼的文字默認的顏色是白色,如果你的Toolbar的背景是相對深顏色的話,是沒有問題的,但是如果你的Toolbar是相對淺的背景顏色,那麼很可能這些時間文字會顯示不出來,那麼就要修改上面狀態欄的顏色了。

先在style裡設置,這是我的style.xml:

 





接下來我們就要把狀態欄設置為透明:

 

 

private void setTranslucentWindows(Activity activity) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            //透明狀態欄
            activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        }
    }

以下是我寫的標題欄的布局文件:

 

 




    

        

            

                

                    

                

                

            

        

    


將標題欄的布局文件引入到我們界面的布局文件裡,我們是相當於在recyclerView的header上疊加了一層透明的標題欄,這裡對recyclerView的adapter的所有操作我都集成了一個通用格式來進行操作,方便很多。我給recyclerView添加了一個header,在這裡為了簡便,用imageView來代替了輪播圖。為了達到漸變的效果,我們要去監聽滑動事件,是否滑動到imageView的高度,也就是把imageView隱藏,當正好隱藏的時候標題欄的文字將出現(這個一般看交互,如果大圖下面有標題,一般建議標題覆蓋以後,標題欄上的標題再顯示),當前的y與整體要滑動距離的百分比來控制標題欄的背景透明度。在這裡要注意,當onCreate方法的時候,一個view的getMeasuredHeight()方法或者寬度的方法獲得的都是0,因為這個時候你的view還沒有draw上去,只有當onCreate方法執行完了以後,控件才會被onMeasure。所以有兩種策略,一種是我以下代碼實現的,等view的onMeasure好了以後再去調用方法,還有一種是去注冊一個ViewTreeObserver的監聽回調,具體大家可以去自行百度。ok,下面貼上Activity裡的代碼:

 

 

public class MainActivity extends AppCompatActivity {

    @Bind(R.id.recycler)
    RecyclerView recyclerView;
    @Bind(R.id.layout_toolbar_my_container)
    RelativeLayout layoutToolBarBackground;
    @Bind(R.id.text_toolbar_index)
    TextView centerText;

    private ArrayList modelList = new ArrayList<>();
    private MyRecyclerAdapter adapter;
    private LinearLayoutManager layoutManager;
    private int itemIndex;
    private ToolBarBackgroundController toolBarBackgroundController;
    private int anchorHeight;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        setTranslucentWindows(this);
        ButterKnife.bind(this);
        layoutManager = new LinearLayoutManager(this.getApplicationContext());
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL_LIST,
                R.drawable.devide_line_gray, 0));
        initHead();
        initData();
        initView();
    }

    private void initHead() {
        layoutToolBarBackground.setBackgroundColor(Color.TRANSPARENT);
        toolBarBackgroundController = new ToolBarBackgroundController(layoutToolBarBackground);
    }

    public class ToolBarBackgroundController {

        private View layoutToolbar;

        public ToolBarBackgroundController(View layoutToolbar) {
            this.layoutToolbar = layoutToolbar;
            layoutToolbar.setBackgroundColor(Color.TRANSPARENT);
        }

        public void setTransparent(boolean needTransparent) {
            if (needTransparent) {
                //變透明
                centerText.setVisibility(View.GONE);
            } else {
                layoutToolbar.setBackgroundColor(getResources().getColor(R.color.base));
                centerText.setVisibility(View.VISIBLE);
            }
        }
    }

    private void setTranslucentWindows(Activity activity) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            //透明狀態欄
            activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        }
    }

    private int getStatusBarHeight(Context context) {
        int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            return context.getResources().getDimensionPixelSize(resourceId);
        } else return 0;
    }

    private void initData() {
        for (int i = 0; i < 20; i++) {
            Model model = new Model();
            model.setName("jjq" + i);
            model.setDesc("哈哈哈哈哈哈哈哈");
            modelList.add(model);
        }
    }

    private void initView() {
        if (adapter == null) {
            adapter = new MyRecyclerAdapter();
        } else {
            adapter.notifyDataSetChanged();
        }
        adapter.initData(false);
        adapter.appendData(modelList);
        recyclerView.setAdapter(adapter);
        recyclerView.addOnScrollListener(new OnScrollColorChangeListener());
    }

    private class OnScrollColorChangeListener extends RecyclerView.OnScrollListener {

        private boolean isTrans = true;
        private int y = 0;

        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);
            if (anchorHeight != 0) {
                y += dy;
                boolean needTrans = y <= anchorHeight;
                if (needTrans != isTrans) {
                    isTrans = needTrans;
                    toolBarBackgroundController.setTransparent(needTrans);
                } else {
                    if (y / anchorHeight < 1) {
                        layoutToolBarBackground.setBackgroundColor(getResources().getColor(R.color.base));
                        layoutToolBarBackground.getBackground().setAlpha((int) ((float) y / anchorHeight * 255));
                    }
                }
            }
        }
    }

    private class MyRecyclerAdapter extends RecyclerView.Adapter {
        private final int TYPE_HEADER = 0x1000;
        private final int TYPE_NORMAL = 0x2000;
        private final int TYPE_FOOTER = 0x3000;
        private final int TYPE_EMPTY = 0x4000;
        private final int TYPE_THEME = 0x5000;
        private ArrayList itemInfos;
        private boolean needFooter = false;
        private boolean hasFooter = false;

        public class MyItemInfo {
            int type;
            Model model;

            public MyItemInfo(int type, Model model) {
                this.type = type;
                this.model = model;
            }
        }

        public MyRecyclerAdapter() {
            itemInfos = new ArrayList<>();
        }

        public void initData(boolean needFooter) {
            this.needFooter = needFooter;
            this.hasFooter = false;
            int oldCount = itemInfos.size();
            itemInfos.clear();
            this.notifyItemRangeRemoved(0, oldCount);
            itemInfos.add(new MyItemInfo(TYPE_HEADER, null));
            //itemInfos.add(new MyItemInfo(TYPE_FOOTER, null));
            //this.notifyItemRangeInserted(0, 2);
        }

        public void appendData(ArrayList models) {
            int oldCount = itemInfos.size();
            if (hasFooter) {
                itemInfos.remove(oldCount - 1);
                this.notifyItemRemoved(oldCount - 1);
                oldCount--;
            }
            int size = models.size();
            for (int i = 0; i < size; i++) {
                itemInfos.add(new MyItemInfo(TYPE_NORMAL, models.get(i)));
            }

            this.notifyItemRangeInserted(oldCount + 1, size);
            if (needFooter) {
                itemInfos.add(new MyItemInfo(TYPE_FOOTER, null));
                this.notifyItemInserted(itemInfos.size() - 1);
                hasFooter = true;
            }
        }

        public void removeFooter() {
            int oldCount = itemInfos.size();
            itemInfos.remove(oldCount - 1);
            notifyItemRemoved(oldCount - 1);
        }

        public void appendEmptyView() {
            int oldCount = itemInfos.size();
            if (hasFooter) {
                itemInfos.remove(oldCount - 1);
                this.notifyItemRemoved(oldCount - 1);
                oldCount--;
            }
            itemInfos.add(new MyItemInfo(TYPE_EMPTY, null));
            notifyItemRangeInserted(oldCount, 1);
        }

        @Override
        public int getItemViewType(int position) {
            return itemInfos.get(position).type;
        }

        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            LayoutInflater inflater = LayoutInflater.from(parent.getContext());
            View view = null;
            switch (viewType) {
                case TYPE_HEADER:
                    view = inflater.inflate(R.layout.layout_main_recycler_head, parent, false);
                    return new MyHeaderItemHolder(view, MainActivity.this);
                case TYPE_NORMAL:
                    view = inflater.inflate(R.layout.layout_list_item, parent, false);
                    return new NormalViewHolder(view);
                case TYPE_EMPTY:
                    return null;
                case TYPE_FOOTER:
                    return null;
                default:
                    return null;
            }
        }

        @Override
        public void onBindViewHolder(RecyclerView.ViewHolder viewHolder, int i) {
            switch (viewHolder.getItemViewType()) {
                case TYPE_NORMAL:
                    NormalViewHolder normalViewHolder = (NormalViewHolder) viewHolder;
                    normalViewHolder.setContent(itemInfos.get(i).model, i);
                    break;
                case TYPE_HEADER:
                    MyHeaderItemHolder headerViewHolder = (MyHeaderItemHolder) viewHolder;
                    headerViewHolder.setContent();
                    break;
                case TYPE_FOOTER:
                case TYPE_EMPTY:
                    break;
                default:
                    break;
            }
        }

        @Override
        public int getItemCount() {
            return itemInfos.size();
        }

        private class EmptyItemHolder extends RecyclerView.ViewHolder {
            public EmptyItemHolder(View itemView) {
                super(itemView);
            }
        }

        private class MyHeaderItemHolder extends RecyclerView.ViewHolder {
            private Context context;
            private ImageView imageView;

            public MyHeaderItemHolder(View itemView, Context context) {
                super(itemView);
                this.context = context;
                imageView = (ImageView) itemView.findViewById(R.id.img_main_recycler_head_banner);
                imageView.post(new Runnable() {
                    @Override
                    public void run() {
                        anchorHeight = imageView.getMeasuredHeight() - layoutToolBarBackground.getMeasuredHeight();
                    }
                });
            }

            //填充頭部內容
            public void setContent() {

            }
        }

        private class NormalViewHolder extends RecyclerView.ViewHolder {
            private Model model;
            private TextView nameView;
            private TextView descView;

            public NormalViewHolder(View itemView) {
                super(itemView);
                nameView = (TextView) itemView.findViewById(R.id.text_list_item_name);
                descView = (TextView) itemView.findViewById(R.id.text_list_item_desc);
                itemView.setOnClickListener(new OnItemClickListener());
            }

            public void setContent(Model model, int index) {
                this.model = model;
                nameView.setText(model.getName());
                descView.setText(model.getDesc());
                itemIndex = index;

            }

            private class OnItemClickListener implements View.OnClickListener {
                @Override
                public void onClick(View v) {

                }
            }
        }

        private class FooterViewHolder extends RecyclerView.ViewHolder {

            public FooterViewHolder(View itemView) {
                super(itemView);
            }
        }
    }

}

ok,到這裡demo就搞定了!當然如果你的標題欄上的文字太長的話,你也可以自己給textView加上跑馬燈效果,很簡單,不知道的人可以自行去谷歌百度,記得給textView加上焦點就可以了。

項目地址:點擊打開鏈接

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