我想设置一个onClickListener到我的CheckBox,但我的CheckBox实例返回null onClickListener给我一个nullPointerException。我已经看过类似于我的其他问题,并没有发现任何有效的工作。我对RecyclerView不太熟悉,所以如果它与我如何初始化视图有关,我不会感到惊讶。查看里面的RecyclerView返回null
这里是question-
Months0Through6.java
public class Months0Through6 extends android.support.v4.app.Fragment {
public Months0Through6() {
// Required empty public constructor
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
CheckBox checkBox;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_blank, container, false);
//This is returning null
checkBox = (CheckBox)rootView.findViewById(R.id.checkBox_ID);
RecyclerView rv = (RecyclerView) rootView.findViewById(R.id.rv_recycler_view);
rv.setHasFixedSize(true);
MilestonesAdapter adapter = new MilestonesAdapter(new String[]{"Month 0 stuff", "Example Two", "Example Three", "Example Four", "Example Five" , "Example Six" , "Example Seven"});
rv.setAdapter(adapter);
LinearLayoutManager llm = new LinearLayoutManager(getActivity());
rv.setLayoutManager(llm);
checkBox.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getContext(),
"Your Message", Toast.LENGTH_LONG).show();
}
});
return rootView;
}
card_item.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="68dp">
<android.support.v7.widget.CardView
android:id="@+id/card_view"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_margin="10dp"
android:layout_height="62dp"
card_view:cardCornerRadius="4dp"
card_view:elevation="14dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<CheckBox
android:id="@+id/checkBox_ID"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TextView
android:id="@+id/tv_text"
android:layout_toRightOf ="@+id/checkBox_ID"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center" >
</TextView>
<TextView
android:id="@+id/tv_blah"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Another Recyclerview Fragment"
android:layout_below="@+id/tv_text"
android:layout_toRightOf="@+id/checkBox_ID"
android:layout_toEndOf="@+id/checkBox_ID">
</TextView>
</RelativeLayout>
</android.support.v7.widget.CardView>
</RelativeLayout>