欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Android(二)

程序员文章站 2022-06-06 09:54:56
...

1. Recyclerview

RecyclerView能够灵活实现大数据集的展示,视图的复用管理比ListView更好,能够显示列表、网格、瀑布流等形式,且不同的ViewHolder能够实现item多元化的功能。

添加的依赖库:implementation ‘com.android.support:design:25.3.1’

1.1 线性列表

  • 效果图
    Android(二)

  • LinearRecyclerViewActivity代码的实现

public class LinearRecyclerViewActivity extends AppCompatActivity {

    private RecyclerView mRvMain;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_linear_recycler_view);
        mRvMain = (RecyclerView) findViewById(R.id.rv_linear_Main);
        mRvMain.setLayoutManager(new LinearLayoutManager(LinearRecyclerViewActivity.this));
        //设置间隔线
        mRvMain.addItemDecoration(new MyDecoration());
        mRvMain.setAdapter(new LinearAdapter(LinearRecyclerViewActivity.this));

    }

    class MyDecoration extends RecyclerView.ItemDecoration {
        @Override
        public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
            super.getItemOffsets(outRect, view, parent, state);
            outRect.set(0,0,0,getResources().getDimensionPixelOffset(R.dimen.dividerHeight));
        }
    }
}
  • activity_linear_recycler_view布局
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    >

    <android.support.v7.widget.RecyclerView
        android:id="@+id/rv_linear_Main"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/colorGrayDark"
        />

</RelativeLayout>
  • LinearAdapter代码
public class LinearAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    private Context mContext;

    public LinearAdapter(Context context) {
        this.mContext = context;
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        if(viewType == 0) {
            return new LinearViewHolder(LayoutInflater.from(mContext).inflate(R.layout.layout_linear_item,parent,false));
        } else {
            return new LinearViewHolder2(LayoutInflater.from(mContext).inflate(R.layout.layout_linear_item2,parent,false));
        }
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
        if(getItemViewType(position) == 0) {
            ((LinearViewHolder)holder).tvTitle.setText("Hello World");
        } else {
            ((LinearViewHolder2)holder).tvTitle.setText("Hello");
//            Glide.with(mContext).load("").into(((LinearViewHolder2)holder).imageView);
        }

        //点击事件监听
        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(mContext,"click..."+position,Toast.LENGTH_SHORT).show();
            }
        });
    }

    @Override
    public int getItemCount() {
        return 30;
    }

    @Override
    public int getItemViewType(int position) {
        if (position %2 == 0) {
            return 0;
        } else {
            return 1;
        }
    }

    class LinearViewHolder extends RecyclerView.ViewHolder {
        private TextView tvTitle;

        public LinearViewHolder(View itemView) {
            super(itemView);
            tvTitle = (TextView) itemView.findViewById(R.id.tv_Title);
        }
    }

    class LinearViewHolder2 extends RecyclerView.ViewHolder {
        private TextView tvTitle;
        private ImageView imageView;

        public LinearViewHolder2(View itemView) {
            super(itemView);
            tvTitle = (TextView) itemView.findViewById(R.id.tv_Title2);
            imageView = (ImageView) itemView.findViewById(R.id.tv_image);
        }
    }
}

1.2 水平滚动

  • 效果图
    Android(二)
  • HorAdapter代码实现
public class HorAdapter extends RecyclerView.Adapter<HorAdapter.LinearViewHolder> {

    private Context mContext;

    public HorAdapter(Context context) {
        this.mContext = context;
    }

    @Override
    public LinearViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        return new LinearViewHolder(LayoutInflater.from(mContext).inflate(R.layout.layout_hor_item,parent,false));
    }

    @Override
    public void onBindViewHolder(LinearViewHolder holder, final int position) {
        holder.tvTitle.setText("Hello");
        //点击事件监听
        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(mContext,"click..."+position,Toast.LENGTH_SHORT).show();
            }
        });
    }

    @Override
    public int getItemCount() {
        return 80;
    }

    class LinearViewHolder extends RecyclerView.ViewHolder {
        private TextView tvTitle;

        public LinearViewHolder(View itemView) {
            super(itemView);
            tvTitle = (TextView) itemView.findViewById(R.id.tv_Title);
        }
    }

}
  • HorRecyclerViewActivity代码
public class HorRecyclerViewActivity extends AppCompatActivity {
    private RecyclerView mRvHor;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_hor_recycler_view);
        mRvHor = (RecyclerView) findViewById(R.id.rv_hor);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(HorRecyclerViewActivity.this);

        linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        mRvHor.setLayoutManager(linearLayoutManager);
        mRvHor.addItemDecoration(new MyDecoration());
        mRvHor.setAdapter(new HorAdapter(HorRecyclerViewActivity.this));
    }

    class MyDecoration extends RecyclerView.ItemDecoration {
        @Override
        public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
            super.getItemOffsets(outRect, view, parent, state);
            outRect.set(0,0,getResources().getDimensionPixelOffset(R.dimen.dividerHeight),0);
        }
    }
}

1.3 网格视图

Adapter的代码和前面水平滚动的Adapter类似(将layout换掉即可)

  • 效果图
    Android(二)
  • GridRecyclerViewActivity代码
public class GridRecyclerViewActivity extends AppCompatActivity {
    private RecyclerView mRvGrid;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_grid_recycler_view);
        mRvGrid = (RecyclerView) findViewById(R.id.rv_grid);
        //第二个参数表示有3列
        mRvGrid.setLayoutManager(new GridLayoutManager(GridRecyclerViewActivity.this,3));
        mRvGrid.setAdapter(new GridAdapter(GridRecyclerViewActivity.this));
    }

}

1.4 瀑布流

Adapter代码与前面类似

  • 效果图
    Android(二)
  • PuRecyclerViewActivity代码
public class PuRecyclerViewActivity extends AppCompatActivity {
    private RecyclerView mRvPu;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pu_recycler_view);
        mRvPu = (RecyclerView) findViewById(R.id.rv_main_pu);
        //设置边距
        mRvPu.addItemDecoration(new MyDecoration());
        //设置成VERTIVCAL前面的数字就是表示几列,HORIZONYTAL前面的数字就是表示几行
        mRvPu.setLayoutManager(new StaggeredGridLayoutManager(2,StaggeredGridLayoutManager.VERTICAL));
        mRvPu.setAdapter(new PuAdapter(PuRecyclerViewActivity.this));
    }

    class MyDecoration extends RecyclerView.ItemDecoration {
        @Override
        public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
            super.getItemOffsets(outRect, view, parent, state);
            int num = getResources().getDimensionPixelOffset(R.dimen.dividerHeightHigh);
            outRect.set(num,num,num,num);
        }
    }
}

2. WebView

用途:WebView主要用来加载网页

实现方法:loadURL();

  • 设置页面可点击返回的方法
@Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && mWv.canGoBack()) {
            mWv.goBack();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
  • WebViewActivity代码的实现
public class WebViewActivity extends AppCompatActivity {
    private WebView mWv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_web_view);
        mWv = (WebView) findViewById(R.id.wv);
        //1.加载本地HTML文件
//        mWv.loadUrl("file:///android_asset/test.html");
        //设置页面支持js文件
        mWv.getSettings().setJavaScriptEnabled(true);
        //2.加载网络URL
        mWv.setWebViewClient(new MyWebViewClient());
        mWv.setWebChromeClient(new MyWebChromeClient());
        mWv.loadUrl("https://m.baidu.com");
    }



    //监听页面加载
    class MyWebViewClient extends WebViewClient {

        //设置其点击后使用的浏览器时本浏览器
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
//            view.loadUrl(request.getUrl().toString());
            String url = request.getUrl().toString();
            if (url == null) return false;

            try{
                if(!url.startsWith("http://") && !url.startsWith("https://")){
                    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                    startActivity(intent);
                    return true;
                }
            }catch (Exception e){//防止crash (如果手机上没有安装处理某个scheme开头的url的APP, 会导致crash)
                return true;//没有安装该app时,返回true,表示拦截自定义链接,但不跳转,避免弹出上面的错误页面
            }

            // TODO Auto-generated method stub
            //返回值是true的时候控制去WebView打开,为false调用系统浏览器或第三方浏览器
            view.loadUrl(url);
            return true;
        }

        //页面初始化时
        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
            Log.d("WebView","onPageStarted...");
        }

        //页面加载完成时
        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            Log.d("WebView","onPageFinished...");
//            mWv.loadUrl("javascript:alert('hello')");
//            mWv.evaluateJavascript("script:alert('hello')",null);
        }
    }

    class MyWebChromeClient extends WebChromeClient {
        //监听进度条
        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            super.onProgressChanged(view, newProgress);
        }

        //设置页面的标题
        @Override
        public void onReceivedTitle(WebView view, String title) {
            super.onReceivedTitle(view, title);
            setTitle(title);
        }
    }

    /**
     * 重写页面可点击返回的方法
     * @param keyCode
     * @param event
     * @return
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && mWv.canGoBack()) {
            mWv.goBack();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}

3. Toast

Toast是一个消息提示组件

创建一个ToastUtil类:消除连续点击的作用(只会承认最后一次点击)

public class ToastUtil {
    public static Toast toast;

    /**消除Toast连续点击出现等待状况
        只按最后一个点击的Toast弹出开始计算时间,也只弹一次
     */
    public static void showMsg(Context context,String msg) {
        if(toast == null) {
            toast = Toast.makeText(context,msg,Toast.LENGTH_LONG);
        } else {
            toast.setText(msg);
        }
        toast.show();
    }
}

4. AlertDialog(提示框)

主要通过AlertDialog.Builder来实现后面需要什么样式设计通过.来设置

4.1 效果一:AlertDialog默认样式

Android(二)

case R.id.dialog_1:
    AlertDialog.Builder builder1 = new AlertDialog.Builder(AlertDialogActivity.this);
    builder1.setTitle("请回答").setMessage("你觉得课程如何?").setIcon(R.drawable.icon_question)
            .setPositiveButton("棒", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    ToastUtil.showMsg(AlertDialogActivity.this,"你很诚实~");
                }
            })
            .setNeutralButton("还好", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    ToastUtil.showMsg(AlertDialogActivity.this,"你再瞅瞅~");
                }
            })
            .setNegativeButton("不好", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    ToastUtil.showMsg(getApplicationContext(),"睁眼说瞎话~");
                }
            }).show();
    break;

4.2 效果二:(单选框)

Android(二)

case R.id.dialog_3:
    AlertDialog.Builder builder3 = new AlertDialog.Builder(AlertDialogActivity.this);
    final String[] arr3 = new String[]{"男","女"};
    //中间的参数checkedItem是默认选中数组中哪个元素(从0开始)
    builder3.setTitle("请选择性别").setSingleChoiceItems(arr3, 0, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
           ToastUtil.showMsg(getApplicationContext(),arr3[which]);
        }
    }).show();
    break;

4.3 效果三:(复选框)

Android(二)

case R.id.dialog_4:
    final String[] arr4 = new String[]{"唱歌","跳舞","写代码"};
    boolean[] isSelected = new boolean[]{false,false,true};
    AlertDialog.Builder builder4 = new AlertDialog.Builder(AlertDialogActivity.this);
    builder4.setTitle("选择兴趣").setMultiChoiceItems(arr4, isSelected, new DialogInterface.OnMultiChoiceClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which, boolean isChecked) {
            ToastUtil.showMsg(AlertDialogActivity.this,arr4[which]+":"+isChecked);
        }
    }).setPositiveButton("确定", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {

                }
            })
            .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {

                }
            }).show();
    break;

4.4 效果四:(自定义)

Android(二)

case R.id.dialog_5:
    AlertDialog.Builder builder5 = new AlertDialog.Builder(AlertDialogActivity.this);
    View view = LayoutInflater.from(AlertDialogActivity.this).inflate(R.layout.layout_dialog, null);
    EditText etUserName = (EditText) view.findViewById(R.id.et_username);
    EditText etPassWord = (EditText) view.findViewById(R.id.et_password);
    Button btnLogin = (Button) view.findViewById(R.id.btn_login);
    btnLogin.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            ToastUtil.showMsg(getApplicationContext(),"登录成功");
        }
    });
    builder5.setTitle("请先登录").setView(view).show();
    break;

5. Progress(进度条)

  • 效果图
    Android(二)

5.1 Layout的代码

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="15dp">

    <ProgressBar
        android:id="@+id/pb_1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        />

    <ProgressBar
        android:id="@+id/pb_2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        style="@android:style/Widget.ProgressBar"
        android:layout_marginTop="10dp"
        />

    <ProgressBar
        android:id="@+id/pb_3"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        style="@android:style/Widget.ProgressBar.Horizontal"
        android:layout_marginTop="10dp"
        android:progress="10"
        android:max="100"
        />

    <ProgressBar
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        style="@android:style/Widget.Material.ProgressBar.Horizontal"
        android:layout_marginTop="10dp"
        android:progress="10"
        android:max="100"
        android:secondaryProgress="30"
        />

    <Button
        android:id="@+id/btn_start"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="模拟进度"
        android:layout_marginTop="10dp"
        />

<!--    自定义进度条 -->
    <ProgressBar
        android:id="@+id/pb_5"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        style="@style/MyProgressBar"/>

    <Button
        android:id="@+id/btn_ProgressDialog1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="ProgressDialog1"
        android:layout_marginTop="10dp"
        android:textAllCaps="false"
        />
    <Button
        android:id="@+id/btn_ProgressDialog2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="ProgressDialog2"
        android:layout_marginTop="10dp"
        android:textAllCaps="false"
        />
</LinearLayout>

5.2 ProgressActivity的代码

public class ProgressActivity extends AppCompatActivity {
    private Button mBtnStart,mBtnProgressDialog1,mBtnProgressDialog2;
    private ProgressBar mPb3;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_progress);
        mPb3 = (ProgressBar) findViewById(R.id.pb_3);
        mBtnStart = (Button) findViewById(R.id.btn_start);
        mBtnStart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                handler.sendEmptyMessage(0);
            }
        });

        mBtnProgressDialog1 = (Button) findViewById(R.id.btn_ProgressDialog1);
        mBtnProgressDialog1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ProgressDialog progressDialog = new ProgressDialog(ProgressActivity.this);
                progressDialog.setTitle(" 提示");
                progressDialog.setMessage("正在加载...");
                progressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
                    @Override
                    public void onCancel(DialogInterface dialog) {
                        ToastUtil.showMsg(ProgressActivity.this,"取消");
                    }
                });
//                progressDialog.setCancelable(false);        //设置false后旁边点击不可取消
                progressDialog.show();
            }
        });


        mBtnProgressDialog2 = (Button) findViewById(R.id.btn_ProgressDialog2);
        mBtnProgressDialog2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
               ProgressDialog progressDialog = new ProgressDialog(ProgressActivity.this);
               progressDialog.setTitle("提示");
               progressDialog.setMessage("正在下载...");

               progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);    //设置进度条的状态为横向
               progressDialog.setButton(DialogInterface.BUTTON_POSITIVE, "确定", new DialogInterface.OnClickListener() {
                   @Override
                   public void onClick(DialogInterface dialog, int which) {
//                       ToastUtil.showMsg(ProgressActivity.this,"已取消");
                   }
               });
                progressDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        ToastUtil.showMsg(ProgressActivity.this,"已取消");
                    }
                });
               progressDialog.show();
            }
        });
    }



    //进行演示进度条工作步骤一:
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if(mPb3.getProgress() < 100) {
                mPb3.postDelayed(runnable,500);
            } else {
                ToastUtil.showMsg(ProgressActivity.this,"加载完成");
            }
        }
    };

    //进行演示进度条工作步骤二:
    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            mPb3.setProgress(mPb3.getProgress()+5);
            handler.sendEmptyMessage(0);
        }
    };
}

6. 自定义Dialog

主要思路:设计一个类继承Dialog用来自定义Dialog

效果图:
Android(二)

  • 自定义CustomDialog的代码
public class CustomDialog extends Dialog implements View.OnClickListener {
    private TextView mTvTitle,mTvMessage,mTvCancel,mTvConfirm;

    private String title,message,cancel,confirm;

    private ICancelListener cancelListener;
    private IConfirmListener confirmListener;

    public CustomDialog setTitle(String title) {
        this.title = title;
        return this;
    }

    public CustomDialog setMessage(String message) {
        this.message = message;
        return this;
    }

    public CustomDialog setCancel(String cancel,ICancelListener listener) {
        this.cancel = cancel;
        this.cancelListener = listener;
        return this;
    }

    public CustomDialog setConfirm(String confirm,IConfirmListener listener) {
        this.confirm = confirm;
        this.confirmListener = listener;
        return this;
    }

    public CustomDialog(@NonNull Context context) {
        super(context);
    }

    public CustomDialog(@NonNull Context context, int themeResId) {
        super(context, themeResId);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_custom_dialog);

        //设置宽度(直接套用即可)
        WindowManager m = getWindow().getWindowManager();
        Display d = m.getDefaultDisplay();
        WindowManager.LayoutParams p = getWindow().getAttributes();
        Point size = new Point();
        d.getSize(size);
        p.width = (int) (size.x * 0.8);
        getWindow().setAttributes(p);

        mTvTitle = (TextView) findViewById(R.id.tv_title);
        mTvMessage = (TextView) findViewById(R.id.tv_message);
        mTvCancel = (TextView) findViewById(R.id.tv_cancel);
        mTvConfirm = (TextView) findViewById(R.id.tv_confirm);

        if (!TextUtils.isEmpty(title)) {
            mTvTitle.setText(title);
        }
        if (!TextUtils.isEmpty(message)) {
            mTvMessage.setText(message);
        }
        if (!TextUtils.isEmpty(cancel)) {
            mTvCancel.setText(cancel);
        }
        if (!TextUtils.isEmpty(confirm)) {
            mTvConfirm.setText(confirm);
        }

        mTvCancel.setOnClickListener(this);
        mTvConfirm.setOnClickListener(this);
    }

    //设置view的点击监听事件
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_cancel :
                if (cancelListener != null) {
                    cancelListener.onCancel(this);
                }
                dismiss();
                break;
            case R.id.tv_confirm :
                if (confirmListener != null) {
                    confirmListener.onConfirm(this);
                }
                dismiss();
                break;
        }
    }

    public interface ICancelListener {
        void onCancel(CustomDialog dialog);
    }

    public interface IConfirmListener {
        void onConfirm(CustomDialog dialog);
    }
}
  • CustomDialogActivity的代码
public class CustomDialogActivity extends AppCompatActivity {
    private Button mBtnCustom_Dialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_custom_dialog);

        mBtnCustom_Dialog = (Button) findViewById(R.id.btn_custom_dialog);
        mBtnCustom_Dialog.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                CustomDialog customDialog = new CustomDialog(CustomDialogActivity.this);
                customDialog.setTitle("提示").setMessage("确定要删除吗?")
                        .setCancel("取消", new CustomDialog.ICancelListener() {
                            @Override
                            public void onCancel(CustomDialog dialog) {
                                ToastUtil.showMsg(CustomDialogActivity.this,"已取消");
                            }
                        })
                        .setConfirm("确定", new CustomDialog.IConfirmListener() {
                            @Override
                            public void onConfirm(CustomDialog dialog) {
                                ToastUtil.showMsg(CustomDialogActivity.this,"确定");
                            }
                }).show();
            }
        });
    }
}

7. 属性动画

  • 补间动画和属性动画的区别与联系:
    1. 补间动画:虽然效果展示了,但是实际位置并没有发生改变;
    2. 属性动画:真正的做到了位置发生了变化

属性动画的实现:主要通过 ValueAnimator 和 ObjectAnimator.ofFloat 实现,最后.start

属性 效果
translation 平移
translationX 沿X轴平移
alpha 渐变
rotation 旋转
scaleX 缩放
  • 代码
public class AnimatorActivity extends AppCompatActivity {
    private TextView mTvAnimatorTest;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_animator);
        mTvAnimatorTest = (TextView) findViewById(R.id.tv_test);
        mTvAnimatorTest.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                mTvAnimatorTest.animate().translationY(800).setDuration(2000).start();    //平移

//                mTvAnimatorTest.animate().rotation(800).setDuration(2000).start();    //旋转


                //1.使用ValueAnimator
                /*ValueAnimator valueAnimator = ValueAnimator.ofInt(0,100);   //设置从0到100位置
                valueAnimator.setDuration(2000);        //设置响应时间为两秒
                valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                    @Override
                    public void onAnimationUpdate(ValueAnimator animation) {
                        //valueAnimator 实际的值
                        Log.d("Animated-Value",animation.getAnimatedValue()+"");
                        //动画的进度0-1
                        Log.d("Animated-Fraction",animation.getAnimatedFraction()+"");
                    }
                });
                valueAnimator.start();*/


                //2.使用ObjectAnimator.ofFloat
                ObjectAnimator objectAnimator = ObjectAnimator.ofFloat(mTvAnimatorTest,"translationY",0,800,300,1100);   //后面第三个参数开始移动的位置起始点
                objectAnimator.setDuration(5000);
                objectAnimator.start();
            }
        });
    }
}
相关标签: Android