Android Studio - 无法解析方法 'setText(double)'

Android Studio - Cannot resolve method 'setText(double)'

我已经初始化了一个 double 变量并想在 TextView 中显示它。
变量名称以红色下划线标出。
我试图将它解析为字符串,但没有成功。

public class MainActivity extends AppCompatActivity {

    Location currentloc = new Location("currentloc");

    double currlat = 0.0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        TextView gpsbox = (TextView) findViewById(R.id.gpsView);

        try {
            currlat = currentloc.getLatitude();
        } catch(Exception e) {
            Toast.makeText(this, "Hello, an exception was just thrown but I catched it. " + e.toString(), Toast.LENGTH_SHORT).show();
        }

        gpsbox.setText(currlat);

        setContentView(R.layout.activity_main);
    }
}

您必须通过

将其拆分为字符串
String.valueOf(currlat);

希望对你有用。

试试这个

setContentView(R.layout.activity_main);
TextView gpsbox = (TextView) findViewById(R.id.gpsView);

    try {
        currlat = currentloc.getLatitude();
    } catch(Exception e) {
        Toast.makeText(this, "Hello, an exception was just thrown 
     but I catched it. " + e.toString(), Toast.LENGTH_SHORT).show();
    }

    gpsbox.setText(String.valueOf(currlat));

代码中有 2 个错误。

  1. 在findViewById之后使用set content view会抛出异常
  2. double 应使用 String.valueOf() 方法包装以转换为字符串。

    public class MainActivity 扩展 AppCompatActivity {

    Location currentloc = new Location("currentloc");
    
    double currlat = 0.0;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
    
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        TextView gpsbox = (TextView) findViewById(R.id.gpsView);
    
        try {
            currlat = currentloc.getLatitude();
        } catch (Exception e) {
            Toast.makeText(this, "Hello, an exception was just thrown but I catched it. " + e.toString(), Toast.LENGTH_SHORT).show();
        }
    
        gpsbox.setText(String.valueOf(currlat));
    
    }
    

    }