【发布时间】:2018-03-15 15:29:16
【问题描述】:
我想在按钮 click 上显示 toast,该按钮位于片段中。我已经尝试过获取toast 上下文的方法,但它没有在按钮单击时显示。
这是我的代码
public class Bottom_Sheet_Fragment extends Fragment {
Button addComment;
public Bottom_Sheet_Fragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view=inflater.inflate(R.layout.fragment_bottom__sheet, container, false);
addComment=(Button) container.findViewById(R.id.addCommentBtn);
addComment.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(getActivity(), "Added", Toast.LENGTH_SHORT).show();
}
});
return view;
}
}
这是片段布局
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/bottom_sheet1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@android:color/holo_blue_light"
android:fillViewport="true"
android:orientation="vertical"
app:behavior_hideable="true"
app:behavior_peekHeight="0dp"
app:layout_behavior="android.support.design.widget.BottomSheetBehavior">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@android:color/holo_blue_light"
android:orientation="vertical">
<android.support.v7.widget.RecyclerView
android:id="@+id/commentList"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<EditText
android:id="@+id/etComment"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:hint="Write comment" />
<Button
android:id="@+id/addCommentBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:text="Add" />
</RelativeLayout>
</LinearLayout>
这个布局文件包含在另一个活动中,在包含语句中。不知道问题出在哪里。这个片段就像一个底页。
【问题讨论】:
-
尝试在
onClick中添加一些Log.d并观看logcat? -
您需要在
view上调用findViewById(),而不是container。我很惊讶它没有崩溃。 -
所以你的fragment根本没有添加:
Fragment#onCreateView方法没有被调用,你知道怎么debug your app吗? -
是的,它解释了为什么你的代码没有崩溃——一旦你添加了你的片段,你会看到由于
NullPointerException而导致的漂亮崩溃
标签: android fragment onclicklistener android-toast