我有一个自定义片段,它会从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!");
}
我很困惑。
答案 0 :(得分:5)
当您创建可能使用ContextThemeWrapper创建的LayoutInflater时,您需要使用活动上下文创建。
我有类似的问题。我是这样创造的:
(LayoutInflater)getApplicationContext()。getSystemService(Context.LAYOUT_INFLATER_SERVICE);
然后我这样做了:
(LayoutInflater)this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
并且工作了。
我希望我有所帮助。