为什么android ImageSpan会显示我的图片两次(当setBounds超过某个魔法宽度时)?

时间:2014-03-30 02:59:49

标签: android android-edittext

以下是将ImageSpan放入EditText的代码。

public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    EditText et = (EditText) getActivity().findViewById(R.id.html_text);

    SpannableString ss = new SpannableString("ABC");
    Drawable d = getResources().getDrawable(R.drawable.ic_launcher);

    d.setBounds(0,0,2256,760);

    ImageSpan span = new ImageSpan(d, "haha", ImageSpan.ALIGN_BASELINE);
    ss.setSpan(span, 0, 3, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    et.setText(ss);
}

在玩耍时,我注意到一些奇怪的事情。我的AVD是2560x1600。当setBounds调用宽度小于或等于2256时,图片显示正确。但是对于宽度大于2256的图片,图片会显示两次。不同图片的魔力值相同。我也尝试过不同尺寸的AVD。对于720x1080,魔术宽度为608.这个魔法宽度是多少?如何确保我的照片不超过这个神奇的宽度?

BTW,这是EditText的布局:

<EditText
    android:id="@+id/html_text"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

1 个答案:

答案 0 :(得分:0)

这对我有用

int width;
int height;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_matn_activity3);  
Display display = getWindowManager().getDefaultDisplay(); 
     width = display.getWidth();  // deprecated
     height = display.getHeight();  // deprecated
 SpannableString ss = new SpannableString("ABC");
Drawable d = getResources().getDrawable(R.drawable.ic_launcher);
double ratio= (double)((double)(d.getIntrinsicWidth())/(double)(d.getIntrinsicHeight()));
//this shows the original ratio of image

                if(d.getIntrinsicWidth()<width){
                d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight());
                Log.v("small","small");
                }else{
                    Log.v("big","big");
                    d.setBounds(0, 0,(int)(width*.95),(int)(d.getIntrinsicHeight()/ratio*.95));
//i dont know why but if you put 1 instead of .95 again you will see 2 images
//this is exactly the magic width you have said
                }
}

它可能没什么问题,因为我的项目很大而且不同我无法输入确切的代码 但它通常有效