自定义拖动阴影与文本

时间:2016-07-10 11:07:02

标签: android drag-and-drop

我正在尝试使用小颜色矩形内的文本创建自定义拖动阴影。任何帮助将受到高度赞赏。尝试了两种方式:

一个。使用TextView创建自定义布局并将其膨胀如下:

{
  "result": "\u041b\u043e\u0440\u044d\u043c \u0438\u043f\u0441\u04af\u043c \u0434\u043e\u043b\u043e\u0440 \u0441\u0438\u0442 \u0430\u043c\u044d\u0442, c\u043e\u043d\u0441\u044dc\u0442\u044d\u0442\u04af\u044d\u0440 \u0430\u0434\u0438\u043f\u0438\u0441c\u0438\u043d\u0433 \u044d\u043b\u0438\u0442. \u0410\u044d\u043d\u044d\u0430\u043d c\u043e\u043c\u043c\u043e\u0434\u043e \u043b\u0438\u0433\u04af\u043b\u0430 \u044d\u0433\u044d\u0442 \u0434\u043e\u043b\u043e\u0440."
}

这种方法的问题是因为view1没有添加到视图层次结构中,在MyDragShadowBuilder中,getView()。getWidth()返回0,因此没有绘制任何内容

湾尝试创建一个扩展Drawable的自定义TextDrawable类。这显示了文字,但它非常小,虽然我给的字体大小是20sp。

TextDrawable类:

 public void onItemLongClick(View view, int position) {
    LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View view1 = inflater.inflate(R.layout.drag_shadow, null);
    TextView textCount = (TextView) view1.findViewById(R.id.textCount);
    textCount .setText("" + count);
    View.DragShadowBuilder shadowBuilder = new MyDragShadowBuilder(view1); // Tried with both view1 and textCount
                view.startDrag(data, shadowBuilder, view1, 0);
}

}

MyDragShadowBuilder:

public class TextDrawable extends Drawable {

private final String text;
private final Paint paint;

public TextDrawable(Context context,String text) {

    this.text = text;
    int size = context.getResources().getDimensionPixelSize(R.dimen.drag_shadow_font); //20sp
     Logger.log("TAG","Size="+size);  //60
    this.paint = new Paint();
    paint.setColor(Color.BLUE);
    paint.setTextSize(size);
    paint.setAntiAlias(true);
 //        paint.setFakeBoldText(true);
//        paint.setShadowLayer(6f, 0, 0, Color.BLACK);
//        paint.setStyle(Paint.Style.FILL);
//        paint.setTextAlign(Paint.Align.LEFT);
}

@Override
public void draw(Canvas canvas) {
    canvas.drawText(text, 0, 0, paint);
}

@Override
public void setAlpha(int alpha) {
    paint.setAlpha(alpha);
}

@Override
public void setColorFilter(ColorFilter cf) {
    paint.setColorFilter(cf);
}

@Override
public int getOpacity() {
    return PixelFormat.TRANSLUCENT;
}

1 个答案:

答案 0 :(得分:0)

虽然我来不晚,但可能对其他人有帮助,您的第一种方法是正确的,但是在新建MyDragShadowBuilder(view1)之前,您需要致电-

view1.measure(MeasureSpec.makeMeasureSpec(width,MeasureSpec.EXACTLY),MeasureSpec.makeMeasureSpec(height,MeasureSpec.EXACTLY)); view1.layout(0,0,view1.getMeasuredWidth(),view1.getMeasuredHeight())

这将为您的自定义视图提供适当的尺寸