Android:以编程方式添加和删除View

时间:2014-06-21 18:01:24

标签: android view nullpointerexception android-inflate

我正在动态添加和删除视图,如下所示:

代码:

    view_share_dialog = findViewById(R.id.view_share_coloring);

    case R.id.btn_share_coloring:

        if(btn.isChecked())
        {

            CloseOpenedView(btn);
            AnimUtils.slideToLeft_ColorView(view_share_dialog, mContext);
            view_share_dialog.bringToFront();
            mDrawView.newLine(android.R.color.transparent);
            Toast.makeText(getApplicationContext(), "FRONT", Toast.LENGTH_SHORT).show();
        }
        else
        {
            img.bringToFront();
            AnimUtils.slideToRight_ColorView(view_share_dialog, mContext);                  
            mDrawView.newLine(Color.parseColor(allColors[lastSelectedCol]));
            ((RelativeLayout)view_share_dialog.getParent()).removeView(view_share_dialog);

            Toast.makeText(getApplicationContext(), "GONE", Toast.LENGTH_SHORT).show();
        }
        break;

// these are the buttons of choices for sharing in the View
public void shareButtonClickable(boolean clickable)
{
    findViewById(R.id.btn_share_copy).setClickable(clickable);  //line 467
    findViewById(R.id.btn_share_email).setClickable(clickable);
    findViewById(R.id.btn_share_facebook_c).setClickable(clickable);
    findViewById(R.id.btn_share_photo_album).setClickable(clickable);
}

的logcat:

06-22 01:52:36.571: E/AndroidRuntime(15096): Caused by: java.lang.reflect.InvocationTargetException
06-22 01:52:36.571: E/AndroidRuntime(15096):    at java.lang.reflect.Method.invokeNative(Native Method)
06-22 01:52:36.571: E/AndroidRuntime(15096):    at java.lang.reflect.Method.invoke(Method.java:515)
06-22 01:52:36.571: E/AndroidRuntime(15096):    at android.view.View$1.onClick(View.java:3964)
06-22 01:52:36.571: E/AndroidRuntime(15096):    ... 12 more
06-22 01:52:36.571: E/AndroidRuntime(15096): Caused by: java.lang.NullPointerException
06-22 01:52:36.571: E/AndroidRuntime(15096):    at com.abc.abc.ColoringPageActivity.shareButtonClickable(ColoringPageActivity.java:467)
06-22 01:52:36.571: E/AndroidRuntime(15096):    at com.abc.abc.ColoringPageActivity.onClickToggle_coloring(ColoringPageActivity.java:528)
06-22 01:52:36.571: E/AndroidRuntime(15096):    ... 15 more

问题:

首次按下btn_share_coloring按钮,可以将视图从屏幕右侧动画到中心。然后当再次按下btn_share_coloring(即未选中)时,视图也可以从中心向右动画,可以正确显示Toast“Gone”。然而,当用户再次按下btn时,将导致致命的NPE。

虽然可以正确删除View,但视图如何再次充分膨胀?

谢谢!

0 个答案:

没有答案