[英]Android: Button OnClick not working in SherlockFragment
I've tab activity in which i want to use a button, but when i click on button, it force closes the app. 我在其中要使用按钮的选项卡活动,但是当我单击按钮时,它会强制关闭应用程序。 Can you please tell me what is going on, i am new to Android.
您能告诉我发生了什么吗,我是Android新手。
public class HomeActivity extends SherlockFragment {
private Button bt;
private Context con;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.home_layout, container, false);
bt = (Button)rootView.findViewById(R.id.btn);
bt.setOnClickListener(new View.OnClickListener(){
@Override public void onClick(View v)
{
Toast.makeText(con, "hello", Toast.LENGTH_LONG).show();
}
});
return rootView;
}
}
when i click on button, it force closes the app
当我单击按钮时,它会强制关闭应用程序
Because con
object of Context is null
. 因为Context的
con
对象为null
。 which is used for showing Toast message in Button onClick
method. 用于在Button
onClick
方法中显示Toast消息。
Do it as: 这样做:
Toast.makeText(v.getContext(), "hello", Toast.LENGTH_LONG).show();
And initialize con
object by calling getActivity()
in onCreateView
as: 然后通过在
onCreateView
调用getActivity()
来初始化con
对象:
con=getActivity();
If you can avoid that, don't keep a reference to the context; 如果可以避免这种情况,请不要保留对上下文的引用; instead of the
而不是
private Context con;
get the current Activity in the code, so use 在代码中获取当前的Activity,因此使用
Toast.makeText(getActivity(), "hello", Toast.LENGTH_LONG).show();
Btw, this seems to be the cause of your crash, as Context is null. 顺便说一句,这似乎是导致崩溃的原因,因为Context为null。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.