这是我的代码,按下按钮时会调用Spawn方法:
public void Spawn (View V) {
LayoutInflater inflater =
(LayoutInflater)this.getSystemService( Context.LAYOUT_INFLATER_SERVICE );
View iv = inflater.inflate( R.layout.motor_block, null );
//LinearLayout iv = (LinearLayout) findViewById(R.id.motor_block);
RelativeLayout rl = (RelativeLayout) findViewById(R.id.layout);
CheckBox A = (CheckBox)findViewById(R.id.checkBox1);
boxesA.put(currentKey,A);
CheckBox B = (CheckBox)findViewById(R.id.checkBox2);
boxesB.put(currentKey,B);
CheckBox C = (CheckBox)findViewById(R.id.checkBox3);
boxesC.put(currentKey,C);
iv.setTag(currentKey);
rl.addView(iv);
currentKey ++;
iv.setOnTouchListener(new View.OnTouchListener() {
public boolean onTouch(View v,MotionEvent event) {
iAction = event.getActionMasked();
switch (iAction) {
case MotionEvent.ACTION_MOVE:
v.getLocationOnScreen(aLocation); // get absolute physical location of this View
iOffsetX = (aLocation [ 0 ] - (int) v.getX()); // subtract out this View's relative location within its parent View...
iOffsetY = (aLocation [ 1 ] - (int) v.getY()); // ...yielding the offsets that convert getRawX/Y's coords to setX/Y's coords
iNewX = (int) event.getRawX(); // get absolute physical coords of this touch
iNewY = (int) event.getRawY();
iNewX -= iOffsetX; // remove parent View's screen offset (calc'd above)
iNewY -= iOffsetY;
iNewX -= iRelX; // remove stored touch offset
iNewY -= iRelY;
v.setX(iNewX); // finally, move View to new coords (relative to its parent View)
v.setY(iNewY);
bExitValue = true;
break;
case MotionEvent.ACTION_DOWN:
if (delete){ v.setVisibility(View.GONE); }
iRelX = (int) event.getX(); // preserve offset of this touch within the View
iRelY = (int) event.getY();
bExitValue = false;
break;
case MotionEvent.ACTION_UP:
bExitValue = true;
break;
}
return (bExitValue);
}
});
iv.setOnLongClickListener(new OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
v.setHapticFeedbackEnabled(false);
if (!bExitValue) {
Log.i("TAG",(String) v.getTag());
int key = (Integer) v.getTag();
CheckBox A = boxesA.get(key);
CheckBox B = boxesB.get(key);
CheckBox C = boxesC.get(key);
if (A.isChecked()){ //A IS NULL
Log.i("Checked","A");
}
if (B.isChecked()){
Log.i("Checked","B");
}
if (C.isChecked()){
Log.i("Checked","C");
}
Log.i("Click","LONG");
v.setHapticFeedbackEnabled(true);
}
return true;
}
});
}
在此方法中,会生成一个视图,其中包含三个复选框。 我只是把它们放在一个Hash-map中,以Integer为键。 事实证明A是空的,这对我来说毫无意义。有什么想法吗?
提前致谢。
答案 0 :(得分:0)
在尝试访问属于它的CheckBox视图之前,您需要将视图添加到布局中。在呈现之前访问这些视图的任何尝试都将返回null,因为它们尚未创建。