Android程序计算两个数字的总和

时间:2014-07-09 09:57:11

标签: java android

我编写了一个java程序来计算Android中两个数字的总和。应用程序运行但只要我点击计算就崩溃了。这是我在java android btw上的第一个程序..

XML是:     

<TextView
    android:id="@+id/section_label"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

<TextView
    android:id="@+id/textView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignTop="@+id/section_label"
    android:layout_centerHorizontal="true"
    android:text="CALCULATOR"
    android:textAppearance="?android:attr/textAppearanceLarge"
    android:textSize="32sp" />

<TextView
    android:id="@+id/textView3"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignLeft="@+id/textView1"
    android:layout_alignParentBottom="true"
    android:layout_marginBottom="62dp"
    android:layout_marginLeft="23dp"
    android:text="The Sum is :"
    android:textAppearance="?android:attr/textAppearanceMedium"
    android:textSize="18sp" />

<Button
    android:id="@+id/button1"
    style="?android:attr/buttonStyleSmall"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_above="@+id/textView3"
    android:layout_centerHorizontal="true"
    android:layout_marginBottom="64dp"
    android:onClick="OnButtonClick"
    android:text="Calculate" />

<EditText
    android:id="@+id/num2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_above="@+id/button1"
    android:layout_alignLeft="@+id/textView1"
    android:layout_marginBottom="33dp"
    android:ems="10"
    android:hint="enter second number" />

<EditText
    android:id="@+id/num1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_above="@+id/num2"
    android:layout_alignLeft="@+id/num2"
    android:layout_marginBottom="28dp"
    android:ems="10"
    android:hint="enter first number" >
</EditText>

<TextView
    android:id="@+id/textView2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_above="@+id/num2"
    android:layout_centerHorizontal="true"
    android:text="+"
    android:textAppearance="?android:attr/textAppearanceMedium" />

<TextView
    android:id="@+id/textView4"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignRight="@+id/num2"
    android:layout_alignTop="@+id/textView3"
    android:text="TextView" />

</RelativeLayout>

JAVA代码是:

package com.ezxample.zz;

import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends ActionBarActivity implements
    ActionBar.OnNavigationListener {

/**
 * The serialization (saved instance state) Bundle key representing the
 * current dropdown position.
 */
private static final String STATE_SELECTED_NAVIGATION_ITEM =     "selected_navigation_item";


public void onButtonClick(View v)
{ 
    int n1,n2,sum;
    EditText e1 = (EditText)findViewById(R.id.num1);
    EditText e2 = (EditText)findViewById(R.id.num2);
    TextView t1 = (TextView)findViewById(R.id.textView4);
    n1=Integer.parseInt(e1.getText().toString());
    n2=Integer.parseInt(e2.getText().toString());
    sum = n1 + n2;
    t1.setText(Integer.toString(sum));
}

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



    // Set up the action bar to show a dropdown list.
    final ActionBar actionBar = getSupportActionBar();
    actionBar.setDisplayShowTitleEnabled(false);
    actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);

    // Set up the dropdown list navigation in the action bar.
    actionBar.setListNavigationCallbacks(
    // Specify a SpinnerAdapter to populate the dropdown list.
            new ArrayAdapter<String>(actionBar.getThemedContext(),
                    android.R.layout.simple_list_item_1,
                    android.R.id.text1, new String[] {
                            getString(R.string.title_section1),
                            getString(R.string.title_section2),
                            getString(R.string.title_section3), }), this);
}

@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
    // Restore the previously serialized current dropdown position.
    if (savedInstanceState.containsKey(STATE_SELECTED_NAVIGATION_ITEM)) {
        getSupportActionBar().setSelectedNavigationItem(
                savedInstanceState.getInt(STATE_SELECTED_NAVIGATION_ITEM));
    }
}

@Override
public void onSaveInstanceState(Bundle outState) {
    // Serialize the current dropdown position.
    outState.putInt(STATE_SELECTED_NAVIGATION_ITEM, getSupportActionBar()
            .getSelectedNavigationIndex());
}

@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) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();
    if (id == R.id.action_settings) {
        return true;
    }
    return super.onOptionsItemSelected(item);
}

@Override
public boolean onNavigationItemSelected(int position, long id) {
    // When the given dropdown item is selected, show its contents in the
    // container view.
    getSupportFragmentManager()
            .beginTransaction()
            .replace(R.id.container,
                    PlaceholderFragment.newInstance(position + 1)).commit();
    return true;
}

/**
 * A placeholder fragment containing a simple view.
 */
public static class PlaceholderFragment extends Fragment {
    /**
     * The fragment argument representing the section number for this
     * fragment.
     */
    private static final String ARG_SECTION_NUMBER = "section_number";

    /**
     * Returns a new instance of this fragment for the given section number.
     */
    public static PlaceholderFragment newInstance(int sectionNumber) {
        PlaceholderFragment fragment = new PlaceholderFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_SECTION_NUMBER, sectionNumber);
        fragment.setArguments(args);
        return fragment;
    }

    public PlaceholderFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_main, container,
                false);
        TextView textView = (TextView) rootView
                .findViewById(R.id.section_label);
        textView.setText(Integer.toString(getArguments().getInt(
                ARG_SECTION_NUMBER)));
        return rootView;
    }
}

}

2 个答案:

答案 0 :(得分:4)

假设您的XML是activity_main.xml,替换

android:onClick="OnButtonClick"

with(参见拼写错误)

android:onClick="onButtonClick"

应解决问题。

答案 1 :(得分:2)

尝试替换您的活动代码。

public class MainActivity extends ActionBarActivity implements ActionBar.OnNavigationListener {

    /**
     * The serialization (saved instance state) Bundle key representing the
     * current dropdown position.
     */
    private static final String STATE_SELECTED_NAVIGATION_ITEM =     "selected_navigation_item";


    private EditText e1;
    private EditText e2;
    private TextView t1;
    private TextView textView;
    public void onButtonClick(View v)
    {
        if(v.getId() == R.id.button1) {
            boolean isValidate = true;
            if (e1.getText().toString().length() <= 0) {
                e1.setError("Value Required");
                isValidate = false;
            } 
            if (e2.getText().toString().length() <= 0) {
                e2.setError("Value Required");
                isValidate = false;
            }
            if (isValidate) {
                t1.setText(Integer.toString(Integer.parseInt(e1.getText().toString()) +  Integer.parseInt(e2.getText().toString())));
            }
        }
    }

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


        // Set up the action bar to show a dropdown list.
        final ActionBar actionBar = getSupportActionBar();
        actionBar.setDisplayShowTitleEnabled(false);
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);

        // Set up the dropdown list navigation in the action bar.
        actionBar.setListNavigationCallbacks(
                // Specify a SpinnerAdapter to populate the dropdown list.
                new ArrayAdapter<String>(actionBar.getThemedContext(),
                        android.R.layout.simple_list_item_1,
                        android.R.id.text1, new String[] {
                        getString(R.string.title_section1),
                        getString(R.string.title_section2),
                        getString(R.string.title_section3), }), this);
    }

    @Override
    public void onRestoreInstanceState(Bundle savedInstanceState) {
        // Restore the previously serialized current dropdown position.
        if (savedInstanceState.containsKey(STATE_SELECTED_NAVIGATION_ITEM)) {
            getSupportActionBar().setSelectedNavigationItem(savedInstanceState.getInt(STATE_SELECTED_NAVIGATION_ITEM));
        }
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        // Serialize the current dropdown position.
        outState.putInt(STATE_SELECTED_NAVIGATION_ITEM, getSupportActionBar()
                .getSelectedNavigationIndex());
    }

    @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) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public boolean onNavigationItemSelected(int position, long id) {
        // When the given dropdown item is selected, show its contents in the
        // container view.
        getSupportFragmentManager()
                .beginTransaction()
                .replace(R.id.container,PlaceholderFragment.newInstance(position + 1)).commit();
        return true;
    }

    /**
     * A placeholder fragment containing a simple view.
     */
    public static class PlaceholderFragment extends Fragment {
        /**
         * The fragment argument representing the section number for this
         * fragment.
         */
        private static final String ARG_SECTION_NUMBER = "section_number";

        /**
         * Returns a new instance of this fragment for the given section number.
         */
        public static PlaceholderFragment newInstance(int sectionNumber) {
            PlaceholderFragment fragment = new PlaceholderFragment();
            Bundle args = new Bundle();
            args.putInt(ARG_SECTION_NUMBER, sectionNumber);
            fragment.setArguments(args);
            return fragment;
        }

        public PlaceholderFragment() {
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_main, container, false);
            e1 = (EditText) rootView.findViewById(R.id.num1);
            e2 = (EditText) rootView.findViewById(R.id.num2);
            t1 = (TextView) rootView.findViewById(R.id.textView4);
            textView = (TextView) rootView.findViewById(R.id.section_label);
            textView.setText(Integer.toString(getArguments().getInt(ARG_SECTION_NUMBER)));
            return rootView;
        }
    }
}