在我的项目中,我有一个EditText,一个TextView和一个Imageview。我在Textview和Imageview中显示用户在EditText中输入的内容。这是代码:
public class MainActivity extends AppCompatActivity{
private TextView textView;
private EditText editText;
private ImageView imageView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView= (TextView) findViewById(R.id.flip);
imageView= (ImageView) findViewById(R.id.iv_text_to_image);
editText= (EditText) findViewById(R.id.original);
textView.setText("Hello World");
textView.setDrawingCacheEnabled(true);
textView.buildDrawingCache();
imageView.setImageBitmap(textView.getDrawingCache());
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
//s = "."+s;
textView.setText(s);
imageView.setImageBitmap(textView.getDrawingCache());
}
@Override
public void afterTextChanged(Editable s) {
}
});
}
}
代码有时它可以工作但不完美,例如,如果我取消注释s =“。”+ s;它可以工作,但不会在ImageView中显示输入的最后一个字符。如果我删除该行,结果是意外的,它们很大程度上取决于您的类型。如果不是s =“。”+ s;我将它改为s =“a”+ s;或者像b或c等其他字母,结果再次被忽视。
您认为.setImageBitmap()和.getDrawingCache()可能会发生什么?
顺便说一下,在imageView
中没有显示“Hello world”答案 0 :(得分:0)
我修好了这样做:
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
textView.setText(s);
}
@Override
public void afterTextChanged(Editable s) {
textView.setDrawingCacheEnabled(true);
imageView.setDrawingCacheEnabled(true);
// this is the important code :)
// Without it the view will have a dimension of 0,0 and the bitmap will be null
textView.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
textView.layout(0, 0, textView.getMeasuredWidth(), textView.getMeasuredHeight());
Bitmap bm2 = textView.getDrawingCache();
if (bm2!=null){
imageView.setImageBitmap(bm);
}else{
imageView.setImageBitmap(textView.getDrawingCache());
}
}
我从这里得到了这个想法Android View.getDrawingCache returns null, only null