How to put view into ViewGroup in code (combined control)
Need: To create a similar Baidu post-refresh button, but do not want to use XML to layout.
Requirement: Create a view class to inherit Relativelayout and then populate the ImageView in Relativelayout
So how to put ImageView into Relativelayout from Java code.
Public classRefreshviewextendsRelativelayoutImplementsview.onclicklistener{PrivateImageView Mivrefresh; PrivateContext Mcontext; PublicRefreshview (Context context) {Super(context); Initview (context); } PublicRefreshview (Context context, AttributeSet attrs) {Super(context, attrs); Initview (context); } PublicRefreshview (context context, AttributeSet attrs,intdefstyleattr) { Super(context, attrs, defstyleattr); Initview (context); } Private voidInitview (Context context) {Mcontext=context; //①, creating a View instanceMivrefresh =NewImageView (context); Mivrefresh.setimageresource (R.mipmap.ic_launcher); //②, creating layoutsLayoutparams params =Newlayoutparams (ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); //here is the most important: AddRule () Set the layout constraints, here is relativelayout so use the relativelayout constraints, as XMLParams.addrule (relativelayout.center_in_parent,true); //add into RelativelayoutAddView (Mivrefresh,params); }} RefreshviewSecond, the realization of the imageview in the picture rotation repeated playback effect
Knowledge: ①, how to create Animation② in code and XML, how to configure a animation interpolator, how to repeat ③, how to call animation
Here you select the code to create the animation
PrivateImageView Mivrefresh;Private voidSetrefreshanimstart () {Linearinterpolator Lin=NewLinearinterpolator (); //Create Animation animation.relative_to_self to represent itself as a pointAnimation am =NewRotateanimation (0, +360, Animation.relative_to_self,0.5f, Animation.relative_to_self,0.5f ); //execution time of animation start to end (1000 = 1 seconds)Am. Setduration (1000 ); //Animation Repeat count (-1 means repeat)Am.setrepeatcount (-1 ); //Setting the InterpolatorAm.setinterpolator (Lin); //View Control call animationmivrefresh.startanimation (AM); Isfinish=false; }Refreshview
Project Knowledge (vi)