2010-01-14 51 views
1

我的应用程序的底层视图具有在画布上绘制的位图,线条等。我想显示图像(图标),这将响应触摸事件。这些图像的数量和位置将根据SQLite数据库中的数据而变化。ViewGroup中的ImageButtons

我正确地认为实现这一目标的方法是首先添加一个ViewGroup,然后为每个图标添加一个带有OnTouch侦听器的ImageButton对象,并通过在RelativeLayout中设置边距来定义位置。 LayoutParams对象?

我的每个按钮的代码的内容如下: '

public class MyButton { 

ImageButton mButton; 
private Bitmap Star; 

public MyButton(int intX, int intY) { 
    mButton = new ImageButton(Global.thisApp);  
    mButton.setImageBitmap(BitmapFactory.decodeResource(Global.thisApp.getResources(), R.drawable.star)r); 
    mButton.setPadding(0, 0, 0, 0); 
    mButton.setOnTouchListener(new ImageButton.OnTouchListener() { 
     @Override 
     public boolean onTouch(View arg0, MotionEvent arg1) { 
      // ToDo 
      return false; 
     } 
    }); 
    RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams 
     (LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); 
    params.setMargins(intX, intY, 0, 0); 
    Global.thisApp.mLayout.addView(mButton, params); 
} 

}

` 和其产生的按钮的代码如下:

 poiCount = 0; 
    mCursor=Global.mDBAdapter.fetchItems(...); 
    if (mCursor.getCount()>=0) { 
     poi = new MyButton[mCursor.getCount()]; 
     mCursor.moveToFirst(); 
     do { 
      int X = ... ; 
      int Y = ... ; 
      poi[poiCount] = new MyButton("Type", X, Y); 
      poiCount++; 
     } while (mCursor.moveToNext()); 
    } 

此代码是从底层视图的onDraw()方法调用。

这似乎在最初绘制屏幕时以及随后重新绘制屏幕(使用新数据)时会添加新按钮;但是,以前的按钮不会被删除。

我试着调用Global.ThisApp.MyLayout.removeView,每个依次按钮作为参数,但Eclipse对象表示MyButton对象不能成为removeView的参数。

如何在每次底层视图无效时删除现有按钮?

+0

没有任何直接的答案,我决定采取不同的课程。而不是添加ImageButton对象到ViewGroup我现在已经改变了应用程序,使得图标位图仅仅绘制在主视图的画布上,并且我已经在View的OnTouch方法中插入了简单代码以确定触摸的接近程度任何图标。这似乎工作得很好,比添加ImageButton快得多。 – prepbgg 2010-01-14 20:13:00

回答

0

MyButton应扩展查看(在您的情况下ImageButton)添加到ViewGroup或从ViewGroup中删除。

+0

谢谢。我明天会试试。我应该删除mButton字段和构造函数的第一行: (mButton = new ImageButton(Global.thisApp))? – prepbgg 2010-01-14 22:57:37

+0

是的,你不需要那条线。你的构造函数也应该接收其他参数(至少是Context)。 – 2010-01-15 00:02:31

+0

我修改了MyButton类,以便它扩展ImageButton而不是将ImageButton作为成员。这工作,但我似乎仍然有相同的问题: - 按钮是缓慢出现(在仿真器上,无论如何) - 他们不响应触摸(我尝试在ToTouch内放置吐司方法) - 当ViewGroup(RelativeLayout)失效时,它们不会被删除。 幸运的是,我的替代代码(忽略ImageButtons并直接绘制到画布上)似乎可行,所以我认为我会坚持这一点。 (它可以很容易地检测触摸是否接近多个图标。) – prepbgg 2010-01-15 08:35:03