我怎样才能使用我的片段方法?

时间:2015-11-08 19:54:57

标签: java android android-fragments

我正在尝试制作一个由我创建的多个应用构建的应用。这个应用程序(My_App_Show)有一个导航抽屉,可以保存可能的应用程序片段。单击抽屉中的一个项目后,它会将相应的片段膨胀到主要活动场所.Holder中。一旦视图出现,我就无法使用任何功能。

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

这是我的主要活动,以下是我的第一个" 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);
}

当我运行代码时,一切正常,直到我在编辑文本框中键入消息,然后点击发送消息按钮。错误弹出说; &#34;无法在父级或祖先语句中找到方法sendMessage(View)for android:在视图类android.support.v7.widget.AppCompatButton&#34;上定义的onClick属性。

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)

任何人都可以告诉我需要做些什么才能使我的碎片正常运行?

1 个答案:

答案 0 :(得分:0)

根据您描述的错误判断,您调用sendMessage传递View参数。但是,代码中的sendMessage()方法不接受任何参数。