实现接口的空类变量

时间:2014-09-06 09:28:29

标签: java android android-fragments alertdialog

我还没有找到类似的问题,所以我写了一个新问题。 我正在开发一个小的Android应用程序,我的界面有一些问题。该应用由3个片段和ViewPager组成。单击一个按钮,我显示一个自定义对话框(使我扩展AlertDialog.Builder类)。为了从目标片段中检索数据,我创建了一个我在片段中实现的接口。

一切似乎都有效,但是当我尝试在重写方法中访问片段类变量时,它们是空的!类变量在onCreateView片段方法中初始化。 感谢

import android.content.DialogInterface;

public interface BandDialogInterface{

    public void onActionCreate(DialogInterface dialog, String name, MyColor color);

    public void onActionEdit(DialogInterface dialog, int id, String name, MyColor color);
}

因为我在尝试一些事情,所以有点混乱:

public class EditBandDialog extends AlertDialog.Builder {

    private final Band band;
    private Spinner listColor;
    private EditText inputName;

    private DatabaseHelper dbHelper;

    private BandDialogInterface bandDialogInterface;

    public EditBandDialog(Context context, final Band band){
        super(context);
        this.band = band;

        try{
            bandDialogInterface = ((MercenAppActivity)context).getBandsFragment();
            Log.d("CONTEXT", ((MercenAppActivity)context).getBandsFragment().toString());
        }catch (Exception e){
            e.printStackTrace();
        }

        View dialogView = ((Activity)context).getLayoutInflater().inflate(R.layout.dialog_edit_band, null);
        setView(dialogView);

        setCancelable(false);

        dbHelper = new DatabaseHelper(context);

        listColor = (Spinner)dialogView.findViewById(R.id.dialog_edit_band_color);
        inputName = (EditText)dialogView.findViewById(R.id.dialog_edit_band_name);

        BandColorAdapter adapter = new BandColorAdapter(context);
        listColor.setAdapter(adapter);

        if(isNewBand()) {
            setTitle(R.string.title_new_band);
            setPositiveButton("Crea", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {

                    //bandAdapter.insert(new Band(-1, inputName.getText().toString(), ((MyColor) listColor.getSelectedItem())));
                    //Toast.makeText(getContext(), R.string.toast_band_added, Toast.LENGTH_SHORT).show();
                    bandDialogInterface.onActionCreate(dialog, inputName.getText().toString(), (MyColor)listColor.getSelectedItem());

                }
            });
        }else{
            setTitle(R.string.title_edit_band);

            inputName.setText(band.getName());

            int pos = 0;
            while(((MyColor)listColor.getAdapter().getItem(pos)).getColor() != band.getColor())
                pos++;
            listColor.setSelection(pos);

            setPositiveButton("Modifica", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    //dbHelper.updateBand(dbHelper.getWritableDatabase(), band.getId(), inputName.getText().toString(), ((MyColor) listColor.getSelectedItem()).getColor());
                    //bandAdapter.update(new Band(band.getId(), inputName.getText().toString(), ((MyColor) listColor.getSelectedItem())));
                    //Toast.makeText(getContext(), R.string.toast_band_edited, Toast.LENGTH_SHORT).show();
                    bandDialogInterface.onActionEdit(dialog, band.getId(), inputName.getText().toString(), (MyColor)listColor.getSelectedItem());
                }
            });
        }

        setNegativeButton("Annulla", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });

    }

    private boolean isNewBand(){
        return band == null;
    }

}

class MyColor{
    int color;

    public MyColor(int color){
        this.color = color;
    }

    public static MyColor fromString(String s){
        return new MyColor(Color.parseColor(s));
    }

    public int getColor(){
        return color;
    }
}

class BandColorAdapter extends ArrayAdapter<MyColor> implements SpinnerAdapter {

    private static final MyColor[] colors = {MyColor.fromString("#D60000"),     //ROSSO
                                             MyColor.fromString("#0080FF"),     //AZZURRO
                                             MyColor.fromString("#00AD37"),     //VERDE
                                             MyColor.fromString("#FFF700"),     //GIALLO
                                             MyColor.fromString("#FF8400"),     //ARANCIO
                                             MyColor.fromString("#10009C")};    //BLU

    public BandColorAdapter(Context context) {
        super(context, R.layout.row_band_color, colors);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        if (convertView == null) {
            convertView = LayoutInflater.from(getContext()).inflate(R.layout.row_band_color, parent, false);
        }

        View bandColor = convertView.findViewById(R.id.band_color_item);
        bandColor.setBackgroundColor(getItem(position).getColor());

        return convertView;
    }

    @Override
    public View getDropDownView(int position, View convertView, ViewGroup parent) {
        if (convertView == null)
        {
            convertView = LayoutInflater.from(getContext()).inflate(R.layout.row_band_color, parent, false);
        }

        View bandColor = convertView.findViewById(R.id.band_color_item);
        bandColor.setBackgroundColor(getItem(position).getColor());

        return convertView;
    }
}

这是我实现界面的类:

public class BandsFragment extends Fragment implements BandDialogInterface{

    private static final String TAG = "BandsFragment";
    private static final boolean D = true;

    private DatabaseHelper dbHelper;
    private BandAdapter bandAdapter;

    private String s;

    public BandsFragment(){

    }

    @Override
    public void onActionCreate(DialogInterface dialog, String name, MyColor color) {
        //Toast.makeText(getActivity(), "CREATE", Toast.LENGTH_SHORT).show();
        //bandAdapter.insert(new Band(0, name, color));
        Log.d("CREATE", s);
    }

    @Override
    public void onActionEdit(DialogInterface dialog, int id, String name, MyColor color) {
        Toast.makeText(getActivity(), "EDITED", Toast.LENGTH_SHORT).show();
    }

    /**
     * Returns a new instance of this fragment for the given section
     * number.
     */
    public static BandsFragment newInstance() {
        BandsFragment fragment = new BandsFragment();
        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_bands, container, false);

        if (D) Log.d(TAG, "--- onCreateView ---");

        dbHelper = new DatabaseHelper(getActivity());

        ListView listBands = (ListView)rootView.findViewById(R.id.list_bands);
        TextView noBands = (TextView)rootView.findViewById(R.id.no_bands);

        bandAdapter = new BandAdapter(getActivity(), noBands);
        listBands.setAdapter(bandAdapter);

//        if(dbList.size() == 0){
//            noBands.setVisibility(View.VISIBLE);
//        }else{
//            noBands.setVisibility(View.GONE);
//        }

        listBands.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //TODO something
            }
        });

        registerForContextMenu(listBands);

        return rootView;
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        if (D) Log.d(TAG, "--- onAttach ---");
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (D) Log.d(TAG, "--- onCreate ---");
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        if (D) Log.d(TAG, "--- onViewCreated ---");
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        if (D) Log.d(TAG, "--- onActivityCreated ---");
    }

    @Override
    public void onStart() {
        super.onStart();
        if (D) Log.d(TAG, "--- onStart ---");
    }

    @Override
    public void onResume() {
        super.onResume();
        if (D) Log.d(TAG, "--- onResume ---");
    }

    @Override
    public void onPause() {
        super.onPause();
        if (D) Log.d(TAG, "--- onPause ---");
    }

    @Override
    public void onStop() {
        super.onStop();
        if (D) Log.d(TAG, "--- onStop ---");
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (D) Log.d(TAG, "--- onDestroyView ---");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (D) Log.d(TAG, "--- onDestroy ---");
    }

    @Override
    public void onDetach() {
        super.onDetach();
        if (D) Log.d(TAG, "--- onDetach ---");
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo);
        AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)menuInfo;
        menu.setHeaderTitle(bandAdapter.getItem(info.position).getName());
        getActivity().getMenuInflater().inflate(R.menu.context_band, menu);

        MenuItem.OnMenuItemClickListener l = new MenuItem.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                onContextItemSelected(item);
                return true;
            }
        };

        for(int i = 0; i < menu.size(); ++i){
            menu.getItem(i).setOnMenuItemClickListener(l);
        }

    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {
        AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)item.getMenuInfo();
        switch (item.getItemId()){
            case R.id.context_band_edit:
                new EditBandDialog(getActivity(), bandAdapter.getItem(info.position)).show();
                //Log.d("D",bandAdapter.getItem(info.position).getName());
                break;
            case R.id.context_band_delete:
                /*dbHelper.deleteBand(dbHelper.getWritableDatabase(), bandAdapter.getItem(info.position).getId());
                bandAdapter.remove(bandAdapter.getItem(info.position));
                bandAdapter.notifyDataSetChanged();*/
                bandAdapter.delete(bandAdapter.getItem(info.position));
                Toast.makeText(getActivity(), R.string.toast_band_deleted, Toast.LENGTH_SHORT).show();
                break;
        }
        return true;
    }
}


class BandAdapter extends ArrayAdapter<Band> implements SpinnerAdapter{

    private DatabaseHelper dbHelper;
    private TextView noBands;

    public BandAdapter(Context context, TextView noBands) {
        super(context, R.layout.row_band);
        this.noBands = noBands;
        dbHelper = new DatabaseHelper(context);
        updateAdapter();
    }

    private void updateAdapter(){
        clear();
        addAll(dbHelper.getAllBands());

        if(noBands != null) {

            if (isEmpty()) {
                noBands.setVisibility(View.VISIBLE);
            } else {
                noBands.setVisibility(View.GONE);
            }

        }
        notifyDataSetChanged();
    }

    public void insert(Band band){
        //dbHelper.insertBand(dbHelper.getWritableDatabase(), band.getName(), band.getColor());
        Toast.makeText(getContext(), "ADDED", Toast.LENGTH_SHORT).show();
        updateAdapter();
    }

    public void update(Band band){
        dbHelper.updateBand(dbHelper.getWritableDatabase(), band.getId(), band.getName(), band.getColor());
        updateAdapter();
    }

    public void delete(Band band){
        dbHelper.deleteBand(dbHelper.getWritableDatabase(), band.getId());
        updateAdapter();
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // Get the data item for this position
        Band band = getItem(position);

        // Check if an existing view is being reused, otherwise inflate the view
        if (convertView == null) {
            convertView = LayoutInflater.from(getContext()).inflate(R.layout.row_band, parent, false);
        }
        // Lookup view for data population
        TextView bandName = (TextView) convertView.findViewById(R.id.band_name);
        View bandColor = (View) convertView.findViewById(R.id.band_color);
        bandColor.setBackgroundColor(band.getColor());
        // Populate the data into the template view using the data object
        bandName.setText(band.getName());
        // Return the completed view to render on screen
        return convertView;
    }

    @Override
    public View getDropDownView(int position, View convertView, ViewGroup parent) {
        if (convertView == null)
        {
            convertView = LayoutInflater.from(getContext()).inflate(R.layout.row_band, parent, false);
        }

        Band band = getItem(position);

        TextView bandName = (TextView) convertView.findViewById(R.id.band_name);
        View bandColor = (View) convertView.findViewById(R.id.band_color);
        bandColor.setBackgroundColor(band.getColor());
        // Populate the data into the template view using the data object
        bandName.setText(band.getName());


        return convertView;
    }

}

0 个答案:

没有答案