我正在尝试在我的活动中制作动态添加视图的图像。
你能告诉我我做错了吗,由于某种原因,位图返回null。
谢谢,
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_share);
TextView tv = new TextView(this);
tv.setText("sadasdsadssad");
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT);
tv.setLayoutParams(lp);
tv.setDrawingCacheEnabled(true);
tv.buildDrawingCache();
Bitmap bm = tv.getDrawingCache();
ImageView im = (ImageView)findViewById(R.id.imgQuestion);
im.setImageBitmap(bm);
}
答案 0 :(得分:1)
您没有将文字视图添加到屏幕上。添加后,将计算视图高度和宽度以进行渲染,然后仅绘制视图,您可以从中获取位图。
做三件事,
如果您不希望不显示文本视图,请使用textView.setVisibility(View.INVISIBLE);在获取位图之后。
以下是我的问题代码。
activity_main.xml中
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/root"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity">
<ImageView
android:id="@+id/img_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
MainActivity.java的onCreate()
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView tv;
tv = new TextView(this);
tv.setText("sadasdsadssad");
tv.setVisibility(View.INVISIBLE);
ViewGroup rl = (ViewGroup) findViewById(R.id.root);
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT);
tv.setLayoutParams(lp);
rl.addView(tv);
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
tv.setDrawingCacheEnabled(true);
tv.buildDrawingCache();
Bitmap bm = tv.getDrawingCache();
ImageView im = (ImageView) findViewById(R.id.img_view);
im.setImageBitmap(bm);
}
},100);
}