我的应用程序中有自定义适配器,我需要根据一些数字在每个ListView项目中绘制简单的行。
我已阅读了许多相关的教程,但我仍然不知道如何以正确的方式实现它。我是Android和Java的新手,但我似乎了解Android的一切,但绘画/绘画。任何人都可以建议给我一些指导。
编辑:
以下是我现在使用的一些代码:
在one-item-layout(row.xml)中我有ImageView:
<ImageView
android:id="@+id/chart"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
在我的自定义适配器中,我有这个:
public class MyImageView extends ImageView{
public MyImageView(Context context) {
super(context);
// TODO Auto-generated constructor stub
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
Paint p = new Paint(Paint.ANTI_ALIAS_FLAG);
canvas.drawLine(0, 0, 20, 20, p);
}
}
我遇到的问题是如何将自定义视图放在图像视图(或任何其他容器)中。
答案 0 :(得分:1)
您可以在布局中添加View
以绘制线条并从适配器更改其颜色/宽度。
<View
android:id="@+id/chart"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
并在适配器中
class MyAdapter extends ArrayAdapter<Integer> {
private Context context;
MyAdapter(Context context, Integer[] numbers) {
super(context, R.layout.your_layout, numbers);
this.context = context;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = LayoutInflater.from(context)
.inflate(R.layout.your_layout, parent, false);
holder = new ViewHolder();
holder.lineView = convertView.findViewById(R.id.chart);
convertView.setTag(holder);
}
else {
holder = convertView.getTag();
}
int number = getItem(position);
// Calculate width based on your number. Must be in px
ViewGroup.LayoutParams params = holder.lineView.getLayoutParams();
params.width = calculatedWidth;
// Calculate color based on your number
int color = Color.rgb(r, g, b);
holder.lineView.setBackroundColor(color);
}
private class ViewHolder {
View lineView;
}
}
答案 1 :(得分:1)
你可以试试这个
public class MyImageView extends ImageView{
private Paint mPaint;
private float cx, cy;
private int size;
public MyImageView(Context context) {
super(context);
init();
}
private void init() {
mPaint = new Paint();
mPaint.setAntiAlias(true);
mPaint.setColor(Color.BLACK);
mPaint.setStrokeWidth(20);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawLine(0, 0, size, size, mPaint);
}
@Override
protected void onSizeChanged(int w, int h, int oldW, int oldH) {
super.onSizeChanged(w, h, oldw, oldh);
cx = w/2;
cy = h/2;
///calculate the size of the view here.
size = Math.min(w, h);
}
@Override
protected void onMeasure (int widthMeasureSpec, int heightMeasureSpec) {
setMeasuredDimension(size, size);
}
}