为什么我的 onClick 方法没有从自定义片段中的膨胀视图中调用?

发布于 2024-12-08 16:23:38 字数 821 浏览 2 评论 0原文

我有一个自定义片段,它会膨胀 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

雨夜星沙 2024-12-15 16:23:38

当您创建 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文