变量“startTs”需要声明为final。当我宣布它作为最终的android工作室突出显示它并说“不能为最终变量赋值” 如果删除了最终修饰符,我收到“变量必须是最终的”
现在我想使用变量“startTs”并为其赋值,如何做到
请告诉我如何解决此问题
码:
final long startTs;
mbtnLogFileAction.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
switch (action) {
case "Record":
Log.i(TAG, CSubTag.bullet("ATRx.onPreExecute", "start Recording logs"));
mbtnLogFileAction.setText("Pause");
metLogFileName.setEnabled(false);
String logFileName = metLogFileName.getText().toString();
if (logFileName != null && !logFileName.isEmpty()) {
if (!mLogFileHT.containsKey(logFileName)) {
startTs = TimeUtils.getTSSec();//cant assign value to final variable
mLogFileHT.put(logFileName, startTs);
} else {
startTs = mLogFileHT.get(logFileName);//cant assign value to final variable
}
答案 0 :(得分:1)
只需将startTs全局放入。
public class YourClass
{
long startTs;
// your other code goes here..
mbtnLogFileAction.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
switch (action) {
case "Record":
Log.i(TAG, CSubTag.bullet("ATRx.onPreExecute", "start Recording logs"));
mbtnLogFileAction.setText("Pause");
metLogFileName.setEnabled(false);
String logFileName = metLogFileName.getText().toString();
if (logFileName != null && !logFileName.isEmpty()) {
if (!mLogFileHT.containsKey(logFileName)) {
startTs = TimeUtils.getTSSec();//cant assign value to final variable
mLogFileHT.put(logFileName, startTs);
} else {
startTs = mLogFileHT.get(logFileName);//cant assign value to final variable
}
}
答案 1 :(得分:0)
因为您使用的是匿名内部类,startTs
必须最终在其中使用,因为它是最终的,它应该是编译时常量,不能重新分配< / p>
答案 2 :(得分:0)
最终成员变量必须在声明时或构造函数内部初始化,否则将导致编译错误。