如何将基于活动的应用程序打开到片段中

时间:2015-06-02 20:35:36

标签: android android-fragments android-activity converter super

我学习编程移动应用程序。我决定转换一个Activity的应用程序是一个片段,但我有一个问题。也许你们中的一些人能够帮助我。

package pl.edu.ug.aib.studentizerApp.fragment;

    import android.app.Fragment;

    import android.os.Bundle;
    import android.text.Editable;
    import android.text.TextWatcher;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.ArrayAdapter;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.ListView;
    import android.widget.TabHost;
    import android.widget.TextView;
    import android.widget.Toast;

    import org.androidannotations.annotations.EFragment;

    import java.util.ArrayList;
    import java.util.List;

    import pl.edu.ug.aib.studentizerApp.R;
    import pl.edu.ug.aib.studentizerApp.todoList.DatabaseHandler;
    import pl.edu.ug.aib.studentizerApp.todoList.Task;

    @EFragment(R.layout.fragment_todo)
    public class TODOFragment extends Fragment {

        EditText zadanieTxt, opisTxt, dataTxt, adresTxt;
        List<Task> Tasks = new ArrayList<Task>();
        ListView TaskListView;
        DatabaseHandler dbHandler;
        @Override
        public View onCreateView (LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
            return inflater.inflate(R.layout.fragment_todo, container, false);
        }
        @Override
        public void onStart() {
            super.onStart();


            zadanieTxt = (EditText) getView().findViewById(R.id.txtZadanie);
            opisTxt = (EditText) getView().findViewById(R.id.txtOpis);
            dataTxt = (EditText) getView().findViewById(R.id.txtData);
            adresTxt = (EditText) getView().findViewById(R.id.txtAdres);
            TaskListView = (ListView) getView().findViewById(R.id.listView);
            dbHandler = new DatabaseHandler(getActivity().getApplicationContext());

            TabHost tabHost = (TabHost) getView().findViewById(R.id.baner);

            tabHost.setup();

            TabHost.TabSpec tabSpec = tabHost.newTabSpec("Dodaj zadanie");
            tabSpec.setContent(R.id.tabZadanie);
            tabSpec.setIndicator("Dodaj Zadanie");
            tabHost.addTab(tabSpec);

            tabSpec = tabHost.newTabSpec("lista");
            tabSpec.setContent(R.id.tabListaZadan);
            tabSpec.setIndicator("Lista");
            tabHost.addTab(tabSpec);

            final Button addBtn = (Button) getView().findViewById(R.id.btnAdd);
            addBtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Task task = new Task(dbHandler.getTaskCount(), String.valueOf(zadanieTxt.getText()), String.valueOf(opisTxt.getText()), String.valueOf(dataTxt.getText()), String.valueOf(adresTxt.getText()));
                    if (!taskExists(task)) {
                        dbHandler.createZadanie(task);
                        Tasks.add(task);
                        Toast.makeText(getActivity().getApplicationContext(), String.valueOf(zadanieTxt.getText()) + " zostało dodane do listy zadań!", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    Toast.makeText(getActivity().getApplicationContext(), String.valueOf(zadanieTxt.getText()) + " Zadanie już istnieje", Toast.LENGTH_SHORT).show();
                }
            });

            zadanieTxt.addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence charSequence, int i, int i2, int i3) {

                }

                @Override
                public void onTextChanged(CharSequence charSequence, int i, int i2, int i3) {
                    addBtn.setEnabled(String.valueOf(zadanieTxt.getText()).trim().length() > 0);
                }

                @Override
                public void afterTextChanged(Editable editable) {

                }
            });



            if (dbHandler.getTaskCount() != 0)
                Tasks.addAll(dbHandler.getAllTasks());

            populateList();
        }

        private boolean taskExists(Task task) {
            String zadanie = task.getZadanie();
            int taskCount = Tasks.size();

            for (int i = 0; i < taskCount; i++) {
                if (zadanie.compareToIgnoreCase(Tasks.get(i).getZadanie()) == 0)
                    return true;
            }
            return false;
        }

    //    public void onActivityResult(int reqCode, int resCode, Intent data) {
    //        if (resCode == RESULT_OK) {
    //            if (reqCode == 1) {
    //                imageUri = data.getData();
    //                contactImageImgView.setImageURI(data.getData());
    //            }
    //        }
    //    }

        private void populateList() {
            ArrayAdapter<Task> adapter = new TaskListAdapter();
            TaskListView.setAdapter(adapter);
        }

        private class TaskListAdapter extends ArrayAdapter<Task> {
            public TaskListAdapter()
            {

                super (TODOFragment.this, R.layout.listview_item, Tasks);
            }

            @Override
            public View getView(int position, View view, ViewGroup parent) {
                if (view == null)
                    view = getActivity().getLayoutInflater().inflate(R.layout.listview_item, parent, false);

                Task currentTask = Tasks.get(position);

                TextView zadanie = (TextView) view.findViewById(R.id.zadanie);
                zadanie.setText(currentTask.getZadanie());
                TextView opis = (TextView) view.findViewById(R.id.opis);
                opis.setText(currentTask.getOpis());
                TextView data = (TextView) view.findViewById(R.id.data);
                data.setText(currentTask.getData());
                TextView adres = (TextView) view.findViewById(R.id.adres);
                adres.setText(currentTask.getAdres());

                return view;
            }
        }



    }

问题在于:

private class TaskListAdapter extends ArrayAdapter<Task> {
        public TaskListAdapter()
        {

            super (TODOFragment.this, R.layout.listview_item, Tasks);
        }

我该怎么办?

有一个Message Gradle Build

Information:Gradle tasks [:app:assembleDebug]
:app:preBuild
:app:compileDebugNdk UP-TO-DATE
:app:preDebugBuild
:app:checkDebugManifest
:app:preReleaseBuild
:app:prepareComAndroidSupportAppcompatV72000Library UP-TO-DATE
:app:prepareComAndroidSupportSupportV42000Library UP-TO-DATE
:app:prepareComFacebookAndroidFacebookAndroidSdk3211Library UP-TO-DATE
:app:prepareComMakeramenRoundedimageview150Library UP-TO-DATE
:app:prepareDebugDependencies
:app:compileDebugAidl UP-TO-DATE
:app:compileDebugRenderscript UP-TO-DATE
:app:generateDebugBuildConfig UP-TO-DATE
:app:generateDebugAssets UP-TO-DATE
:app:mergeDebugAssets UP-TO-DATE
:app:generateDebugResValues UP-TO-DATE
:app:generateDebugResources UP-TO-DATE
:app:mergeDebugResources
:app:processDebugManifest UP-TO-DATE
:app:processDebugResources
:app:generateDebugSources
:app:compileDebugJava
Note: Resolve log file to C:\Users\Kisiel\AndroidStudioProjects\Studentizer\app\build\generated\source\apt\androidannotations.log
Note: Initialize AndroidAnnotations 3.2 with options {androidManifestFile=C:\Users\Kisiel\AndroidStudioProjects\Studentizer\app\build\intermediates\manifests\full\debug\AndroidManifest.xml}
Note: Start processing for 17 annotations on 32 elements
Note: AndroidManifest.xml file found with specified path: C:\Users\Kisiel\AndroidStudioProjects\Studentizer\app\build\intermediates\manifests\full\debug\AndroidManifest.xml
Note: AndroidManifest.xml found: AndroidManifest [applicationPackage=pl.edu.ug.aib.studentizerApp, componentQualifiedNames=[pl.edu.ug.aib.studentizerApp.DrawerActivity_, pl.edu.ug.aib.studentizerApp.FragmentActivity_], permissionQualifiedNames=[android.permission.INTERNET, android.permission.CAMERA, android.permission.WRITE_EXTERNAL_STORAGE, android.permission.ACCESS_FINE_LOCATION, android.permission.ACCESS_COARSE_LOCATION, android.permission.ACCESS_NETWORK_STATE, android.permission.SEND_SMS], applicationClassName=null, libraryProject=false, debugabble=false, minSdkVersion=9, maxSdkVersion=-1, targetSdkVersion=20]
Note: Found project R class: pl.edu.ug.aib.studentizerApp.R
Note: Found Android class: android.R
Note: Validating elements
Note: Validating with EActivityHandler: [pl.edu.ug.aib.studentizerApp.DrawerActivity, pl.edu.ug.aib.studentizerApp.FragmentActivity]
Note: Validating with EFragmentHandler: [pl.edu.ug.aib.studentizerApp.fragment.DashboardFragment, pl.edu.ug.aib.studentizerApp.fragment.TimetableFragment, pl.edu.ug.aib.studentizerApp.fragment.TODOFragment, pl.edu.ug.aib.studentizerApp.fragment.WalletFragment]
Note: Validating with EBeanHandler: [pl.edu.ug.aib.studentizerApp.navigationDrawer.DrawerHandler, pl.edu.ug.aib.studentizerApp.navigationDrawer.DrawerListAdapter, pl.edu.ug.aib.studentizerApp.skmTimetable.adapter.TrainsListAdapter, pl.edu.ug.aib.studentizerApp.skmTimetable.backgroundTasks.RestBackgroundTrainLeft, pl.edu.ug.aib.studentizerApp.skmTimetable.backgroundTasks.RestBackgroundTrainRight]
Note: Validating with EViewGroupHandler: [pl.edu.ug.aib.studentizerApp.navigationDrawer.DrawerItemView, pl.edu.ug.aib.studentizerApp.skmTimetable.itemView.TrainItemView]
Note: Validating with ViewByIdHandler: [stanMiasto, stanPogoda, stanC, listTrainLeftLstView, listTrainRightLstView, refreshBtn, restoreGpsBtn, startIdSpinner, endIdSpinner, text, leftTxtView, rightTxtView, leftLayout, rightLayout, drawerLayout, drawerList, icon, name, hour, minute, tip]
Note: Validating with ClickHandler: [refreshBtnClicked(), restoreGpsBtn()]
Note: Validating with RestHandler: [pl.edu.ug.aib.studentizerApp.dashboard.DashboardRestClient, pl.edu.ug.aib.studentizerApp.skmTimetable.SkmRestClient]
Note: Validating with GetHandler: [getTrains(int,int,int), getTrains(int,int,int)]
Note: Validating with OptionsItemHandler: [drawerToggleSelected(android.view.MenuItem)]
Note: Validating with RestServiceHandler: [restClient, restClient]
Note: Validating with RootContextHanlder: [drawerActivity, context, context, activity, activity]
Note: Validating with NonConfigurationInstanceHandler: [restBackgroundTrainLeft, restBackgroundTrainRight]
Note: Validating with BeanHandler: [restBackgroundTrainLeft, restBackgroundTrainRight, drawerHandler, adapterLeft, adapterRight, drawerListAdapter]
Note: Validating with AfterInjectHandler: [init()]
Note: Validating with AfterViewsHandler: [init(), init(), init(), init()]
Note: Validating with UiThreadHandler: [publishResult(pl.edu.ug.aib.studentizerApp.skmTimetable.data.TrainsList), publishError(java.lang.Exception), publishWarning(), publishResult(pl.edu.ug.aib.studentizerApp.skmTimetable.data.TrainsList), publishError(java.lang.Exception), publishWarning()]
Note: Validating with BackgroundHandler: [getTrains(int,int,int), getTrains(int,int,int)]
Note: Processing root elements
Note: Processing root elements EActivityHandler: [pl.edu.ug.aib.studentizerApp.FragmentActivity, pl.edu.ug.aib.studentizerApp.DrawerActivity]
Note: Processing root elements EFragmentHandler: [pl.edu.ug.aib.studentizerApp.fragment.WalletFragment, pl.edu.ug.aib.studentizerApp.fragment.TimetableFragment, pl.edu.ug.aib.studentizerApp.fragment.DashboardFragment, pl.edu.ug.aib.studentizerApp.fragment.TODOFragment]
Note: Processing root elements EBeanHandler: [pl.edu.ug.aib.studentizerApp.skmTimetable.backgroundTasks.RestBackgroundTrainLeft, pl.edu.ug.aib.studentizerApp.skmTimetable.backgroundTasks.RestBackgroundTrainRight, pl.edu.ug.aib.studentizerApp.navigationDrawer.DrawerListAdapter, pl.edu.ug.aib.studentizerApp.skmTimetable.adapter.TrainsListAdapter, pl.edu.ug.aib.studentizerApp.navigationDrawer.DrawerHandler]
Note: Processing root elements EViewGroupHandler: [pl.edu.ug.aib.studentizerApp.navigationDrawer.DrawerItemView, pl.edu.ug.aib.studentizerApp.skmTimetable.itemView.TrainItemView]
Note: Processing root elements RestHandler: [pl.edu.ug.aib.studentizerApp.skmTimetable.SkmRestClient, pl.edu.ug.aib.studentizerApp.dashboard.DashboardRestClient]
Note: Processing enclosed elements
Note: Number of files generated by AndroidAnnotations: 15
Note: Writting following API classes in project: []
Note: Generating class: pl.edu.ug.aib.studentizerApp.skmTimetable.itemView.TrainItemView_
Note: Generating class: pl.edu.ug.aib.studentizerApp.fragment.DashboardFragment_
Note: Generating class: pl.edu.ug.aib.studentizerApp.fragment.TODOFragment_
Note: Generating class: pl.edu.ug.aib.studentizerApp.fragment.TimetableFragment_
Note: Generating class: pl.edu.ug.aib.studentizerApp.fragment.WalletFragment_
Note: Generating class: pl.edu.ug.aib.studentizerApp.skmTimetable.adapter.TrainsListAdapter_
Note: Generating class: pl.edu.ug.aib.studentizerApp.skmTimetable.SkmRestClient_
Note: Generating class: pl.edu.ug.aib.studentizerApp.dashboard.DashboardRestClient_
Note: Generating class: pl.edu.ug.aib.studentizerApp.DrawerActivity_
Note: Generating class: pl.edu.ug.aib.studentizerApp.FragmentActivity_
Note: Generating class: pl.edu.ug.aib.studentizerApp.skmTimetable.backgroundTasks.RestBackgroundTrainLeft_
Note: Generating class: pl.edu.ug.aib.studentizerApp.skmTimetable.backgroundTasks.RestBackgroundTrainRight_
Note: Generating class: pl.edu.ug.aib.studentizerApp.navigationDrawer.DrawerHandler_
Note: Generating class: pl.edu.ug.aib.studentizerApp.navigationDrawer.DrawerItemView_
Note: Generating class: pl.edu.ug.aib.studentizerApp.navigationDrawer.DrawerListAdapter_
Note: Time measurements: [Whole Processing = 187 ms], [Generate Sources = 100 ms], [Process Annotations = 38 ms], [Validate Annotations = 17 ms], [Find R Classes = 10 ms], [Extract Annotations = 9 ms], [Extract Manifest = 6 ms], 
Note: Finish processing
Note: Start processing for 0 annotations on 15 elements
Note: Time measurements: [Whole Processing = 0 ms], 
Note: Finish processing
Note: Start processing for 0 annotations on 0 elements
Note: Time measurements: [Whole Processing = 1 ms], 
Note: Finish processing
C:\Users\Kisiel\AndroidStudioProjects\Studentizer\app\src\main\java\pl\edu\ug\aib\studentizerApp\navigationDrawer\DrawerListAdapter.java
Error:(36, 19) error: constructor DrawerItem in class DrawerItem cannot be applied to given types;
required: int,int,Class<? extends Fragment>
found: String,int,Class<TODOFragment_>
reason: actual argument String cannot be converted to int by method invocation conversion
Note: C:\Users\Kisiel\AndroidStudioProjects\Studentizer\app\src\main\java\pl\edu\ug\aib\studentizerApp\fragment\TimetableFragment.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
Error:Execution failed for task ':app:compileDebugJava'.
> Compilation failed; see the compiler error output for details.
Information:BUILD FAILED
Information:Total time: 5.649 secs
Information:2 errors
Information:0 warnings
Information:See complete output in console

1 个答案:

答案 0 :(得分:0)

super (TODOFragment.this, R.layout.listview_item, Tasks); 正在寻找你有TODOFragment.this的上下文(这是一个片段,因此不是一个上下文)。

尝试调用TODOFragment.this.getActivity()而不是TODOFragment.this,你应该全部设置。