我本想要实现,长按一个按钮,该按钮被删除,但是不知道为何老是报错误。
代码:
public class RedirectActivity extends Activity {
Button button = null;
Button button1 = null;
LinearLayout linearLayout = null;
Bundle saved = null;
boolean flag;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
this.saved = savedInstanceState;
button1 = (Button)findViewById(R.id.button1);
linearLayout = (LinearLayout)findViewById(R.id.layout);
button = new Button(this);
button.setId(R.id.button2+1);
button.setText("add one button");
button.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
// linearLayout.addView(button);
linearLayout.addView(button, 1);
button1.setOnLongClickListener(new View.OnLongClickListener() {
public boolean onLongClick(View v) {
// ok();
linearLayout.removeView(button1);
return false;
}
});
}
}
button报了空指针异常,楼主把button.setId(R.id.button2+1);这句代码去掉
把button设置为GONE可以不。
true和flase表示事件是否被消耗,
原来其中的实现机制是这样的啊,所以按照onLongClick()的实现机制,将语句return false;改为return true;就可以了