为什么我的 onClick 方法没有从自定义片段中的膨胀视图中调用?
我有一个自定义片段,它会膨胀 test.xml 中的内容
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.test, container, true);
return v;
}
在 test.xml 内部,我定义了一个切换按钮,如下所示:
<ToggleButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="update"
/>
当我单击切换按钮时,出现以下错误:
Could not find a method update(View) in the activity class
android.view.ContextThemeWrapper for onClick handler on view class
android.widget.ToggleButton
我在两个中都定义了以下方法调用活动和片段,但都没有被调用:
public void update(View view) {
Log.d(LOG_TAG, "starting update!");
}
我很困惑。
I have a custom Fragment that inflates it's content from test.xml
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.test, container, true);
return v;
}
Inside of test.xml, I have a toggle button defined like so:
<ToggleButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="update"
/>
When I click on the toggle button, I get the following error:
Could not find a method update(View) in the activity class
android.view.ContextThemeWrapper for onClick handler on view class
android.widget.ToggleButton
I have the following method defined in both the calling activity and the fragment, but neither is getting called:
public void update(View view) {
Log.d(LOG_TAG, "starting update!");
}
I'm confused.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当您创建 LayoutInflater 时,您可能正在使用 ContextThemeWrapper 创建,并且要工作,您需要使用活动上下文创建。
我有类似的问题。我是这样创建的:
(LayoutInflater) getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
然后我这样做了:
(LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
并工作了。
我希望我有所帮助。
When you are creating the LayoutInflater you are creating, probably, with the ContextThemeWrapper and to work you need to create with the activity context.
I had similar problem. I was creating like this:
(LayoutInflater) getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
then I done like this:
(LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
and worked.
I hope I have helped.