简体   繁体   中英

Can't get To Do Activity to work in a fragment

sorry I'm fairly new to android so I seem to keep getting stuck on the simplest things.

I had two projects I had completed for a class. One was a simple To Do List and another that allowed different fragments to be used depending on whether you are in portrait or landscape mode. both worked but when trying to combine the two I get an error when put my To Do activity in the fragment if I extend Fragment (findByViews and setContentView dont work.

I can replace Fragment with FragmentActivity which fixes this but then my MainActivity.java's fragmentTransaction.replace(android.R.id.content, pm_fragment); gets an error saying: "replace (int, android.app.Fragment) in FragmentTransaction cannot be applied to (int, com.android.MyFragmentsTodo.PM_Fragment)"

Can anyone tell me what I can do to make this work? I have a test tomorrow and I'm worried the lecturer might want us to mix an activity with fragments. Any help would be greatly appreciated.

MainActivity.java

    package com.android.myfragmentstodo;

import android.app.Activity;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.res.Configuration;
import android.support.v4.app.FragmentActivity;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;


public class MainActivity extends ActionBarActivity{

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

        Configuration config = getResources().getConfiguration();

        FragmentManager fragmentManager = getFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

        //check device orientation and act upon it
        if(config.orientation == Configuration.ORIENTATION_LANDSCAPE){
            // If orientation is landscape then
            LM_Fragment ls_fragment = new LM_Fragment();
            fragmentTransaction.replace(android.R.id.content, ls_fragment);

        }else{
            // If orientation is portrait then
            PM_Fragment pm_fragment = new PM_Fragment();
            fragmentTransaction.replace(android.R.id.content, pm_fragment);
        }
        //apply (commit) the changes
        fragmentTransaction.commit();

    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

PM_Fragment.java

    package com.android.myfragmentstodo;

        import android.app.Activity;

        import android.app.Fragment;
        import android.os.Bundle;


        import android.support.v4.app.FragmentActivity;
        import android.support.v7.app.ActionBarActivity;
        import android.view.LayoutInflater;
        import android.view.Menu;
        import android.view.MenuItem;
        import android.view.View;
        import android.view.ViewGroup;
        import android.widget.AdapterView;
        import android.widget.ArrayAdapter;
        import android.widget.Button;
        import android.widget.EditText;
        import android.widget.ListView;
        import android.widget.Toast;

        import java.util.ArrayList;

/**
 * Created by Malan on 4/20/2015.
 */
public class PM_Fragment extends android.support.v4.app.Fragment {

    private ArrayList<String> items;
    private ArrayAdapter<String> adapter;
    private ListView listView;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedinstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        listView = (ListView) findViewById(R.id.todoItems);
        items = new ArrayList<String>();
        adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, items);

        listView.setAdapter(adapter);


        Button button = (Button) findViewById(R.id.btnAddItem);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                EditText editText = (EditText) findViewById(R.id.todoEdit);
                String itemText = editText.getText().toString();
                adapter.add(itemText);
                editText.setText("");
                Toast toast = Toast.makeText(getApplicationContext(), "Item Added", Toast.LENGTH_SHORT);
                toast.show();
            }
        });

        setupListViewListener();

        return inflater.inflate(R.layout.lm_fragment, container, false);
    }

    private void setupListViewListener() {
        listView.setOnItemLongClickListener(
                new AdapterView.OnItemLongClickListener(){
                    @Override
                    public boolean onItemLongClick(AdapterView<?> av,
                                                   View item, int pos, long id){
                        items.remove(pos);
                        adapter.notifyDataSetChanged();
                        return true;
                    }
                });
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    public void AddItem(View view) {
        EditText editText = (EditText) findViewById(R.id.todoEdit);
        String itemText = editText.getText().toString();
        adapter.add(itemText);
        editText.setText("");
    }
}

OK i have figured out how to fix the issue. One must keep extending Fragment but when doing using findViewById one must use:

rootView = inflater.inflate(R.layout.pm_fragment, container, false);

and then precede all findViewById's with rootView like this:

listView = (ListView) rootView.findViewById(R.id.todoItems);

Whenever "this" is used instead use "getActivity()" for example:

adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, items);

when using getApplicationContext you must use getActivity().getApplicationContext() for example:

Toast toast = Toast.makeText(getActivity().getApplicationContext(), "Item Added", Toast.LENGTH_SHORT);

in the end my PM_Fragment is altered to look like this: PM_Fragment.java

    package com.android.myfragmentstodo;




        import android.app.Fragment;
        import android.os.Bundle;


        import android.view.LayoutInflater;
        import android.view.Menu;
        import android.view.MenuItem;
        import android.view.View;
        import android.view.ViewGroup;
        import android.widget.AdapterView;
        import android.widget.ArrayAdapter;
        import android.widget.Button;
        import android.widget.EditText;
        import android.widget.ListView;
        import android.widget.Toast;

        import java.util.ArrayList;

/**
 * Created by Malan on 4/20/2015.
 */
public class PM_Fragment extends Fragment {

    private ArrayList<String> items;
    private ArrayAdapter<String> adapter;
    private ListView listView;
    View rootView;


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

        rootView = inflater.inflate(R.layout.pm_fragment, container, false);


        listView = (ListView) rootView.findViewById(R.id.todoItems);
        items = new ArrayList<String>();
        adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, items);

        listView.setAdapter(adapter);


        Button button = (Button) rootView.findViewById(R.id.btnAddItem);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                EditText editText = (EditText) rootView.findViewById(R.id.todoEdit);
                String itemText = editText.getText().toString();
                adapter.add(itemText);
                editText.setText("");
                Toast toast = Toast.makeText(getActivity().getApplicationContext(), "Item Added", Toast.LENGTH_SHORT);
                toast.show();
            }
        });

        setupListViewListener();

        return rootView;
    }

    private void setupListViewListener() {
        listView.setOnItemLongClickListener(
                new AdapterView.OnItemLongClickListener(){
                    @Override
                    public boolean onItemLongClick(AdapterView<?> av,
                                                   View item, int pos, long id){
                        items.remove(pos);
                        adapter.notifyDataSetChanged();
                        return true;
                    }
                });
    }




    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    public void AddItem(View view) {
        EditText editText = (EditText) rootView.findViewById(R.id.todoEdit);
        String itemText = editText.getText().toString();
        adapter.add(itemText);
        editText.setText("");
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM