问题
Here is my code to put an ImageSpan in an 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);
}
While playing around, I noticed something strange. My AVD is 2560x1600. When the setBounds call with width less or equal to 2256, the picture is showing correctly. But for width larger than 2256, the picture is shown twice.! The magic value is the same for different pictures. I also tried AVD with different size. For 720x1080, the magic width is 608. What is this magic width? How can I make sure my picture doesn't exceed this magic width?
BTW, here is the layout for the EditText:
<EditText
android:id="@+id/html_text"
android:layout_width="match_parent"
android:layout_height="match_parent" />
回答1:
this worked for me
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
}
}
it may have little problems because my project is big and different i cant put the exact code .but it generally works
来源:https://stackoverflow.com/questions/22739748/why-does-android-imagespan-show-my-picture-twice-when-setbounds-exceed-certain