java - Variable 'Button' never assigned (Java using android studio)
问题描述
First: Apologies if this question has been asked several times already. I just couldn't find a fix.
Compiler in android studio returns "1 error":
Button button_go2activity findViewById(R.id.button_go2activity);
Error code: variable 'button_go2activity' never assigned
This is confusing to me. I also have another button, which I assigned the same (and which works fine). I also tried to add the variable 'button' in the strings.xml (although it works with the other button without that declaration).
Please see the code attached. Many thanks for your help.
Best, Constantin
package paperpad.app;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.app.Activity;
import android.content.Intent;
import android.content.res.Configuration;
import android.database.Cursor;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.method.LinkMovementMethod;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
//private Button button; //button because otherwise not declared???
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button_openHelp = findViewById(R.id.button_openHelp); //connect button "open help" to xml
button_openHelp.setOnClickListener(new View.OnClickListener() { //find button
@Override
public void onClick(View view) { //activity when button "open help" is clicked
Intent openHelp = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.youtube.com")); //link to paperPad youtube channel
startActivity(openHelp);
}
});
Button button_go2activity findViewById(R.id.button_go2activity);
button_go2activity.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View view) {
openActivity_loadPicture(); //activity defined below
}
});
}
public void openActivity_loadPicture() {
Intent intent = new Intent(this, loadpicture.class);
startActivity(intent);
}
}
解决方案
在您的代码中,您缺少=
赋值运算符。定义的行button_go2activity
应如下所示:
Button button_go2activity = findViewById(R.id.button_go2activity);
推荐阅读
- python - 从列表创建 lambda 函数的方法
- kendo-ui - 如何在 Kendo UI 网格中将复选框检查限制为 5
- asp.net - 锁定事务 (SQL Server + EF5)
- html - 使用 display: block in tbody 时标题单元格和行单元格未对齐
- java - 检查服务器上的 Jboss 实例的行为是否与本地相同的实例不同?
- reactjs - 使用 TypeScript 3 扩展道具的 React 组件中的默认属性值
- java - 例外:不能转换为 java.lang.Long
- mysql - Laravel 数据库从旧数据库 UTF-8 编码问题迁移
- android - Custom ReleaseTree is not showing the logs using Timber
- python-3.x - how to write testcases for yaml file using python