简单介绍下我的问题:
就是我在fragment_main.xml下写了一个算两个数的加减法,代码如下:
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/my_edit_1"
android:text="100"
android:inputType="numberDecimal"
/>
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/my_edit_2"
android:text="200"
android:inputType="numberDecimal"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/my_text1"
android:textSize = "20sp"
android:textColor ="#0000FF"
android:text = "= "
/>
<LinearLayout
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/my_button_add"
android:text="加(+)"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/my_button_sub"
android:text="减(-)"
/>
</LinearLayout>
后来在MainActivity里面添加响应:
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
TextView text1;
EditText tEdit_1,tEdit_2;
Button buttonAdd,buttonSub,buttonMuti,buttonDiv;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
text1=(TextView)rootView.findViewById(R.id.my_text1);
tEdit_1 = (EditText)rootView.findViewById(R.id.my_edit_1);
tEdit_2 = (EditText)rootView.findViewById(R.id.my_edit_2);
buttonAdd = (Button)rootView.findViewById(R.id.my_button_add);
buttonSub = (Button)rootView.findViewById(R.id.my_button_sub);
buttonAdd.setOnClickListener( (OnClickListener) this);
buttonSub.setOnClickListener((OnClickListener) this);
return rootView;
}
public void onClick(View view) {
String s1=tEdit_1.getText().toString();
String s2=tEdit_2.getText().toString();
if(view==buttonAdd) {
computer(s1,s2,'+');
}
if(view==buttonSub) {
computer(s1,s2,'-');
}
}
void computer(String s1,String s2,char op) {
double n1=1,n2=1,result=1;
n1 =Double.parseDouble(s1);
n2 =Double.parseDouble(s2);
switch(op) {
case '+': result = n1+n2;
break;
case '-': result = n1-n2;
break;
}
text1.setText("="+result);
}
}