将一些功能从mainactivity移到另一个类

时间:2018-12-09 16:32:41

标签: android class

我有一个addAllToGroup单击函数,并且在许多不同的地方使用DialogWithRadioButtonM,是否可以将DialogWithRadioButtonM()和redioGroup1()函数放在单独的文件(类)中?这是我的代码: 我试图将其放在类中,但是在其中出现onclicklistener错误,并且我也不知道如何在nonActivity java文件中使用上下文。抱歉,我是android和java的新手,感谢您的帮助。

public void addAllToGroup(View view) {
        csM = new String[6];
        //dialogTitle="Add This to Group";
        csM[0] = "Add to Group 1";
        csM[1] = "Add to Group 2";
        csM[2] = "Add to Group 3";
        csM[3] = "Add to Group 4";
        csM[4] = "Add to Group 5";
        csM[5] = "Remove Grouping";
        DialogWithRadioButtonM("Add Selected to Group");
    }

    public void DialogWithRadioButtonM(String str){

        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
        builder.setTitle(str);
        builder.setSingleChoiceItems(csM, -1, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int item) {
                Log.i("TAG2", "onCreate: "+item);

                switch(item)
                {
                    case 0: backFromDialogM=0; break;
                    case 1: backFromDialogM=1; break;
                    case 2: backFromDialogM=2; break;
                    case 3: backFromDialogM=3; break;
                    case 4: backFromDialogM=4; break;
                    case 5: backFromDialogM=5; break;
                    case 6: backFromDialogM=6; break;
                    case 7: backFromDialogM=7; break;
                }

                redioGroup1(backFromDialogM);
                alertDialogM.dismiss();
            }
        });
        alertDialogM = builder.create();
        alertDialogM.show();

    }


    public void redioGroup1(int group) {

        int iCount = myRecycler.getAdapter().getItemCount();
        MyDateBase mydbM = new MyDateBase(MainActivity.this);
        final SQLiteDatabase databaseM = mydbM.getWritableDatabase();
        String strCL = "cl" + "0";
        String rawQueryM="";
        for (int i = 0; i < iCount; i++) {
            if (mAdapter.itemList.get(i).isChecked()) {
                mAdapter.itemList.get(i).getuSentId();
                rawQueryM ="UPDATE wp_words SET " + strCL + " =" + group + " WHERE wid= " + mAdapter.itemList.get(i).getuSentId();
                databaseM.execSQL(rawQueryM);
                Log.i("tog", "" + mAdapter.itemList.get(i).getuSentId());
            }
        }
        Log.i("togf", "" + rawQueryM);

    }

谢谢

1 个答案:

答案 0 :(得分:0)

您的“ DialogWithRadioButtonM”类取决于它所在的外部类。 您必须使“ DialogWithRadioButtonM”不依赖于其外部的其他变量/对象,否则就不能将其移动到独立的Class文件中。 例如:“ backFromDialogM”和“ alertDialogM”未声明为INSIDE DialogWithRadioButtonM,而是在同一文件中的其他地方声明。