我有一个类(称为 Doodling :))),它扩展了视图和显示该视图的活动(称为 DrawActivity )。我需要将我的涂鸦类创建的位图对象传递给绘制活动。有可能吗?如果是的话,怎么样?!
代码如下:
public class Doodling extends View {
Bitmap bitmap;
public DoodleCanvas(Context context, AttributeSet attrs) {
...
}
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
if (bitmap != null) {
bitmap .recycle();
}
canvas= new Canvas();
bitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
canvas.setBitmap(bitmap);
}
protected void onDraw(Canvas c) {
...
}
public class DrawActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_draw);
}
然后通过.xml
将涂鸦视图放置在布局中答案 0 :(得分:0)
在DrawActivity
中创建Doodling
课程的新实例。
然后使用以下代码: -
doodlingObject.setDrawingCacheEnabled(true);
doodlingObject.buildDrawingCache();
Bitmap bitmap = doodlingObject.getDrawingCache();
希望这有帮助!
答案 1 :(得分:0)
我将添加难以实现此目的但我会建议您使用EventBus以获得更清洁的用途,而不必担心接口或活动生命周期
如果您已从活动本身创建了View对象,则可以使用接口执行此操作
类似的东西:
interface BitMapListener{
void onBitMapCreated(Bitmap bMap);
}
然后这个接口在Activity
中实现public DrawActivity ... implements BitMapListener{
BitMap created;
@override
public void onBitMapCreated(BitMap map){
created = map;
}
//when calling DrawView activity pass in this object
//DrawView(DrawActivity.this);
从活动中调用DrawView类时,请记住传递此活动对象,如:
DrawView ...{
DrawActivity callback;
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
if (bitmap != null) {
bitmap .recycle();
}
canvas= new Canvas();
bitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
canvas.setBitmap(bitmap);
callback.onBitMapCreated(bitmap);
}
答案 2 :(得分:0)
如果您可以保证Doodling仅用于DrawActivity,那么您可以使用getSystemService()
获取对活动的引用。
public class DrawActivity extends AppCompatActivity {
private static final String TAG = "DrawActivity";
public static DrawActivity get(Context context) {
// noinspection ResourceType
return (DrawActivity)context.getSystemService(TAG);
}
@Override
public Object getSystemService(String name) {
if(TAG.equals(name)) return this ;
return super.getSystemService(name);
}
和
public class Doodle extends View {
....
DrawActivity drawActivity = DrawActivity.get(getContext());