public class ContentFragment extends Fragment implements View.OnClickListener {
@BindView(R.id.button_show_toast)
Button button_show_toast;
Unbinder unbinder;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_a, container, false);
unbinder = ButterKnife.bind(this, view);
return view;
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
button_show_toast.setOnClickListener(this);
}
@Override
public void onDestroyView() {
super.onDestroyView();
unbinder.unbind();
}
@Override
public void onClick(View v) {
int i = v.getId();
// Why v.getId() isn't equal to R.id.button_show_toast?
Log.d("v.getId()", i + "");
Log.d("R.id.button_show_toast", R.id.button_show_toast + "");
Toast.makeText(getActivity(), "I am come from fragment.", Toast.LENGTH_SHORT).show();
}
}
我想使用切换功能来管理按钮点击事件。但是,v.getId()
并不等于R.id.button_show_toast
,我现在无法找到答案。
log
告诉我v.getId()
不等于R.id.button_show_toast
。希望可以有人帮帮我。
以下是日志信息:
D / v.getId():2131492957
D / R.id.button_show_toast:2131492992
另外,我在这里发布了fragment_a.xml
文件:
<?xml version="1.0" encoding="utf-8"?>
<Button xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/button_show_toast"
style="@style/MyButtonStyle"
android:text="@string/hello"/>
答案 0 :(得分:1)
这样的事情
@OnClick(R.id.button_show_toast)
public void onClick(View v) {
int i = v.getId();
// Why v.getId() isn't equal to R.id.button_show_toast?
Log.d("v.getId()", i + "");
Log.d("R.id.button_show_toast", R.id.button_show_toast + "");
Toast.makeText(getActivity(), "I am come from fragment.", Toast.LENGTH_SHORT).show();
}
答案 1 :(得分:0)
在onCreateView()
中添加此行button_show_toast=(Button)view.findViewById(R.id.button_show_toast); // add this line
整个代码:
Button button_show_toast;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_a, container, false);
unbinder = ButterKnife.bind(this, view);
button_show_toast=(Button)view.findViewById(R.id.button_show_toast); // add this line
return view;
}
答案 2 :(得分:0)
虽然我不确定,但您的项目可能包含两个或多个具有相同ID的视图 - R.id.button_show_toast
。尝试搜索整个项目。
此外,您可以使用@OnClick
定义ButterKnife
方法,如下所示: -
@OnClick(R.id.button_show_toast)
public void onShowToastClicked() {
// Do your stuff here...
}
答案 3 :(得分:0)
您可以使用以下功能:
@OnClick(R.id.button_show_toast)
public void onClick(View v) {
int i = v.getId();
}