我试图引用片段中的按钮并听取其点击次数。由于某种原因,它不断抛出NullPointerException,但我不知道为什么它为null。我知道答案可能非常简单明了但我无法在任何地方找到答案。
代码:
CardKeyboardFrag.java
package com.example.cribbage2;
import android.app.Activity;
import android.app.Fragment;
import android.content.Context;
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;
public class CardKeyboardFrag extends android.support.v4.app.Fragment
implements View.OnClickListener {
CardTransfer mCallback;
public interface CardTransfer {
void onCardSelected(int card);
}
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.card_keyboard_frag, container, false);
//region buttonAssignments
//this is where it happens
Button one = (Button) getActivity().findViewById(R.id.buttonA);
one.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
buttonClicked(1);
}
});
//endregion
return view;
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
try {
mCallback = (CardTransfer) context;
} catch (ClassCastException e) {
throw new ClassCastException(context.toString() + " must implement CardTransfer");
}
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.buttonA:
buttonClicked(1);
break;
}
}
public void buttonClicked(int num){
mCallback.onCardSelected(num);
}
}
这是xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto">
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="16dp"
android:text="Cards"
android:textAlignment="center"
android:textSize="30sp"/>
<GridLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentStart="true"
android:layout_marginBottom="8dp"
android:columnCount="3"
android:rowCount="5">
<Button
android:id="@+id/buttonA"
android:layout_width="120dp"
android:layout_height="50dp"
android:text="Ace"/>
</GridLayout>
</RelativeLayout>
提前致谢