嗨,我正在尝试计算像计算器这样的数字。如果我使用 Activity,则代码可以工作,但在 Sherlock Fragment 中不起作用。我使用 android:onClick=""。有人可以告诉我应该怎么做来实现这个代码。谢谢你。
代码 :
public class Calculate extends SherlockFragment {
private int resultspinner, inputnumber, totals;
private Spinner spinner;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
View rootView = inflater.inflate(R.layout.activity_summary,
container, false);
setSpinnerContent(rootView);
return rootView;
}
private void setSpinnerContent(View view)
{
spinner = (Spinner) view.findViewById( R.id.spinner );
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(getActivity()
.getBaseContext(),
R.array.pangkat_arrays, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter( adapter );
...
}
// showing a toast on selecting an item
//Toast.makeText(parent.getContext(), item, Toast.LENGTH_LONG).show();
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
}
public void startcalculate(View view) {
EditText ed_resultspinner = (EditText) getView().findViewById(R.id.EditText1);
EditText ed_input = (EditText) getView().findViewById(R.id.EditText2);
EditText ed_total = (EditText) getView().findViewById(R.id.EditText3);
try {
resultspinner = Integer.parseInt(ed_resultspinner.getText().toString());
inputnumber = Integer.parseInt(ed_input.getText().toString());
totals = resultspinner + inputnumber;
ed_total.setText(String.valueOf(totals));
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
<Spinner android:id="@+id/spinner1" android:layout_width="match_parent" android:layout_height="wrap_content" /> <EditText android:id="@+id/editText1" android:layout_width="match_parent" android:layout_height="wrap_content" android:ems="10" android:inputType="number" /> <EditText android:id="@+id/editText2" android:layout_width="match_parent" android:layout_height="wrap_content" android:ems="10" android:inputType="number" > <requestFocus /> </EditText> <EditText android:id="@+id/editText3" android:layout_width="match_parent" android:layout_height="wrap_content" android:ems="10" android:inputType="number" /> <Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:onClick="startcalculate" android:text="Button" />
错误
java.lang.IllegalStateException:在活动类 com.user.learing.MainActivity 中找不到方法 startcalculate(View) 用于视图类 android.widget.Button 上的 onClick 处理程序,ID 为“button1”