项目知识(六)

一、如何在代码中将View放入ViewGroup中(组合控件)

需求:创建一个类似百度贴吧刷新的按钮,但又不想用xml来布局。

要求:创建一个View类继承RelativeLayout然后将ImageView填充的RelativeLayout中

那么怎么从JAVA代码中将ImageView放入RelativeLayout中。

public class RefreshView extends RelativeLayout implements View.OnClickListener{
    private ImageView mIvRefresh;
    private Context mContext;

    public RefreshView(Context context) {
        super(context);
        initView(context);
    }

    public RefreshView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initView(context);
    }

    public RefreshView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initView(context);
    }

    private void initView(Context context){
        mContext = context;
        //①、创建View实例
        mIvRefresh = new ImageView(context);
        mIvRefresh.setImageResource(R.mipmap.ic_launcher);
        //②、创建布局
        LayoutParams params = new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        //这里最重要:addRule()设置布局约束,这里是relativeLayout所以使用relativeLayout的约束,跟xml一样
        params.addRule(RelativeLayout.CENTER_IN_PARENT,TRUE);
       //添加进RelativeLayout中       
 addView(mIvRefresh,params);
    }

}
    
RefreshView

二、实现ImageView中的图片旋转重复播放效果

用到的知识:①、如何在代码中和xml中创建Animation ②、如何配置Animation 插值器、重复次数  ③、View如何调用Animation

这里选择代码中创建Animation

private ImageView mIvRefresh; 

private void setRefreshAnimStart(){
        LinearInterpolator lin = new LinearInterpolator();
        //创建Animation    Animation.RELATIVE_TO_SELF表示以自身为点
        Animation am = new RotateAnimation( 0, +360,
                Animation.RELATIVE_TO_SELF, 0.5f,
                Animation.RELATIVE_TO_SELF, 0.5f );

        // 动画开始到结束的执行时间(1000 = 1 秒)
        am. setDuration ( 1000 );
        // 动画重复次数(-1 表示一直重复)
        am.setRepeatCount ( -1 );
        //设置插值器
        am.setInterpolator(lin);
        // view控件调用Animation
        mIvRefresh.startAnimation(am);
        isFinish = false;
    }
RefreshView
posted @ 2016-06-13 12:59  技术丶从积累开始  阅读(132)  评论(0编辑  收藏  举报