如何在android studio中添加方法?

时间:2017-10-11 13:46:45

标签: java android android-studio

这是我的代码:

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

        final EditText txtFirstNum = (EditText) findViewById(R.id.txtFirstNum);
        final EditText txtSecondNum = (EditText) findViewById(R.id.txtSecondNum);
        final TextView txtResult = (TextView) findViewById(R.id.lblResult);

        Button btnAdd = (Button) findViewById(R.id.btnAdd);
        btnAdd.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {

                int num1 = Integer.parseInt(txtFirstNum.getText().toString());
                int num2 = Integer.parseInt(txtSecondNum.getText().toString());
                int result = num1 + num2;
                txtResult.setText(result + "");
            }
        });

        Button btnSub = (Button) findViewById(R.id.btnSub);
        btnSub.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {


                int num1 = Integer.parseInt(txtFirstNum.getText().toString());
                int num2 = Integer.parseInt(txtSecondNum.getText().toString());
                int result = num1 - num2;
                txtResult.setText(result + "");
            }
        });
    }
}

我本来想要做的是使用一个我可以调用的方法,而不是像这样重复相同的代码行(这不起作用):

    int num1;
    int num2;
    btnAdd.setOnClickListener(new View.OnClickListener()
    {
        @Override
        public void onClick(View v)
        {

            getNumbers();
            int result = num1 + num2;
            txtResult.setText(result + "");
        }
    });

...

private void getNumbers()
{
   num1 = Integer.parseInt(txtFirstNum.getText().toString());
   num2 = Integer.parseInt(txtSecondNum.getText().toString());
}

2 个答案:

答案 0 :(得分:2)

为什么不创建两个类似于getNumber方法而不是void

的方法
private int getFirstNumber()
{
   return Integer.parseInt(txtFirstNum.getText().toString());
}

private int getSecondNumber()
{
   return Integer.parseInt(txtFirstNum.getText().toString());
}

并将其用于:

    @Override
    public void onClick(View v)
    {
        int result = getFirstNumber() + getSecondNumber();
        txtResult.setText(result + "");
    }

答案 1 :(得分:0)

你必须制作班级的num1和num2属性