如何将 activity 转换为片段

how to convert activity to fragment

我正在尝试使用导航抽屉,我有一个包含 ListViewActivity 代码。我想将所有 Activity 转换为 Fragment,我该怎么做?

有人可以 post 我的代码转换成 Fragment 吗?

这是我的 activity 代码:

public class SceltaDiete extends ActionBarActivity{


ListView sceltadieta;
Database d = new Database(getApplicationContext());

public void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);
    setContentView(R.layout.scelta_activity);
    sceltadieta = (ListView) findViewById(R.id.scelta_dieta);

    final Cursor c = d.scelta();

      CursorLoader(c);

        String from[] = {Codice.DATI_ID,
                Codice.DATI_NOME_DIETA};

        int to[] = {R.id.record_id,
                R.id.record_nome};

    @SuppressWarnings("deprecation")
    SimpleCursorAdapter sca = new SimpleCursorAdapter(this,
            R.layout.singolo_elemento,
            c, from, to);
    sceltadieta = (ListView) findViewById(R.id.scelta_dieta);
    sceltadieta.setAdapter(sca);
    sceltadieta.setClickable(true);
    sceltadieta.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @SuppressWarnings("deprecation")
        public void onItemClick(AdapterView<?> parent, View v, int position,
                long id) {
            TextView txtId = (TextView) v.findViewById(R.id.record_id);
            TextView txtNome = (TextView) v.findViewById(R.id.record_nome);
            String nomeString = (String) txtNome.getText();
            String elemIdString = (String) txtId.getText(); 
            final int elemIdInt = Integer.parseInt(elemIdString);
            switch(elemIdInt){
            case 1:
                d.cancella();   
                d.insertscelta(nomeString);
                break;
            case 2:
                d.cancella();   
                d.insertscelta(nomeString);
                break;
            case 3: 
                d.cancella();
                d.insertscelta(nomeString);
                break;
            case 4: 
                d.cancella();
                d.insertscelta(nomeString);
                break;
            case 5: 
                d.cancella();
                d.insertscelta(nomeString);
                break;
            case 6: 
                d.cancella();
                d.insertscelta(nomeString);
                break;
            case 7: 
                d.cancella();
                d.insertscelta(nomeString);
                break;
            }
          }
        });
}
private void CursorLoader(Cursor c) {
    // TODO Auto-generated method stub

}

}

我已经转换了我的代码:

public class SceltaDiete extends Fragment{

private static final String ARG_SECTION_NUMBER="section_number";
public SceltaDiete() {
    // Required empty public constructor
}
ListView sceltadieta;
Database d;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.scelta_activity, container, false);
    sceltadieta = (ListView) getActivity().findViewById(R.id.scelta_dieta);
    d= new Database(getActivity());

    final Cursor c = d.scelta();

    CursorLoader(c);

    String from[] = {Codice.DATI_ID,
            Codice.DATI_NOME_DIETA};

    int to[] = {R.id.record_id,
            R.id.record_nome};

    @SuppressWarnings("deprecation")
    SimpleCursorAdapter sca = new SimpleCursorAdapter(getActivity(),
            R.layout.singolo_elemento,
            c, from, to);
    sceltadieta = (ListView) getActivity().findViewById(R.id.scelta_dieta);
    sceltadieta.setAdapter(sca);
    sceltadieta.setClickable(true);
    sceltadieta.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @SuppressWarnings("deprecation")
        public void onItemClick(AdapterView<?> parent, View v, int position,
                long id) {
            TextView txtId = (TextView) v.findViewById(R.id.record_id);
            TextView txtNome = (TextView) v.findViewById(R.id.record_nome);
            String nomeString = (String) txtNome.getText();
            String elemIdString = (String) txtId.getText(); 
            final int elemIdInt = Integer.parseInt(elemIdString);
            switch(elemIdInt){
            case 1:
                d.cancella();   
                d.insertscelta(nomeString);
                break;
            case 2:
                d.cancella();   
                d.insertscelta(nomeString);
                break;
            case 3: 
                d.cancella();
                d.insertscelta(nomeString);
                break;
            case 4: 
                d.cancella();
                d.insertscelta(nomeString);
                break;
            case 5: 
                d.cancella();
                d.insertscelta(nomeString);
                break;
            case 6: 
                d.cancella();
                d.insertscelta(nomeString);
                break;
            case 7: 
                d.cancella();
                d.insertscelta(nomeString);
                break;
            }
        }
    });
    return rootView;
}
private void CursorLoader(Cursor c) {
    // TODO Auto-generated method stub

}
@Override
public void onAttach(Activity activity){
    super.onAttach(activity);
    ((MainActivity) activity).onSectionAttached(getArguments().getInt(
            ARG_SECTION_NUMBER));
}
public static SceltaDiete newIstance(int sectionNumber){
    SceltaDiete frag= new SceltaDiete();
    Bundle args=new Bundle();
    args.putInt(ARG_SECTION_NUMBER,sectionNumber);
    frag.setArguments(args);
    return frag;
}}

但是当我点击 Navigation Drawer 来显示我的 Fragment 时,应用程序崩溃了 这是 Logcat:

02-27 13:30:16.189: D/gralloc_goldfish(1095): Emulator without GPU emulation detected.
02-27 13:30:21.943: W/art(1095): Suspending all threads took: 8.538ms
02-27 13:30:22.053: I/art(1095): Background partial concurrent mark sweep GC freed 1886(118KB) AllocSpace objects, 0(0B) LOS objects, 52% free, 929KB/1953KB, paused 11.283ms total 410.100ms
02-27 13:30:23.025: I/Choreographer(1095): Skipped 117 frames!  The application may be doing too much work on its main thread.
02-27 13:30:24.181: I/Choreographer(1095): Skipped 116 frames!  The application may be doing too much work on its main thread.
02-27 13:30:27.901: I/Choreographer(1095): Skipped 188 frames!  The application may be doing too much work on its main thread.
02-27 13:30:28.724: I/Choreographer(1095): Skipped 82 frames!  The application may be doing too much work on its main thread.
02-27 13:30:29.371: I/Choreographer(1095): Skipped 65 frames!  The application may be doing too much work on its main thread.
02-27 13:30:34.325: D/AndroidRuntime(1095): Shutting down VM
02-27 13:30:34.325: D/AndroidRuntime(1095): --------- beginning of crash
02-27 13:30:34.359: E/AndroidRuntime(1095): FATAL EXCEPTION: main
02-27 13:30:34.359: E/AndroidRuntime(1095): Process: com.lp.lemiediete, PID: 1095
02-27 13:30:34.359: E/AndroidRuntime(1095): java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference
02-27 13:30:34.359: E/AndroidRuntime(1095):     at com.lp.lemiediete.SceltaDiete.onCreateView(SceltaDiete.java:48)
02-27 13:30:34.359: E/AndroidRuntime(1095):     at android.support.v4.app.Fragment.performCreateView(Fragment.java:1786)
02-27 13:30:34.359: E/AndroidRuntime(1095):     at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:947)
02-27 13:30:34.359: E/AndroidRuntime(1095):     at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1126)
02-27 13:30:34.359: E/AndroidRuntime(1095):     at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:739)
02-27 13:30:34.359: E/AndroidRuntime(1095):     at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1489)
02-27 13:30:34.359: E/AndroidRuntime(1095):     at android.support.v4.app.FragmentManagerImpl.run(FragmentManager.java:454)
02-27 13:30:34.359: E/AndroidRuntime(1095):     at android.os.Handler.handleCallback(Handler.java:739)
02-27 13:30:34.359: E/AndroidRuntime(1095):     at android.os.Handler.dispatchMessage(Handler.java:95)
02-27 13:30:34.359: E/AndroidRuntime(1095):     at android.os.Looper.loop(Looper.java:135)
02-27 13:30:34.359: E/AndroidRuntime(1095):     at android.app.ActivityThread.main(ActivityThread.java:5221)
02-27 13:30:34.359: E/AndroidRuntime(1095):     at java.lang.reflect.Method.invoke(Native Method)
02-27 13:30:34.359: E/AndroidRuntime(1095):     at java.lang.reflect.Method.invoke(Method.java:372)
02-27 13:30:34.359: E/AndroidRuntime(1095):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
02-27 13:30:34.359: E/AndroidRuntime(1095):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
02-27 13:30:43.969: I/Process(1095): Sending signal. PID: 1095 SIG: 9

@Slaiv206 试试这个:

您必须做的改变:

  1. public class SceltaDiete extends Fragment

    代替ActionBarActivity

  2. 替换public void onCreate(Bundle savedInstanceState){

    public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {


complete class:

import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SimpleCursorAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;

public class SceltaDiete extends Fragment{


    ListView sceltadieta;
    Database d;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.scelta_activity, container, false);
        sceltadieta = (ListView) findViewById(R.id.scelta_dieta);
        d= new Database(getActivity());

        final Cursor c = d.scelta();

        CursorLoader(c);

        String from[] = {Codice.DATI_ID,
                Codice.DATI_NOME_DIETA};

        int to[] = {R.id.record_id,
                R.id.record_nome};

        @SuppressWarnings("deprecation")
        SimpleCursorAdapter sca = new SimpleCursorAdapter(this,
                R.layout.singolo_elemento,
                c, from, to);
        sceltadieta = (ListView) findViewById(R.id.scelta_dieta);
        sceltadieta.setAdapter(sca);
        sceltadieta.setClickable(true);
        sceltadieta.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @SuppressWarnings("deprecation")
            public void onItemClick(AdapterView<?> parent, View v, int position,
                    long id) {
                TextView txtId = (TextView) v.findViewById(R.id.record_id);
                TextView txtNome = (TextView) v.findViewById(R.id.record_nome);
                String nomeString = (String) txtNome.getText();
                String elemIdString = (String) txtId.getText(); 
                final int elemIdInt = Integer.parseInt(elemIdString);
                switch(elemIdInt){
                case 1:
                    d.cancella();   
                    d.insertscelta(nomeString);
                    break;
                case 2:
                    d.cancella();   
                    d.insertscelta(nomeString);
                    break;
                case 3: 
                    d.cancella();
                    d.insertscelta(nomeString);
                    break;
                case 4: 
                    d.cancella();
                    d.insertscelta(nomeString);
                    break;
                case 5: 
                    d.cancella();
                    d.insertscelta(nomeString);
                    break;
                case 6: 
                    d.cancella();
                    d.insertscelta(nomeString);
                    break;
                case 7: 
                    d.cancella();
                    d.insertscelta(nomeString);
                    break;
                }
            }
        });


    return rootView;

    }
    private void CursorLoader(Cursor c) {
        // TODO Auto-generated method stub

    }
}