简体   繁体   中英

How can I use my fragment method?

I am trying to make an app built up of multiple apps that I created. This app(My_App_Show) has a navigation drawer that holds the possible app fragments. Once one of the items in the drawer is clicked it will inflate the corresponding fragment into the main activity placeHolder. Once the view is present I can't get any of the functionality to work.

public class MyAppShowActivity extends AppCompatActivity implements NavigationDrawerFragment.NavigationDrawerCallbacks {

/**
 * Fragment managing the behaviors, interactions and presentation of the navigation drawer.
 */
private NavigationDrawerFragment mNavigationDrawerFragment;
/**
 * Used to store the last screen title. For use in {@link #restoreActionBar()}.
 */
private CharSequence mTitle;

protected static int frag = 0;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_my_app_show);

    mNavigationDrawerFragment = (NavigationDrawerFragment) getSupportFragmentManager().findFragmentById(R.id.navigation_drawer);
    mTitle = getTitle();

    // Set up the drawer.
    mNavigationDrawerFragment.setUp(R.id.navigation_drawer, (DrawerLayout) findViewById(R.id.drawer_layout));

}

@Override
public void onNavigationDrawerItemSelected(int position) {
    // update the main content by replacing fragments
    FragmentManager fragmentManager = getSupportFragmentManager();
    fragmentManager.beginTransaction().replace(R.id.container, PlaceholderFragment.newInstance(position)).commit();
}

public void onSectionAttached(int number) {
    switch (number) {
        case 0:
            frag = 0;
            mTitle = getString(R.string.title_section0);
        case 1:
            frag = 1;
            mTitle = getString(R.string.title_section1);
            break;
        case 2:
            frag = 2;
            mTitle = getString(R.string.title_section2);
            break;
        case 3:
            frag = 3;
            mTitle = getString(R.string.title_section3);
            break;
        case 4:
            frag = 4;
            mTitle = getString(R.string.title_section4);
            break;
        case 5:
            frag = 5;
            mTitle = getString(R.string.title_section5);
            break;
    }
}

public void restoreActionBar() {
    ActionBar actionBar = getSupportActionBar();
    actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
    actionBar.setDisplayShowTitleEnabled(true);
    actionBar.setTitle(mTitle);
}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
    if (!mNavigationDrawerFragment.isDrawerOpen()) {
        // Only show items in the action bar relevant to this screen
        // if the drawer is not showing. Otherwise, let the drawer
        // decide what to show in the action bar.
        getMenuInflater().inflate(R.menu.my_app_show, menu);
        restoreActionBar();
        return true;
    }
    return super.onCreateOptionsMenu(menu);
}

@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);
}

/**
 * A placeholder fragment containing a simple view.
 */
public static class PlaceholderFragment extends Fragment {
    /**
     * The fragment argument representing the section number for this
     * fragment.
     */
    private static final String ARG_SECTION_NUMBER = "section_number";

    /**
     * Returns a new instance of this fragment for the given section
     * number.
     */
    public static PlaceholderFragment newInstance(int sectionNumber) {
        PlaceholderFragment fragment = new PlaceholderFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_SECTION_NUMBER, sectionNumber);
        fragment.setArguments(args);
        return fragment;
    }

    public PlaceholderFragment() {
    }

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

        View view = null;

        switch (frag) {
            case 1:
                view = inflater.inflate(R.layout.fragment_activity_my, container, false);
                break;
            case 2:
                view = inflater.inflate(R.layout.fragment_tic_tac_toe, container, false);
                break;
            case 3:
                view = inflater.inflate(R.layout.fragment_d_side_main, container, false);
                break;
            case 4:

                break;
            case 5:
                view = inflater.inflate(R.layout.fragment_gestures, container, false);
                break;

        }

        return view;
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        ((MyAppShowActivity) activity).onSectionAttached(getArguments().getInt(ARG_SECTION_NUMBER));
    }
}

This is my main activity and the following is an example of my first "app" I'm trying to turn into an fragment to work with my new App:

public class MyActivity extends Fragment {

public final static String EXTRA_MESSAGE = "com.mycompany.myfirstapp.MESSAGE";

private OnFragmentInteractionListener mListener;
protected ArrayAdapter adp;

public MyActivity() {
    // Required empty public constructor
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    ArrayList<OnFragmentInteractionListener> things = new ArrayList<>();
    adp = new ArrayAdapter(this.getActivity(), things.size());
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    return inflater.inflate(R.layout.fragment_activity_my, container, false);
}

@Override
public void onViewCreated(View view, Bundle savedInstanceState){
    ListView lv = (ListView) view.findViewById(R.id.navigation_drawer);
    lv.setAdapter(adp);
}

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
}

/** Called when the user clicks the Send button */
public void sendMessage(View view) {
    Intent intent = new Intent(this.getActivity(), DisplayMessageActivity.class);
    EditText editText = (EditText)this.getActivity().findViewById(R.id.edit_message);
    String message = editText.getText().toString();
    intent.putExtra(EXTRA_MESSAGE, message);
    getActivity().startActivity(intent);
}

public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    this.getActivity().getMenuInflater().inflate(R.menu.menu_my, 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);
}

// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
    if (mListener != null) {
        mListener.onFragmentInteraction(uri);
    }
}

@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);
    try {
        mListener = (OnFragmentInteractionListener) activity;
    } catch (ClassCastException e) {
        throw new ClassCastException(activity.toString()
                + " must implement OnFragmentInteractionListener");
    }
}

@Override
public void onDetach() {
    super.onDetach();
    mListener = null;
}

/**
 * This interface must be implemented by activities that contain this
 * fragment to allow an interaction in this fragment to be communicated
 * to the activity and potentially other fragments contained in that
 * activity.
 * <p/>
 * See the Android Training lesson <a href=
 * "http://developer.android.com/training/basics/fragments/communicating.html"
 * >Communicating with Other Fragments</a> for more information.
 */
public interface OnFragmentInteractionListener {
    public void onFragmentInteraction(Uri uri);
}

When I run the code everything works until I type a message in the edit text box and then hit send message button. The error pops saying; "Could not find method sendMessage(View) in a parent or ancestor Context for android:onClick attribute defined on view class android.support.v7.widget.AppCompatButton".

11-08 13:13:40.602  25322-25322/com.example.darnell.my_app_show E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.darnell.my_app_show, PID: 25322
java.lang.IllegalStateException: Could not find method sendMessage(View) in a parent or ancestor Context for android:onClick attribute defined on view class android.support.v7.widget.AppCompatButton
        at android.support.v7.internal.app.AppCompatViewInflater$DeclaredOnClickListener.resolveMethod(AppCompatViewInflater.java:310)
        at android.support.v7.internal.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:269)
        at android.view.View.performClick(View.java:4764)
        at android.view.View$PerformClick.run(View.java:19833)
        at android.os.Handler.handleCallback(Handler.java:739)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:135)
        at android.app.ActivityThread.main(ActivityThread.java:5290)
        at java.lang.reflect.Method.invoke(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:372)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:908)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:703)

Can anyone tell me what I need to do to get my fragments functional?

Judging by the error you described, you called sendMessage passing a View parameter. However, the sendMessage() method in your code does not accept any parameters.

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