不久前,当我通过布局 XML 添加自定义视图时,我遇到了同样的问题
然后尝试在应用程序的其他地方附加回调...
我创建了一个自定义视图并将其添加到我的“layout_main.xml”中
public class MUIComponent extends SurfaceView implements SurfaceHolder.Callback {
public MUIComponent (Context context, AttributeSet attrs ) {
super ( context, attrs );
}
// ..
}
在主 Activity 中,我想附加一些回调并从 XML 中获取对 UI 元素的引用。
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// ...
MUIInitializer muiInit = new MUIInitializer();
muiInit.setupCallbacks(this);
muiInit.intializeFields(this);
}
}
初始化器并没有做任何花哨的事情,但它试图对自定义视图 (MUIComponent) 进行任何更改
或其他非自定义 UI 元素根本没有出现在应用程序中。
public class MUIInitializer {
// ...
public void setupCallbacks ( Activity mainAct ) {
// This does NOT work properly
// - The object instance returned is technically an instance of my "MUICompnent" view
// but it is a *different* instance than the instance created and shown in the UI screen
// - Callbacks never get triggered, changes don't appear on UI, etc.
MUIComponent badInst = (MUIComponent) mainAct.findViewById(R.id.MUIComponent_TESTSURF);
// ...
// This works properly
LayoutInflater inflater = (LayoutInflater) mainAct.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View inflatedLayout = inflater.inflate ( R.layout.activity_main, null );
MUIComponent goodInst = (MUIComponent) inflatedLayout.findViewById(R.id.MUIComponent_TESTSURF);
// Add callbacks
// ...
}
}
“badInst”和“goodInst”的区别是:
- badInst 使用 Activity 的 findViewByID
- goodInst 膨胀布局并使用膨胀的布局进行查找