[英]How to change the size of the Drawable in TextView in Android?
I want to know how to update a Drawable in a TextView, so I write the following code: 我想知道如何在TextView中更新Drawable,所以我编写以下代码:
public class MainActivity extends AppCompatActivity {
private TextView mText;
private ColorDrawable mColorDrawable;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mText = (TextView) findViewById(R.id.text_view);
mColorDrawable = new ColorDrawable(Color.RED);
mColorDrawable.setBounds(0, 0, 100, 100);
SpannableString string = new SpannableString("This is a color box: /box, right?");
string.setSpan(new ImageSpan(mColorDrawable), 21, 25, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
mText.setText(string);
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
mColorDrawable.setColor(Color.YELLOW);
mColorDrawable.setBounds(0, 0, 200, 200);
mText.invalidate();
}
}, 1000);
}
}
The expected result is that the /box
is replaced with a red square. 预期的结果是
/box
被替换为红色方块。 After 1 second, it becomes bigger and its color turns into yellow. 1秒后,它变大,颜色变成黄色。
And here are the screenshots before and after the color of the box changes. 以下是盒子颜色变化之前和之后的屏幕截图。
As you can see, the color is changed but the size is not changed properly. 如您所见,颜色已更改,但尺寸未正确更改。 Also, the text after the box isn't moved rightwards but is covered by the box.
此外,框后面的文本不会向右移动,而是被框覆盖。
So my question is, how to make the TextView re-layout the Drawables and text, if not using setText()
once more time? 所以我的问题是,如果不再使用
setText()
,如何使TextView重新布局Drawables和文本?
Try to pass "int size" inside run() and then add setTextSize(size) and setBounds: 尝试在run()中传递“int size”,然后添加setTextSize(size)和setBounds:
int size= 20; //you can change that later
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
mColorDrawable.setColor(Color.YELLOW);
mColorDrawable.setBounds(0, 0, 200, 200);
mText.invalidate();
size= size+ 20;
mText.setTextSize(size);
mColorDrawable.setBounds(0, 0, size, size);
}
}, 1000);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.