2017-10-28 91 views
0

我想設置一個片段內的按鈕(R.id.addclick)的onclick方法。沒有錯誤,但每次啓動模擬器並按下按鈕時,它都會顯示「不幸,...已停止」。請給我一些建議。片段和onClick按鈕

first_layout XML:

Button 
     android:id="@+id/addclick" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_below="@+id/edit17" 
     android:layout_marginTop="16dp" 
     android:layout_toEndOf="@+id/textView32" 
     android:layout_toRightOf="@+id/textView32" 
     android:onClick="addclick" 
     android:text="submit" /> 

我的整個片段代碼:

package com.example.administrator.realrandd; 

import android.app.Fragment; 
import android.os.Bundle; 
import android.support.annotation.Nullable; 
import android.view.LayoutInflater; 
import android.view.View; 
import android.view.ViewGroup; 
import android.widget.Button; 
import android.widget.EditText; 
import android.widget.TextView; 

/** 
* Created by Administrator on 2017-10-28. 
*/ 
public class FirstLayout extends Fragment implements View.OnClickListener { 
    View v; 

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

     v = inflater.inflate(R.layout.first_layout, container, false); 

     Button b = (Button) v.findViewById(R.id.addclick); 
     b.setOnClickListener(this); 
     return v; 
    } 

    @Override 
    public void onClick(View v) { 
     switch (v.getId()) { 
      case R.id.addclick: 

       EditText number1 = (EditText)v.findViewById(R.id.edit1); 
       EditText number2 = (EditText)v.findViewById(R.id.edit2); 

       TextView result = (TextView)v.findViewById(R.id.Final); 

       int n1 = Integer.parseInt(number1.getText().toString()); 
       int n2 = Integer.parseInt(number2.getText().toString()); 

       result.setText(Integer.toString(n1+n2)); 



       break; 
     } 
    } 
} 
+0

刪除安卓的onClick =從你的XML 「添加點擊」 檢查。 如果您仍然收到任何錯誤,請分享日誌 – Araju

回答

1

不匹配的名字:您的佈局,你是指一個名爲方法

android:onClick="addclick" 

但在你的代碼中設置了一個名爲

public void onClick(View v) { 

而且......「添加點擊」方法!=「點擊」

有望使這兩個名字搭配你。


所以accordigly命名方法在你的代碼:

public void addclick(View v) { 
+2

先生,'android:onClick =「onClick」'不會在FRAGMENT –

+1

@IntelliJAmiya中糾正。謝謝你,先生。 –

0

我覺得下面的文本字段爲空。這就是空字符串不能轉換爲int的原因。

EditText number1 = (EditText)v.findViewById(R.id.edit1); 
EditText number2 = (EditText)v.findViewById(R.id.edit2); 

在這種情況下,如果你看一下日誌,你會發現像

Exception in thread "main" java.lang.NumberFormatException: For input string: "" 
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65) 
at java.lang.Integer.parseInt(Integer.java:504) 
at java.lang.Integer.parseInt(Integer.java:527) 

錯誤

+0

如果您在日誌中發現任何其他異常。請提供 – Zenith