在editText span中单击其删除按钮时删除元素

时间:2013-02-04 11:03:14

标签: android

final SpannableStringBuilder sb = new SpannableStringBuilder();
TextView tv = createContactTextView(contactName);
BitmapDrawable bd = (BitmapDrawable) convertViewToDrawable(tv);
bd.setBounds(0, 0, bd.getIntrinsicWidth(),bd.getIntrinsicHeight());

sb.append(contactName + ",");
sb.setSpan(new ImageSpan(bd), sb.length()-(contactName.length()+1), sb.length()-            1,Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
to_input.setText(sb);

public static Object convertViewToDrawable(View view) {
  int spec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
  view.measure(spec, spec);
  view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());
  Bitmap b = Bitmap.createBitmap(view.getMeasuredWidth(), view.getMeasuredHeight(),
        Bitmap.Config.ARGB_8888);
  Canvas c = new Canvas(b);
  c.translate(-view.getScrollX(), -view.getScrollY());
  view.draw(c);
  view.setDrawingCacheEnabled(true);
  Bitmap cacheBmp = view.getDrawingCache();
  Bitmap viewBmp = cacheBmp.copy(Bitmap.Config.ARGB_8888, true);
  view.destroyDrawingCache();
  return new BitmapDrawable(viewBmp);

}

public TextView createContactTextView(String text){
  //creating textview dynamically
  TextView tv = new TextView(this);
  tv.setText(text);
  tv.setTextSize(20);
  tv.setBackgroundResource(R.drawable.oval);
  tv.setCompoundDrawablesWithIntrinsicBounds(0, 0,     R.drawable.ic_clear_search_api_holo_light, 0);
 tv.setOnTouchListener(new OnTouchListener() {

        @Override
        public boolean onTouch(View v, MotionEvent event) {
              Drawable co =  ((TextView) v).getCompoundDrawables()[2];

                if (event.getX() > v.getMeasuredWidth() - v.getPaddingRight()
                        - co.getIntrinsicWidth()) {
                            //tv.setText("");
                            Log.i(TAG, "clicked on delete button");
                    return true;
                } else {
                    return false;
                }
        }

});
  return tv;


}

它将在editText中创建带有文本的Spans但我想删除span在该范围内点击删除按钮。我为它创建了代码“tv.setOnTouchListener(new OnTouchListener(){................”在createContactTextView函数中,但它不起作用。     enter image description here}

1 个答案:

答案 0 :(得分:0)

将ImageSpan和ClickableSpan设置为相同的开始和结束位置。

sb.setSpan(new ImageSpan(bd),startSpan ,endSpan , Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
sb.setSpan(new ClickableSpan() {
                    @Override
                    public void onClick(View widget) {
                       //  DeleteHere
                    }
                }, startSpan , endSpan , Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

同时删除你的touchlistener,它将无法正常工作!现在将LinkMovement设置为您的edittext。

editText.setMovementMethod(LinkMovementMethod.getInstance());