当我通过布局XML添加自定义视图,然后尝试在应用程序中的其他位置附加回调时,我遇到了相同的问题。
我创建了一个自定义视图,并将其添加到我的“ layout_main.xml”中
public class MUIComponent extends SurfaceView implements SurfaceHolder.Callback {
public MUIComponent (Context context, AttributeSet attrs ) {
super ( context, attrs );
}
// ..
}
在主活动中,我想附加一些回调并从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使用活动的findViewByID
- goodInst扩大布局并使用扩大后的布局进行查找