我通过扩展View创建了一个自定义视图,它绘制得很好但是当我尝试引用xml中的对象时,我可以说如果报告空指针异常则添加一个触摸侦听器。我的xml文件非常简单
<com.projector.interaction.layout.MapMouseView2
xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/mouse"
android:layout_width="fill_parent" android:layout_height="fill_parent">
</com.projector.interaction.layout.MapMouseView2>
然后我尝试按照
引用Viewpublic void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try {
setContentView(R.layout.testlayout);
MapMouseView2 view = (MapMouseView2)findViewById(R.id.mouse);
view.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
Log.d("Debug","Touch Not Working");
return true;
}
});
} catch (Exception e) {
Log.e("Error","Error in TestActivity",e);
}
}
但它给了我一个空指针异常。然后只有修复我能找到的是将我的视图包装在LinearLayout内的xml文件中并通过
引用视图public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try {
setContentView(R.layout.testlayout);
LinearLayout lay = (LinearLayout)findViewById(R.id.lin);
MapMouseView2 mouseView = (MapMouseView2)lay.getChildAt(0);
mouseView.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
Log.d("Debug","Touch Not Working");
return true;
}
});
} catch (Exception e) {
Log.e("Error","Error in TestActivity",e);
}
}
有人可以告诉我我做错了吗?
View类在这里
public class MapMouseView2 extends View{
WindowManager mWinMgr;
Rect zoom;
Rect panLeftRight;
Rect panUpDown;
public MapMouseView2(Context context,AttributeSet attrs){
super(context);
Log.d("Debug","Context,AttribyteSet");
try {
mWinMgr = (WindowManager) context
.getSystemService(Context.WINDOW_SERVICE);
zoom = new Rect(0, 0, 45, mWinMgr.getDefaultDisplay().getHeight());
panLeftRight = new Rect(0, 458, mWinMgr.getDefaultDisplay().getWidth(),
mWinMgr.getDefaultDisplay().getHeight());
panUpDown = new Rect(mWinMgr.getDefaultDisplay().getWidth() - 45, 0,
mWinMgr.getDefaultDisplay().getWidth(), mWinMgr
.getDefaultDisplay().getHeight());
Log.d("Debug","Leaving Constructor");
} catch (Exception e) {
Log.e("Error","Error in MapMouseView",e);
}
}
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
try {
Paint paint = new Paint();
paint.setStyle(Paint.Style.FILL);
// make the entire canvas white
paint.setColor(Color.BLACK);
canvas.drawPaint(paint);
paint.setColor(Color.BLUE);
canvas.drawRect(zoom, paint);
paint.setColor(Color.RED);
canvas.drawRect(panLeftRight, paint);
paint.setColor(Color.RED);
canvas.drawRect(panUpDown, paint);
//canvas.drawCircle(x,y,30,threadPaint);
} catch (Exception e) {
Log.e("Error","Exception in OnDraw",e);
}
}
}
答案 0 :(得分:4)
我认为你应该在super(context, attrs);
的构造函数中调用MapMouseView2
。
修改强>
如果你不这样做,你的观点就不会得到身份。
在第二种方法中,您指的是按位置而不是名称的视图,因此它可以工作。