无法从静态上下文引用非静态方法

无法从静态上下文引用非静态方法

本文介绍了Android:无法从静态上下文引用非静态方法。困惑?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我非常非常喜欢Java和编程。我写了一个基本程序,用来添加用户输入的2个数字并将它们添加起来并在输出框中显示它们,但是我得到非静态方法setText(java.lang.CharSequence)'无法引用来自静态上下文,但我不知道静态的东西是什么

I am extremely extremely new to Java and programming in general. I wrote this for a basic program to add 2 numbers input by the user and add them up and display them in the output box, however I'm getting "Non-static method 'setText(java.lang.CharSequence)' cannot be referenced from a static context", but I don't know what the static thing is

    private void onClick(View v){
    EditText input1 = (EditText) findViewById(R.id.input1);
    double calc1 =  Double.parseDouble(String.valueOf(input1));
    EditText input2 = (EditText) findViewById(R.id.input2);
    double calc2 = Double.parseDouble(String.valueOf(input2));
    double total = calc1 + calc2;
    String result = Double.toString(total);
    EditText output1 = (EditText)findViewById(R.id.output);
    EditText.setText(result);
    }

给出错误的行:

    EditText.setText(result);

很抱歉,如果我非常无能,但我搜索过,我真的不明白如何解决它。谢谢。

Sorry if I'm being extremely incompetent but I searched and I couldn't really understand how to fix it. Thanks.

推荐答案

在静态上下文中,您没有对象(类的实例),而是实例变量和方法依赖于它们。

In a static context, you don't have an object (instance of the class), but the instance variables and methods depend on them.

你有一个名为output1的实例,但你尝试通过类的名称调用你的方法'setText'(这是一种静态方法) 。

You have an instance, called output1, but you try to call your method 'setText' through the class's name (which is a static approach).

更改行

EditText output1 = (EditText)findViewById(R.id.output);
    EditText.setText(result);

EditText output1 = (EditText)findViewById(R.id.output);
    output1.setText(result);

这篇关于Android:无法从静态上下文引用非静态方法。困惑?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-22 21:32