gpt4 book ai didi

java - NullPointerException setOnClickListner

转载 作者:行者123 更新时间:2023-12-01 18:05:09 26 4
gpt4 key购买 nike

我是android初学者。这是我从书上复制的代码。但是当我下载并在智能手机上运行时,会发生 NullPointerException。

异常信息如下:

java.lang.NullPointerExcption:尝试在 .... 处的空对象引用上调用虚拟方法“void android.widget.Button.setOnClickListner”

这是我的代码的一部分:

public class MainActivity extends AppCompatActivity {

Button btn1 , btn2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

// requestWindowFeature(Window.FEATURE_PROGRESS);
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
btn1 = (Button) findViewById(R.id.btn1);
btn2 = (Button) findViewById(R.id.btn2);
btn1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
setProgressBarIndeterminateVisibility(true);
setProgressBarVisibility(true);
setProgress(4500);
}
});
btn2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
setProgressBarIndeterminateVisibility(false);
setProgressBarVisibility(false);
}
});
setContentView(R.layout.activity_main);

Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);

FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}

这是 XML 文件:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:context="com.neoncowboy.titleprogressbar.MainActivity"
tools:showIn="@layout/activity_main"
android:orientation="horizontal">

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="显示"
android:id="@+id/btn1" />

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="隐藏"
android:id="@+id/btn2" />

</LinearLayout>

最佳答案

setContentView() 行必须位于 findViewById() 行之前。

关于java - NullPointerException setOnClickListner,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37054639/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com