如何销毁我之前创建的视图对象

时间:2013-02-12 06:59:59

标签: android android-view

我想要销毁View中创建的OnClickListener类的对象 popupView 对象。

我希望机制每次都应该创建新的View。我对创建View对象的方式有疑问。

我的完整代码:

package com.addictioncounterapp;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout.LayoutParams;
import android.widget.PopupWindow;
import android.widget.TextView;

public class AddictionDetails extends Activity 
{
TextView tv_addiction_name, tv_today, tv_yesterday, tv_this_week, tv_this_month, tv_total;
ImageView iv_back, iv_filter;
int year, month, day;
int placeData;
Boolean state = false;
DatePickerDialog.OnDateSetListener dateListener;
SQLiteDatabase database;
int cat_id = 0;


@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_addiction_details);

    Intent intent = getIntent();
    final String cat_name = intent.getStringExtra("cat_name");
    tv_addiction_name = (TextView) findViewById(R.id.textViewAddictionDetails);
    tv_addiction_name.setText(cat_name);

    tv_total = (TextView) findViewById(R.id.textview_total);
    tv_today = (TextView) findViewById(R.id.textview_today);
    tv_yesterday = (TextView) findViewById(R.id.textview_yesterday);
    tv_this_week = (TextView) findViewById(R.id.textview_this_week);
    tv_this_month = (TextView) findViewById(R.id.textview_this_month);

    iv_back = (ImageView) findViewById(R.id.imageViewAddictionDetailsBack);
    iv_back.setClickable(true);
    iv_back.setOnClickListener(new OnClickListener()
                                    {
                                        @Override
                                        public void onClick(View v)
                                        {
                                            Intent intent = new Intent(AddictionDetails.this, StartActivity.class);
                                            startActivity(intent);
                                        }
                                    }
                                );

    iv_filter = (ImageView) findViewById(R.id.imageViewAddictionDetailsFilter);
    iv_filter.setClickable(true);
    iv_filter.setOnClickListener(new OnClickListener()
                                    {
                                        @Override
                                        public void onClick(View v)
                                        {   
                                            if(state == false)
                                            {
                                                state = true;
                                                LayoutInflater layoutInflater = (LayoutInflater)getBaseContext().getSystemService(LAYOUT_INFLATER_SERVICE);
                                                final View popupView = layoutInflater.inflate(R.layout.activity_filter_addiction_form, null);

                                                final PopupWindow popupWindow = new PopupWindow(popupView, LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
                                                popupWindow.setWidth(300);
                                                popupWindow.setHeight(300);

                                                final Calendar cal = Calendar.getInstance();
                                                year = cal.get(Calendar.YEAR);
                                                month = cal.get(Calendar.MONTH);
                                                day = cal.get(Calendar.DAY_OF_MONTH);

                                                final EditText etStartDate = (EditText)popupView.findViewById(R.id.editTextFilterStartDate);
                                                etStartDate.setOnClickListener(new OnClickListener()
                                                                                    {   
                                                                                        @Override
                                                                                        public void onClick(View v)
                                                                                        {
                                                                                            showDialog(1);
                                                                                            placeData = 1;
                                                                                        }
                                                                                    }
                                                                                );

                                                final EditText etEndDate = (EditText)popupView.findViewById(R.id.editTextFilterEndDate);
                                                etEndDate.setOnClickListener(new OnClickListener()
                                                                                    {   
                                                                                        @Override
                                                                                        public void onClick(View v)
                                                                                        {
                                                                                            showDialog(1);
                                                                                            placeData = 2;
                                                                                        }
                                                                                    }
                                                                            );

                                                Button btn_done = (Button) popupView.findViewById(R.id.buttonDone);
                                                btn_done.setOnClickListener(new OnClickListener()
                                                                            {
                                                                                 @Override
                                                                                 public void onClick(View v)
                                                                                 {
                                                                                     if(etStartDate.getText()+""=="" || etEndDate.getText()+""=="")
                                                                                     {
                                                                                         AlertDialog.Builder adb = new Builder(AddictionDetails.this);
                                                                                         adb.setTitle("Error");
                                                                                         adb.setMessage("Fields can't be blank.");
                                                                                         adb.setIcon(R.drawable.ic_launcher);
                                                                                         adb.setPositiveButton("Ok",new DialogInterface.OnClickListener()
                                                                                                                         {
                                                                                                                             public void onClick(DialogInterface dialog, int which)
                                                                                                                             {
                                                                                                                                 dialog.dismiss();
                                                                                                                             }
                                                                                                                         }
                                                                                                                );
                                                                                         AlertDialog ad = adb.create();
                                                                                         ad.show();
                                                                                     }
                                                                                     else
                                                                                     {
                                                                                        SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");

                                                                                        Date date1 = null;
                                                                                        try
                                                                                        {
                                                                                            date1 = sdf.parse(etStartDate.getText()+"");
                                                                                        }
                                                                                        catch (ParseException e)
                                                                                        {
                                                                                            e.printStackTrace();
                                                                                        }

                                                                                        Date date2 = null;
                                                                                        try
                                                                                        {
                                                                                            date2 = sdf.parse(etEndDate.getText()+"");
                                                                                        }
                                                                                        catch (ParseException e)
                                                                                        {
                                                                                            e.printStackTrace();
                                                                                        }

                                                                                        System.out.println(sdf.format(date1));
                                                                                        System.out.println(sdf.format(date2));

                                                                                        if(date1.compareTo(date2)>0)
                                                                                        {
                                                                                            AlertDialog.Builder adb = new Builder(AddictionDetails.this);
                                                                                            adb.setTitle("Error");
                                                                                            adb.setMessage("Start date cannot be greater than End date.");
                                                                                            adb.setIcon(R.drawable.ic_launcher);
                                                                                            adb.setPositiveButton("Ok",new DialogInterface.OnClickListener()
                                                                                                                         {
                                                                                                                                 public void onClick(DialogInterface dialog, int which)
                                                                                                                                 {
                                                                                                                                     dialog.dismiss();
                                                                                                                                 }
                                                                                                                             }
                                                                                                                    );
                                                                                             AlertDialog ad = adb.create();
                                                                                             ad.show();
                                                                                        }
                                                                                        else
                                                                                        {
                                                                                            Intent intent = new Intent(AddictionDetails.this, FilteredData.class);
                                                                                            intent.putExtra("start_date", etStartDate.getText()+"");
                                                                                            intent.putExtra("end_date", etEndDate.getText()+"");
                                                                                            intent.putExtra("cat_id", cat_id);
                                                                                            intent.putExtra("cat_name", cat_name);
                                                                                            startActivity(intent);
                                                                                        }
                                                                                     } 
                                                                                 }
                                                                             }
                                                                        );

                                                Button btn_cancel = (Button) popupView.findViewById(R.id.buttonCancel);
                                                btn_cancel.setOnClickListener(new OnClickListener()
                                                                                {
                                                                                     @Override
                                                                                     public void onClick(View v)
                                                                                     {

                                                                                         popupWindow.dismiss();

                                                                                         state = false;
                                                                                     }
                                                                                 }
                                                                            );

                                                dateListener = new DatePickerDialog.OnDateSetListener()
                                                                    {
                                                                        @Override
                                                                        public void onDateSet(DatePicker view, int yr, int monthOfYear, int dayOfMonth)
                                                                        {
                                                                            SimpleDateFormat tmpDateFormat = new SimpleDateFormat("dd/MM/yyyy");
                                                                            Calendar tmpC1 = Calendar.getInstance();
                                                                            tmpC1.set(yr, monthOfYear, dayOfMonth);
                                                                            Date tmpD1 = tmpC1.getTime();
                                                                            String tmpDateString = tmpDateFormat.format(tmpD1);                                                                             
                                                                            update(placeData, tmpDateString);
                                                                        }

                                                                        private void update(int position, String strDate)
                                                                        {
                                                                            switch(position)
                                                                            {
                                                                                case 1:
                                                                                    Log.e("In Addiction details In startDate", strDate);

                                                                                    etStartDate.setText(strDate);
                                                                                    break;

                                                                                case 2:
                                                                                    Log.e("In Addiction details In endDate", strDate);

                                                                                    etEndDate.setText(strDate);
                                                                                    break;
                                                                            }
                                                                        }
                                                                    };

                                                popupWindow.showAsDropDown(iv_filter, 0, 0);
                                            }                                               
                                        }
                                    }
                                );

    loadDB();

    Cursor cursor = database.query("category", new String[]{"cat_id"}, "cat_name=?", new String[]{cat_name}, null, null, null);

    //----------------------fetching id-------------------

    if(cursor.getCount() > 0)
        while(cursor.moveToNext())
            cat_id = cursor.getInt(0);
    cursor.close();

    //----------------------fetching total-------------------

    int totalCounter;
    Cursor totalCursor = database.rawQuery("select sum(cat_attribute_unit) from counter where cat_id ="+cat_id+";", null);
    if(totalCursor.moveToNext())
        totalCounter = totalCursor.getInt(0);
    else
        totalCounter = 0;
    totalCursor.close();
    tv_total.setText(totalCounter+"");

    //----------------------fetching today's count---------------

    Calendar cal1 = Calendar.getInstance();
    SimpleDateFormat dateFormat1 = new SimpleDateFormat("dd/MM/yyyy");

    String todays_date = dateFormat1.format(cal1.getTime());
    int todayCounter;

    Cursor todayCursor = database.rawQuery("select sum(cat_attribute_unit) from counter where cat_id ="+cat_id+" AND counter_entry_date = '"+todays_date+"';", null);
    if(todayCursor.moveToNext())
        todayCounter = todayCursor.getInt(0);
    else
        todayCounter = 0;
    todayCursor.close();

    tv_today.setText(todayCounter+"");

    //----------------------fetching yesterdays count------------------

    Calendar cal2 = Calendar.getInstance();
    SimpleDateFormat dateFormat2 = new SimpleDateFormat("dd/MM/yyyy");
    cal2.add(Calendar.DATE, -1);

    String yesterdays_date = dateFormat2.format(cal2.getTime());

    int yesterdayCounter = 0;

    Cursor yesterdayCursor = database.rawQuery("select sum(cat_attribute_unit) from counter where cat_id ="+cat_id+" AND counter_entry_date = '"+yesterdays_date+"';", null);

    if(yesterdayCursor.moveToFirst())
        yesterdayCounter = yesterdayCursor.getInt(0);
    else
        yesterdayCounter = 0;

    yesterdayCursor.close();

    tv_yesterday.setText(yesterdayCounter+"");

    //-------------------------fetching current week count--------------------

    SimpleDateFormat weekDateFormat = new SimpleDateFormat("dd/MM/yyyy");
    Calendar c1 = Calendar.getInstance();
    c1.set(Calendar.DAY_OF_WEEK, 1);
    Date weekFirstDate = c1.getTime();
    String strWeekFirstDay = weekDateFormat.format(weekFirstDate);

    Cursor weekCursor = database.rawQuery("select sum(cat_attribute_unit) from counter where cat_id ="+cat_id+" AND counter_entry_date BETWEEN '"+strWeekFirstDay+"' AND '"+todays_date+"';", null);

    int weekCounter = 0;
    if(weekCursor.moveToFirst())
        weekCounter = weekCursor.getInt(0);
    else
        weekCounter = 0;
    weekCursor.close();

    tv_this_week.setText(weekCounter+"");

    //----------------------fetching current month count--------------------

    SimpleDateFormat monthDateFormat = new SimpleDateFormat("dd/MM/yyyy");
    Calendar c2 = Calendar.getInstance();
    c2.set(Calendar.DAY_OF_MONTH, 1);
    Date monthFirstDate = c2.getTime();
    String strMonthFirstDay = monthDateFormat.format(monthFirstDate);

    Cursor monthCursor = database.rawQuery("select sum(cat_attribute_unit) from counter where cat_id ="+cat_id+" AND counter_entry_date BETWEEN '"+strMonthFirstDay+"' AND '"+todays_date+"';", null);
    int monthCounter = 0;
    if(monthCursor.moveToFirst())
        monthCounter = monthCursor.getInt(0);
    else
        monthCounter = 0;
    monthCursor.close();

    tv_this_month.setText(monthCounter+"");

    database.close();
}

private void loadDB() 
{
    database = openOrCreateDatabase("AddictionCounter.db", SQLiteDatabase.OPEN_READWRITE, null);
}

protected Dialog onCreateDialog(int id)
{
    return new DatePickerDialog(this, dateListener, year, month, day);
}
}

此外,我无法在OnClickListener的IF循环中引用任何类。在给出 Ctrl + space 时会出错。

2 个答案:

答案 0 :(得分:1)

处销毁popupView
popupWindow.setOnDismissListener

答案 1 :(得分:1)

首先尝试回答,如果我必须重新阅读,请纠正我。

我认为通常的做法是创建一个成员popupWindow,然后使用setContentView和dismiss来显示或不显示它。但是,如果你真的需要销毁它并在每次onClick时创建它:

  • 不要将其声明为最终版。 GC会在调用onClick
  • 之间正常清理它
  • 完成更改后调用dismiss()

你是什么意思你不能在听众中引用任何课程?你的意思是你不能调用像onPause()方法这样的东西吗?为了以防万一,考虑到当你在侦听器中执行此操作时,您不再从Activity中执行此操作。如果你需要引用onCreateDialog或其他东西你可以通过getParent

来完成