Android Can';t解析符号';setText';错误

Android Can';t解析符号';setText';错误,android,textview,settext,Android,Textview,Settext,正如标题所说,我在android项目中尝试设置java文本视图时出错,我不明白为什么 package com.codeherenow.sicalculator; import android.app.Activity; import android.os.Bundle; import android.widget.TextView; import android.widget.SeekBar; public class SICalculator

正如标题所说,我在android项目中尝试设置java文本视图时出错,我不明白为什么

    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)");
}

YT=(TextView)findViewById(R.id.Years)
YT.setText(年+年)
必须移动到
onCreate()
方法中

所以,留下这个

public TextView YT;
并在此处初始化它:

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

    YT = (TextView) findViewById(R.id.Years);
    YT.setText(years + " Year(s)");
}
[编辑]

如果要使用“进度”值进行动态更改:

@Override
public void onProgressChanged (SeekBar seekBar,int i, boolean b)
{
    //years = i;
    YT.setText(i + " Year(s)");
}
示例XML

<TextView
    android:id="@+id/myAwesomeTextView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:text="Escriba el mensaje y luego clickee el canal a ser enviado"
    android:textSize="20sp" />
所以你需要加上

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

在onCreate方法中,您遇到了几个问题

首先,你不能在这里这么做

public TextView YT = (TextView) findViewById(R.id.Years);
因为布局尚未膨胀,所以您无法使用t
findViewById()查找
视图。你可以在那里申报

public TextView YT;
但是在调用
setContentVie()

您正试图在方法外部调用
setText()
。把它移到某个方法。但是您不能在
onCreate()
中执行此操作,因为
Years
没有给定值。所以你可能想把它放在别的地方。可能在
onProgressChanged()

此外,为了遵循Java命名约定,您应该以小写字母(yt或yt和年份)开始命名变量


语句必须编写onCreate()方法。

我刚刚编辑了答案
setText()
不能在声明空间中浮动。加1表示坚持命名约定。
public TextView YT;
@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);
}
public TextView YT = (TextView) findViewById(R.id.Years);