无法解决符号"setText"错误 [英] Can't resolve symbol 'setText' error

查看:73
本文介绍了无法解决符号"setText"错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

就像标题说的那样,尝试在我的android项目中设置Java的文本视图文本时出现错误,

like the title says I'm getting an error when trying to set a text view text from java in my android project, I can't see why.

    package com.codeherenow.sicalculator;

    import android.app.Activity;
    import android.os.Bundle;
    import android.widget.TextView;
    import android.widget.SeekBar;

    public class SICalculatorActivity extends Activity implements SeekBar.OnSeekBarChangeListener{
public double years;
public TextView YT = (TextView) findViewById(R.id.Years);

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.sicalculator);
}
    @Override
    public void onProgressChanged (SeekBar seekBar,int i, boolean b){
        years = i;
    }

    @Override
    public void onStartTrackingTouch (SeekBar seekBar){

    }

    @Override
    public void onStopTrackingTouch (SeekBar seekBar){

    }
YT.setText(years + " Year(s)");

}

推荐答案

您遇到了一些问题.

首先,您不能在这里这样做

First, you can't do this here

public TextView YT = (TextView) findViewById(R.id.Years);

因为布局尚未膨胀,所以您无法通过 findViewById()查找 View .您可以在那里声明

Because the layout hasn't been inflated yet so you can't look for your View witht findViewById(). You can declare it there

public TextView YT;

,但是您需要在 之后调用 setContentVie()

but you need to initialize it after you call setContentVie()

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

    //can't do it before that line ^
    YT = (TextView) findViewById(R.id.Years);
}

并且您正在尝试在方法外部调用 setText().将其移动到某种方法.但是您不能在 onCreate()中执行此操作,因为未给 Years 赋值.因此,您可能希望在其他地方使用它.也许在 onProgressChanged()中.

And you are trying to call setText() outside of a method. Move that to some method. But you can't do it in onCreate() because Years isn't given a value. So you probably want it somewhere else. Maybe in onProgressChanged().

此外,要遵循Java命名约定,您应该以小写字母(yt或yT和年份)开头来命名变量.

Also, to follow Java naming conventions, you should name your variables by starting with lower case (yt or yT and years).

这篇关于无法解决符号"setText"错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆