我在setOnLongClickListener
中的fragment
出错,这是我的代码和错误
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.widget.TextView.findViewById(int)' on a null object reference
at me.jatinsoni.myfragmentexample.BottomVIew.onCreateView(BottomVIew.java:23)
第23行: textView.findViewById(R.id.bottom_text);
import android.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
public class BottomVIew extends Fragment {
public View view;
public TextView textView;
public Button button;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.bottom_layout, container, false);
textView.findViewById(R.id.bottom_text);
button.findViewById(R.id.bottom_button);
button.setOnLongClickListener(
new Button.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
textView.setText(R.string.pressed_long);
return true;
}
}
);
return view;
}
}
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
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="wrap_content">
<TextView
android:id="@+id/bottom_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="8dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="16dp"
android:text="@string/bottom_view"
android:textSize="30sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:fontFamily="serif"
android:textColor="@android:color/black"/>
<Button
android:id="@+id/bottom_button"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="@string/click_to_update"
app:layout_constraintTop_toBottomOf="@+id/bottom_text"
app:layout_constraintStart_toStartOf="@id/bottom_text"
app:layout_constraintEnd_toEndOf="@id/bottom_text"
app:layout_constraintBottom_toBottomOf="parent"
android:layout_marginTop="16dp"
android:layout_marginBottom="16dp"
android:background="@color/colorAccent"
android:textColor="@android:color/white"/>
</android.support.constraint.ConstraintLayout>
答案 0 :(得分:2)
应该会的,
textView = view.findViewById(R.id.bottom_text);
和
buttonView = view.findViewById(R.id.bottom_button);