-1

我有一个布局中的按钮,该按钮设置为 On Click = calculateClickHandler 单击该按钮时,应用程序将关闭并显示以下 logcat。我不确定这是否是因为我试图在 Fragment 中执行此操作并且应该在主要活动中执行此操作?

任何帮助深表感谢。

10-23 15:59:30.929: E/AndroidRuntime(22388): FATAL EXCEPTION: main
10-23 15:59:30.929: E/AndroidRuntime(22388): java.lang.IllegalStateException: Could not find a method calculateClickHandler(View) in the activity class com.HealthKicks.bodystats.admob.MainActivity for onClick handler on view class android.widget.Button with id 'calculatewaist'
10-23 15:59:30.929: E/AndroidRuntime(22388):    at android.view.View$1.onClick(View.java:3620)
10-23 15:59:30.929: E/AndroidRuntime(22388):    at android.view.View.performClick(View.java:4240)
10-23 15:59:30.929: E/AndroidRuntime(22388):    at android.view.View$PerformClick.run(View.java:17721)
10-23 15:59:30.929: E/AndroidRuntime(22388):    at android.os.Handler.handleCallback(Handler.java:730)
10-23 15:59:30.929: E/AndroidRuntime(22388):    at android.os.Handler.dispatchMessage(Handler.java:92)
10-23 15:59:30.929: E/AndroidRuntime(22388):    at android.os.Looper.loop(Looper.java:137)
10-23 15:59:30.929: E/AndroidRuntime(22388):    at android.app.ActivityThread.main(ActivityThread.java:5103)
10-23 15:59:30.929: E/AndroidRuntime(22388):    at java.lang.reflect.Method.invokeNative(Native Method)
10-23 15:59:30.929: E/AndroidRuntime(22388):    at java.lang.reflect.Method.invoke(Method.java:525)
10-23 15:59:30.929: E/AndroidRuntime(22388):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
10-23 15:59:30.929: E/AndroidRuntime(22388):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
10-23 15:59:30.929: E/AndroidRuntime(22388):    at dalvik.system.NativeStart.main(Native Method)
10-23 15:59:30.929: E/AndroidRuntime(22388): Caused by: java.lang.NoSuchMethodException: calculateClickHandler [class android.view.View]
10-23 15:59:30.929: E/AndroidRuntime(22388):    at java.lang.Class.getConstructorOrMethod(Class.java:423)
10-23 15:59:30.929: E/AndroidRuntime(22388):    at java.lang.Class.getMethod(Class.java:787)
10-23 15:59:30.929: E/AndroidRuntime(22388):    at android.view.View$1.onClick(View.java:3613)
10-23 15:59:30.929: E/AndroidRuntime(22388):    ... 11 more

这是片段代码:

package com.HealthKicks.bodystats.admob;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.TextView;


public class DummySectionFragment1 extends Fragment {

    Button calculatewaist;
    EditText waist_edit_text1;
    RadioGroup gender_radio_group1;
    RadioButton gender_radio_male, gender_radio_female;
    Spinner waist_spinner;
    TextView ideal, high, veryhigh;
    String waist_unit, waist;

    public static final String ARG_SECTION_NUMBER = "section_number";

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

         // get the references to the widgets
        waist_spinner = (Spinner) rootView.findViewById(R.id.waist_spinner);
        waist_edit_text1 = (EditText) rootView.findViewById(R.id.waist_edit_text1);
        ideal = (TextView) rootView.findViewById(R.id.ideal);
        high = (TextView) rootView.findViewById(R.id.high);
        veryhigh = (TextView) rootView.findViewById(R.id.veryhigh);
        gender_radio_male = (RadioButton) rootView.findViewById(R.id.gender_radio_male);
        gender_radio_female = (RadioButton) rootView.findViewById(R.id.gender_radio_female);
        calculatewaist = (Button) rootView.findViewById(R.id.calculatewaist);

        return rootView;
    }

    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        calculateClickHandler(view);
    }



    void calculateClickHandler(View view) {
        // TODO Auto-generated method stub

        if (view.getId() == R.id.calculatewaist) {

        // Get the users values from the widget references
            waist_unit = waist_spinner.getSelectedItem().toString();
            float waist = Float.parseFloat(waist_edit_text1.getText().toString());

        // Convert Inches to CM
            if (waist_unit.equals("INCHES")) {
                waist = (float) (waist * 2.54);
                }

        // Interpret what Waist Circumference result means for male

                    if (waist < 94 && (gender_radio_male.isChecked())){
                   ideal.setTextColor(getResources().getColor(R.color.title_color));
                     } else if (waist < 103 && (gender_radio_male.isChecked())) {

                   high.setTextColor(getResources().getColor(R.color.title_color));
                     } else if (waist > 102 && (gender_radio_male.isChecked())) {

                   veryhigh.setTextColor(getResources().getColor(R.color.title_color));

                     }

             // Interpret what Waist Circumference result means for female

                    if (waist < 80 && (gender_radio_female.isChecked())) {
                   ideal.setTextColor(getResources().getColor(R.color.title_color));
                     } else if (waist < 89 && (gender_radio_female.isChecked())) {

                   high.setTextColor(getResources().getColor(R.color.title_color));
                     } else if (waist > 88 && (gender_radio_female.isChecked())) {

                   veryhigh.setTextColor(getResources().getColor(R.color.title_color));

                     }
        };
    }
}

和主要活动代码:

package com.HealthKicks.bodystats.admob;

import java.util.Locale;
import android.app.ActionBar;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.TextView;

public class MainActivity extends FragmentActivity implements
        ActionBar.TabListener {

    EditText waist_edit_text1;
    RadioGroup gender_radio_group1;
    RadioButton gender_radio_male, gender_radio_female;
    Spinner waist_spinner;
    TextView ideal, high, veryhigh;
    String waist_unit, waist;

    /**
     * The {@link android.support.v4.view.PagerAdapter} that will provide
     * fragments for each of the sections. We use a
     * {@link android.support.v4.app.FragmentPagerAdapter} derivative, which
     * will keep every loaded fragment in memory. If this becomes too memory
     * intensive, it may be best to switch to a
     * {@link android.support.v4.app.FragmentStatePagerAdapter}.
     */
    SectionsPagerAdapter mSectionsPagerAdapter;

    /**
     * The {@link ViewPager} that will host the section contents.
     */
    ViewPager mViewPager;

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

        // Set up the action bar.
        final ActionBar actionBar = getActionBar();
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

        // Create the adapter that will return a fragment for each of the three
        // primary sections of the app.
        mSectionsPagerAdapter = new SectionsPagerAdapter(
                getSupportFragmentManager());

        // Set up the ViewPager with the sections adapter.
        mViewPager = (ViewPager) findViewById(R.id.pager);
        mViewPager.setAdapter(mSectionsPagerAdapter);

        // When swiping between different sections, select the corresponding
        // tab. We can also use ActionBar.Tab#select() to do this if we have
        // a reference to the Tab.
        mViewPager
                .setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
                    @Override
                    public void onPageSelected(int position) {
                        actionBar.setSelectedNavigationItem(position);
                    }
                });

        // For each of the sections in the app, add a tab to the action bar.
        for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
            // Create a tab with text corresponding to the page title defined by
            // the adapter. Also specify this Activity object, which implements
            // the TabListener interface, as the callback (listener) for when
            // this tab is selected.
            actionBar.addTab(actionBar.newTab()
                    .setText(mSectionsPagerAdapter.getPageTitle(i))
                    .setTabListener(this));
        }
    }

    private final String TAG = "Main Activity";

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

    @Override
    public boolean onOptionsItemSelected(MenuItem item)
    {
        switch (item.getItemId())
        {
        case R.id.Refresh:
            Log.i(TAG, "Refresh Item Clicked");
            return true;
        }
        switch (item.getItemId())
        {
        case R.id.Info:
            Log.i(TAG, "Info Item Clicked");
            return true;

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

    @Override
    public void onTabSelected(ActionBar.Tab tab,
            FragmentTransaction fragmentTransaction) {
        // When the given tab is selected, switch to the corresponding page in
        // the ViewPager.
        mViewPager.setCurrentItem(tab.getPosition());
    }

    @Override
    public void onTabUnselected(ActionBar.Tab tab,
            FragmentTransaction fragmentTransaction) {
    }

    @Override
    public void onTabReselected(ActionBar.Tab tab,
            FragmentTransaction fragmentTransaction) {
    }

    /**
     * A {@link FragmentPagerAdapter} that returns a fragment corresponding to
     * one of the sections/tabs/pages.
     */
    public class SectionsPagerAdapter extends FragmentPagerAdapter {

        public SectionsPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            // getItem is called to instantiate the fragment for the given page.
            // Return a DummySectionFragment (defined as a static inner class
            // below) with the page number as its lone argument.
            switch (position) {
            case 0:
                Fragment fragment = new DummySectionFragment();
                Bundle args = new Bundle();
                args.putInt(DummySectionFragment.ARG_SECTION_NUMBER, position + 1);
                fragment.setArguments(args);
                return fragment;

              case 1:
                Fragment fragment1 = new DummySectionFragment1();
                Bundle args1 = new Bundle();
                args1.putInt(DummySectionFragment1.ARG_SECTION_NUMBER, position + 2);
                fragment1.setArguments(args1);
                return fragment1;

              case 2:

                 Fragment fragment2 = new DummySectionFragment2();
                 Bundle args2 = new Bundle();
                 args2.putInt(DummySectionFragment2.ARG_SECTION_NUMBER, position + 3);
                 fragment2.setArguments(args2);
                 return fragment2;

              case 3:

                     Fragment fragment3 = new DummySectionFragment3();
                     Bundle args3 = new Bundle();
                     args3.putInt(DummySectionFragment3.ARG_SECTION_NUMBER, position + 4);
                     fragment3.setArguments(args3);
                     return fragment3;

            default:
                return null;
            }
        }

        @Override
        public int getCount() {
            // Show 4 total pages.
            return 4;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            Locale l = Locale.getDefault();
            switch (position) {
            case 0:
                return getString(R.string.title_section1).toUpperCase(l);
            case 1:
                return getString(R.string.title_section2).toUpperCase(l);
            case 2:
                return getString(R.string.title_section3).toUpperCase(l);
            case 3:
                return getString(R.string.title_section4).toUpperCase(l);
            }
            return null;
            }
    }
}
4

1 回答 1

2

java.lang.IllegalStateException: Could not find a method calculateClickHandler(View) in the activity class com.HealthKicks.bodystats.admob.MainActivity for onClick handler on view class android.widget.Button with id 'calculatewaist'"

这真的告诉你所有你需要知道的关于如何解决这个问题:
将方法放在 Activity 中

另一种选择是使用this answer中的说明,您可以在其中Fragment实施OnClickListener并使用此代码:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.fragment_start, container, false);
    Button b = (Button) v.findViewById(R.id.StartButton);
    b.setOnClickListener(this); // This is the important line here!
    return v;
}

@Override
public void onClick(View v) {
    switch (v.getId()) {
        case R.id.StartButton:
            ...
            break;
    }
}
于 2013-10-23T15:06:52.107 回答