如何将Activity转换为Fragment

时间:2014-04-10 01:19:34

标签: android android-fragments android-activity

我遇到了一些困难

  • 我不知道如何为我想在Fragment中使用的listview初始化我的数组适配器
  • 我不知道如何管理操作栏中的选项菜单

片段类

public class FragmentFour extends Fragment {

    ImageView ivIcon;
    TextView tvItemName;

    public static final String IMAGE_RESOURCE_ID = "iconResourceID";
    public static final String ITEM_NAME = "itemName";

    ListView exerciseList;
    ExerciseAdapter exercise_ArrayAdapter;
    ExerciseDatabase exerciseDatabase, db;
    Cursor C;
    String eID, eTitle, eLength, eDate, eTime;
    String APPTAG = "Exercise Tracker ExpenseHistory: ";
    Integer exerciseID_int;
    ArrayList exerciseID_Array, exerciseTitle_Array, exerciseLength_Array, exerciseDate_Array, exerciseTime_Array;

    public FragmentFour()
    {

    }

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

        //SET CUSTOM ADAPTER FOR LISTVIEW
        exerciseList.setAdapter(exercise_ArrayAdapter);
        registerForContextMenu(exerciseList);

        // READING A DB
        ExerciseDatabase exerciseDatabase = new ExerciseDatabase(getActivity());
        SQLiteDatabase readableDB = exerciseDatabase.getReadableDatabase();
        C = readableDB.query("ExerciseTable", new String[] { "_ID", "EXERCISE", "DURATION", "DATE", "TIME"},
                null, null, null, null, "DATE ASC");

        if (C == null || !C.moveToFirst())
        {

            view = inflater.inflate(R.layout.empty_view, null);

        }
        else
        {
            do
            {
                String exerciseID_String = "";
                String exerciseTitle_String = "";
                String exerciseLength_String = "";
                String exerciseDate_String = "";
                String exerciseTime_String = "";

                // Get the data from the database
                exerciseID_int = C.getInt(C.getColumnIndex("_ID"));
                eTitle = C.getString(C.getColumnIndex("EXERCISE"));
                eLength = C.getString(C.getColumnIndex("DURATION"));
                eDate = C.getString(C.getColumnIndex("DATE"));
                eTime = C.getString(C.getColumnIndex("TIME"));

                eID = exerciseID_int.toString();

                //Build strings of each record to then be set to the listview
                exerciseID_String = eID;
                exerciseTitle_String = eTitle;
                exerciseLength_String = eLength;
                exerciseDate_String = eDate;
                exerciseTime_String = eTime;

                //Add the new strings to the corresponding array
                exerciseID_Array.add(exerciseID_String);
                exerciseTitle_Array.add(exerciseTitle_String);
                exerciseLength_Array.add(exerciseLength_String);
                exerciseDate_Array.add(exerciseDate_String);
                exerciseTime_Array.add(exerciseTime_String);
            }
            while (C.moveToNext());
        }

        // Close cursor and database to avoid memory leaks
        C.close();
        readableDB.close();

        // Tell adapter there is new data so update the listview accordingly
        exercise_ArrayAdapter.notifyDataSetChanged();

        return view;


    }

    // Initalizes the variables used in the activity
    public void initializeVariables(View v) {

        exerciseList = (ListView) v.findViewById(R.id.exerciseHistory_listview);
        exerciseID_Array = new ArrayList();
        exerciseTitle_Array = new ArrayList();
        exerciseLength_Array = new ArrayList();
        exerciseDate_Array = new ArrayList();
        exerciseTime_Array = new ArrayList();

        exercise_ArrayAdapter = new ExerciseAdapter(this, R.layout.exercise_item_row, exerciseID_Array, exerciseTitle_Array,
                exerciseLength_Array, exerciseDate_Array, exerciseTime_Array);

    }

    // Create a menu
    public boolean onCreateOptionsMenu(android.view.Menu menu) {
        getMenuInflater().inflate(R.menu.history_menu, menu);
        return true;
    }

    // If the add icon is selected, the ExerciseEntry activity appears, allowing the user to add data to the database
    public boolean onOptionsItemSelected(MenuItem item)
    {
        switch(item.getItemId())
        {
            case R.id.ic_add:
                Intent openExerciseEntry = new Intent(this, ExerciseEntry.class);
                startActivity(openExerciseEntry);
                finish();
                return true;

            default:
                return super.onOptionsItemSelected(item);
        }
    }
}

活动类

public class ExpenseHistory extends Activity {

    ListView expenseList;
    CustomAdapter expense_ArrayAdapter;
    ExpenseDatabase eDatabase;
    Cursor C;
    String eID, eTitle, eAmount, eDate, eTime;
    String APPTAG = "Expense Tracker ExpenseHistory: ";
    Integer expenseID_int;
    ArrayList expenseID_Array, expenseTitle_Array, expenseAmount_Array, expenseDate_Array, expenseTime_Array;
    ExpenseDatabase db;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // Set the layout to the activity_expense_history layout file
        setContentView(R.layout.activity_expense_history);

        // Initalize the variables used in this activity
        initializeVariables();

        // Record in the logcat when the application is Created
        Log.v(APPTAG, "onCreate() called");

        //SET CUSTOM ADAPTER FOR LISTVIEW
        expenseList.setAdapter(expense_ArrayAdapter);
        expenseList.setEmptyView(findViewById(R.id.empty));
        registerForContextMenu(expenseList);

        // READING A DB
        SQLiteDatabase readableDB = eDatabase.getReadableDatabase();
        C = readableDB.query("ExpenseTable", new String[] { "_ID", "EXPENSETITLE", "AMOUNT", "EXPENSEDATE", "EXPENSETIME"},
                null, null, null, null, "EXPENSEDATE ASC");

        if (C == null || !C.moveToFirst())
        {

        }
        else
        {
            do
            {
                String expenseID_String = "";
                String expenseTitle_String = "";
                String expenseAmount_String = "";
                String expenseDate_String = "";
                String expenseTime_String = "";

                // Get the data from the database
                expenseID_int = C.getInt(C.getColumnIndex("_ID"));
                eTitle = C.getString(C.getColumnIndex("EXPENSETITLE"));
                eAmount = C.getString(C.getColumnIndex("AMOUNT"));
                eDate = C.getString(C.getColumnIndex("EXPENSEDATE"));
                eTime = C.getString(C.getColumnIndex("EXPENSETIME"));

                eID = expenseID_int.toString();

                //Build strings of each record to then be set to the listview
                expenseID_String = eID;
                expenseTitle_String = eTitle;
                expenseAmount_String = eAmount;
                expenseDate_String = eDate;
                expenseTime_String = eTime;

                //Add the new strings to the corresponding array
                expenseID_Array.add(expenseID_String);
                expenseTitle_Array.add(expenseTitle_String);
                expenseAmount_Array.add(expenseAmount_String);
                expenseDate_Array.add(expenseDate_String);
                expenseTime_Array.add(expenseTime_String);
            }
            while (C.moveToNext());
        }

        // Close cursor and database to avoid memory leaks
        C.close();
        readableDB.close();

        // Tell adapter there is new data so update the listview accordingly
        expense_ArrayAdapter.notifyDataSetChanged();

    }

    // Initalizes the variables used in the activity
    private void initializeVariables() {

        expenseList = (ListView) findViewById(R.id.expenseHistory_listview);
        eDatabase = new ExpenseDatabase(this);
        expenseID_Array = new ArrayList();
        expenseTitle_Array = new ArrayList();
        expenseAmount_Array = new ArrayList();
        expenseDate_Array = new ArrayList();
        expenseTime_Array = new ArrayList();

        expense_ArrayAdapter = new CustomAdapter(this, R.layout.item_row, expenseID_Array, expenseTitle_Array,
                expenseAmount_Array, expenseDate_Array, expenseTime_Array);

    }

    // Creates a context menu for the ExpenseHistory class which allows a pop up box to appear when something happens
    @Override
    public void onCreateContextMenu(ContextMenu menu, View v,
                                    ContextMenu.ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo);
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.expense_context, menu);
    }

    // When an item is selected, an options box appears
    @Override
    public boolean onContextItemSelected(MenuItem item) {
        AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
        int position = info.position;
        switch (item.getItemId()) {

            case R.id.delete:
            {
                String temp = expenseTitle_Array.get(position).toString();

                expenseID_Array.remove(position);
                expenseTitle_Array.remove(position);
                expenseAmount_Array.remove(position);
                expenseDate_Array.remove(position);
                expenseTime_Array.remove(position);

                db = new ExpenseDatabase(this);

                SQLiteDatabase readableDB = db.getWritableDatabase();
                readableDB.delete("ExpenseTable", "EXPENSETITLE=?",
                        new String[]{temp});

                expense_ArrayAdapter.notifyDataSetChanged();
            }
            return true;

            default:
                return super.onContextItemSelected(item);
        }
    }

    // Create a menu
    public boolean onCreateOptionsMenu(android.view.Menu menu) {
        getMenuInflater().inflate(R.menu.history_menu, menu);
        return true;
    }

    // If the back icon is selected, the user is returned to the MainActivity
    public boolean onOptionsItemSelected(MenuItem item)
    {
        switch(item.getItemId())
        {
            case R.id.ic_back:
                Intent openMainActivity = new Intent(this, MainActivity.class);
                startActivity(openMainActivity);
                finish();
                return true;

            default:
                return super.onOptionsItemSelected(item);
        }
    }

感谢任何帮助。

2 个答案:

答案 0 :(得分:1)

我发现当我学习修改活动以使用片段时,在很多情况下,添加“getActivitiy()。[与在activty中相同的代码]将是一个很好的第一件事,如果那样没有用,很多时候Eclipse都会建议修复。

答案 1 :(得分:0)

对于选项菜单,您需要覆盖片段中的onCreate()并致电setHasOptionsMenu()