Android Fragment onClick按钮方法,应用程序停止工作

时间:2016-06-09 08:54:25

标签: android android-fragments navigation-drawer

您好我有一个导航抽屉,它是我的MainActivity(名称为activity_main.xml的布局)和一些片段,在我的一个片段(名为PrimaryFragment)中我有一个计算器(布局名为peimary_layout.xml)的问题是当我运行应用程序并单击任何计算器按钮时,应用程序停止工作,我收到此错误:

06-09 13:17:32.634 14244-14244/com.androidbelieve.drawerwithswipetabs E/AndroidRuntime: FATAL EXCEPTION: main
                                                                                    Process: com.androidbelieve.drawerwithswipetabs, PID: 14244
                                                                                    java.lang.IllegalStateException: Could not find method clickedBtn8(View) in a parent or ancestor Context for android:onClick attribute defined on view class android.support.v7.widget.AppCompatButton with id 'eightBtn'
                                                                                        at android.view.View$DeclaredOnClickListener.resolveMethod(View.java:4767)
                                                                                        at android.view.View$DeclaredOnClickListener.onClick(View.java:4731)
                                                                                        at android.view.View.performClick(View.java:5697)
                                                                                        at android.widget.TextView.performClick(TextView.java:10815)
                                                                                        at android.view.View$PerformClick.run(View.java:22526)
                                                                                        at android.os.Handler.handleCallback(Handler.java:739)
                                                                                        at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                                        at android.os.Looper.loop(Looper.java:158)
                                                                                        at android.app.ActivityThread.main(ActivityThread.java:7229)
                                                                                        at java.lang.reflect.Method.invoke(Native Method)
                                                                                        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
                                                                                        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)

这是包含计算器的片段:

public class PrimaryFragment extends Fragment  {

    public String str ="";
    Character op = 'q';
    double i,num,numtemp;
    EditText showResult;
    Button x2,x3;
@Nullable
    @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View v= inflater.inflate(R.layout.primary_layout,container,false);
    x2=(Button)v.findViewById (R.id.btnX2);
    x2.setText(Html.fromHtml(getResources().getString(R.string.X2)));
    showResult = (EditText)v.findViewById(R.id.display);
    return v;
}
    public void clickedBtn1(View v){
        insert("1");

    }

    public void clickedBtn2(View v){
        insert("2");

    }
    public void clickedBtn3(View v){
        insert("3");

    }
    public void clickedBtn4(View v){
        insert("4");

    }
    public void clickedBtn5(View v){
        insert("5");

    }
    public void clickedBtn6(View v){
        insert("6");
    }
    public void clickedBtn7(View v){
        insert("7");

    }
    public void clickedBtn8(View v){
        insert("8");

    }
    public void clickedBtn9(View v){
        insert("9");

    }
    public void clickedBtn0(View v){
        insert("0");

    }
    public void clickedBtndot(View v){
        insert(".");

    }


    public void clickedtan(View v){
        showResult.setText("tan");
        op='T';
      Toast.makeText(getActivity().getApplicationContext(),"tan",Toast.LENGTH_SHORT).show();

    }
    public void clickedSin(View v){
        showResult.setText("sin");
        op='S';
       Toast.makeText(getActivity().getApplicationContext(),"Sin",Toast.LENGTH_SHORT).show();

    }
    public void clickedCos(View v){
        showResult.setText("Cos");
        op='C';
        // Toast.makeText(getApplicationContext(),"Cos",Toast.LENGTH_SHORT).show();

    }
    public void clickedSqrt(View v){
        showResult.setText("√");
        op='√';
        //Toast.makeText(getApplicationContext(),"√",Toast.LENGTH_SHORT).show();

    }
    public void clickedBtnx2(View v){
        perform();
        op = 'X';

    }
    public void clickedBtnlog(View v){

        op = 'L';

    }

    public void clickedBtnplus(View v){
        perform();
        op = '+';

    }

    public void clickedMinus(View v){
        perform();
        op = '-';

    }
    public void clickedBtnDiv(View v){
        perform();
        op = '/';

    }
    public void clickedBtnMul(View v){
        perform();
        op = '*';

    }
    public void clickedBtnequal(View v){
        calculate();

    }

    public void clickedBtnClear(View v){
        reset();
    }


    private void reset() {
        // TODO Auto-generated method stub
        str ="";
        op ='q';
        num = 0;
        numtemp = 0;
        showResult.setText("");
    }
    public void insert(String j) {
        // TODO Auto-generated method stub

        str = str+j;

        num = Double.valueOf(str);

        showResult.setText(str);

    }
    private void perform() {
        // TODO Auto-generated method stub
        str = "";
        numtemp = num;
    }
    private void calculate() {
        // TODO Auto-generated method stub
        if(op == '+')
            num = numtemp+num;
        else if(op == '-')
            num = numtemp-num;
        else if(op == '/')
            num = numtemp/num;
        else if(op == '*')
            num = numtemp*num;
        else  if(op=='C')
        {
            perform();

            num=Math.cos(Math.toRadians(numtemp));

        }
        else  if(op=='S')
        {
            perform();

            num=Math.sin(Math.toRadians(numtemp));

        }
        else  if(op=='T')
        {
            perform();

            num=Math.tan(Math.toRadians(numtemp));

        }

        else  if(op=='√')
        {
            perform();

            num=Math.sqrt(numtemp);

        }
        else  if(op=='X')
        {
            num=numtemp*numtemp;

        }
        else  if(op=='L')
        {
            perform();
            num=Math.log(numtemp);

        }
        // showResult.setText("Cos(" + numtemp + ")");
        showResult.setText(String.valueOf(num).toString());
    }

}

这是我的MainActivity

public class MainActivity extends AppCompatActivity{
DrawerLayout mDrawerLayout;
NavigationView mNavigationView;
FragmentManager mFragmentManager;
FragmentTransaction mFragmentTransaction;



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

    /**
     *Setup the DrawerLayout and NavigationView
     */

         mDrawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
         mNavigationView = (NavigationView) findViewById(R.id.shitstuff) ;

    /**
     * Lets inflate the very first fragment
     * Here , we are inflating the TabFragment as the first Fragment
     */

         mFragmentManager = getSupportFragmentManager();
         mFragmentTransaction = mFragmentManager.beginTransaction();
         mFragmentTransaction.replace(R.id.containerView,new TabFragment()).commit();
    /**
     * Setup click events on the Navigation View Items.
     */

         mNavigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
         @Override
         public boolean onNavigationItemSelected(MenuItem menuItem) {
            mDrawerLayout.closeDrawers();



             if (menuItem.getItemId() == R.id.nav_item_sent) {
                 FragmentTransaction fragmentTransaction = mFragmentManager.beginTransaction();
                 fragmentTransaction.replace(R.id.containerView,new SentFragment()).commit();

             }

            if (menuItem.getItemId() == R.id.nav_item_inbox) {
                FragmentTransaction xfragmentTransaction = mFragmentManager.beginTransaction();
                xfragmentTransaction.replace(R.id.containerView,new TabFragment()).commit();
            }

             return false;
        }

    });

    /**
     * Setup Drawer Toggle of the Toolbar
     */

            android.support.v7.widget.Toolbar toolbar = (android.support.v7.widget.Toolbar) findViewById(R.id.toolbar);
            ActionBarDrawerToggle mDrawerToggle = new ActionBarDrawerToggle(this,mDrawerLayout, toolbar,R.string.app_name,
            R.string.app_name);

            mDrawerLayout.setDrawerListener(mDrawerToggle);
mDrawerToggle.syncState();

    }
}

请帮忙,我该怎么办?

2 个答案:

答案 0 :(得分:0)

我猜您正在设置属性android:onClick="clickedBtn8"。如果是这样,请查看此answer

您需要在活动中声明方法public void clickedBtn8(View v) {...}而不是片段。如果您想在用户单击按钮后在片段中执行某些操作,请从活动中调用片段方法,或者将onclicklistener添加到按钮,如下所示:

Button btn8 = (Button) v.findViewById(R.id.btn8); //or whatever your id is
btn8.setOnClickListener(this);

让您的片段实现View.OnClickListener并实现此方法:

public void onClick(View v) {
  // do something when the button is clicked
}

答案 1 :(得分:0)

您已定义 android:onClick XML参数,但您错过了一些步骤。 在此处阅读更多相关信息:https://stackoverflow.com/a/10232111/3546306