今天就跟大家聊聊有关怎么在Android中利用FloatingActionButton实现一个悬浮按钮效果,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。
首先是这个最小的标记:
这个标签带文字,可以是一个TextView,但为了美观,我们使用CardView, CardView是一个FrameLayout,我们要让它具有显示文字的功能,就继承CardView自定义一个ViewGroup。
publicclass TagView延伸CardView
内部维护一个TextView,在其构造函数中我们实例化一个TextView用来显示文字,并在外部调用setTagText的时候把TextView添加到这个CardView中。
公共类TagView延伸CardView { 私人TextView mTextView; 公共TagView(上下文语境){ 这(上下文,null); } 公共TagView(上下文语境,AttributeSet attrs) { 这(上下文、attrs 0); } 公共TagView(上下文语境、AttributeSet attrs int defStyleAttr) { 超级(上下文、attrs defStyleAttr); mTextView=new TextView(上下文); mTextView.setSingleLine(真正的); } 保护无效setTextSize(浮动大小){ mTextView.setTextSize(大小); } 保护无效setTextColor (int颜色){ mTextView.setTextColor(颜色); }//给内部的TextView添加文字 保护无效setTagText(字符串文本){ mTextView.setText(文本); addTag (); }//添加进这个布局中 私人空间addTag () { LayoutParams LayoutParams=new LayoutParams (ViewGroup.LayoutParams.WRAP_CONTENT ,ViewGroup.LayoutParams。WRAP_CONTENT Gravity.CENTER); int l=dp2px (8); int t=dp2px (8); int r=dp2px (8); int b=dp2px (8); layoutParams。setMargins (l、t r、b);//addView会引起所有视图的布局 addView (mTextView layoutParams); } 私人int dp2px (int值){ 返回(int) TypedValue.applyDimension (TypedValue.COMPLEX_UNIT_DIP 、价值getresource () .getDisplayMetrics ()); } }
接下来我们看这个项,它是一个标签和一个工厂的组合:
标记使用刚才我们自定义的TagView,工厂就用系统的FloatingActionButton,这里显然需要一个ViewGroup来组合这两个子视图,可以使LinearLayout用,这里我们就直接使用ViewGroup。
公共类TagFabLayout延伸ViewGroup
我们为这个ViewGroup设置自定义属性,是为了给标签设置文本:
& lt; declare-styleable name=癋abTagLayout"祝辞 & lt; attr name=皌agText"格式=皊tring"/比; & lt;/declare-styleable>
在构造器中获取自定义属性,初始化TagView并添加到该ViewGroup中:
公共TagFabLayout(上下文语境、AttributeSet attrs int defStyleAttr) { 超级(上下文、attrs defStyleAttr); attrs getAttributes(上下文); settingTagView(上下文); } 私人空间getAttributes(上下文语境,AttributeSet AttributeSet) { TypedArray TypedArray=context.obtainStyledAttributes (attributeSet ,R.styleable.FabTagLayout); mTagText=typedArray.getString (R.styleable.FabTagLayout_tagText); typedArray.recycle (); } 私人空间settingTagView(上下文语境){ mTagView=new TagView(上下文); mTagView.setTagText (mTagText); addView (mTagView); }
在onMeasure对该ViewGroup进行测量,这里我直接把宽高设置成wrap_content的了,match_parent和精确值感觉没有必要.TagView和FloatingActionButton横向排列,中间和两边留一点空隙。
@Override 保护空白> @Override tagView保护空白>私人空白bindEvents(视图,视图fabView) { tagView。setOnClickListener(新alt="怎么在Android中利用FloatingActionButton实现一个悬浮按钮效果">思路也很清楚,蒙板是match_parent的,主工厂在右下角(当然我们可以自己设置,也可以对外提供接口来设置位置),三个项目(也就是TagFabLayout)在主工厂的上面。至于动画效果,在点击事件中触发。
公共类MultiFloatingActionButton延伸ViewGroup这里我们还需要自定义一些属性,比如蒙板的颜色,主工厂的颜色,主工厂的图案(当然,你把主工厂直接写在xml中就可以直接定义这些属性),动画的duaration,动画的模式等。
怎么在Android中利用FloatingActionButton实现一个悬浮按钮效果