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

Jim*_*nic 2 android android-fragments

我有一个自定义Fragment,它从test.xml中扩展了它的内容

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.test, container, true);
    return v;
}
Run Code Online (Sandbox Code Playgroud)

在test.xml里面,我有一个如此定义的切换按钮:

<ToggleButton 
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:onClick="update"
    />
Run Code Online (Sandbox Code Playgroud)

当我单击切换按钮时,出现以下错误:

Could not find a method update(View) in the activity class 
android.view.ContextThemeWrapper for onClick handler on view class 
android.widget.ToggleButton
Run Code Online (Sandbox Code Playgroud)

我在调用活动和片段中都定义了以下方法,但是没有被调用:

public void update(View view) {
    Log.d(LOG_TAG, "starting update!");
}
Run Code Online (Sandbox Code Playgroud)

我糊涂了.

小智 5

当您创建可能使用ContextThemeWrapper创建的LayoutInflater时,您需要使用活动上下文进行创建.

我有类似的问题.我是这样创造的:

(LayoutInflater)getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);

然后我这样做了:

(LayoutInflater)this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

并且工作.

我希望我有所帮助.