安卓开发写一个自定义下载按钮
时间: 2023-05-21 09:01:27 浏览: 65
好的,以下是一个简单的安卓自定义下载按钮的代码示例:
1. 在布局文件中添加一个按钮:
```
<Button
android:id="@+id/download_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="下载"
android:background="@drawable/download_button_bg"
android:textColor="@color/white" />
```
2. 创建一个自定义的 Drawable 类,用于设置按钮的背景:
```
public class DownloadButtonDrawable extends Drawable {
private Paint mPaint;
private RectF mRectF;
private int mWidth;
private int mHeight;
private int mColor;
public DownloadButtonDrawable(int color) {
mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mPaint.setStyle(Paint.Style.FILL);
mRectF = new RectF();
mColor = color;
}
@Override
public void draw(Canvas canvas) {
mPaint.setColor(mColor);
canvas.drawRoundRect(mRectF, mWidth / 2, mHeight / 2, mPaint);
}
@Override
public void setAlpha(int alpha) {
mPaint.setAlpha(alpha);
}
@Override
public void setColorFilter(ColorFilter colorFilter) {
mPaint.setColorFilter(colorFilter);
}
@Override
public int getOpacity() {
return PixelFormat.TRANSLUCENT;
}
@Override
protected void onBoundsChange(Rect bounds) {
super.onBoundsChange(bounds);
mWidth = bounds.width();
mHeight = bounds.height();
mRectF.set(bounds);
}
}
```
3. 在 Activity 或 Fragment 中设置按钮的背景和点击事件:
```
Button downloadButton = findViewById(R.id.download_button);
DownloadButtonDrawable drawable = new DownloadButtonDrawable(ContextCompat.getColor(this, R.color.blue));
downloadButton.setBackground(drawable);
downloadButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// 处理下载逻辑
}
});
```
这样就可以实现一个简单的自定义下载按钮了。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)