Tôi chạy vào cùng một vấn đề một khi trở lại khi tôi đã thêm một tùy chỉnh Xem qua XML layout và sau đó đã cố gắng để gắn một callback ở đâu đó trong ứng dụng ...
Tôi tạo ra một giao diện tùy chỉnh và bổ sung nó vào "layout_main.xml" của tôi "
public class MUIComponent extends SurfaceView implements SurfaceHolder.Callback {
public MUIComponent (Context context, AttributeSet attrs) {
super (context, attrs);
}
// ..
}
Và trong hoạt động chính, tôi muốn đính kèm một số cuộc gọi lại và tham khảo các thành phần giao diện người dùng từ XML.
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// ...
MUIInitializer muiInit = new MUIInitializer();
muiInit.setupCallbacks(this);
muiInit.intializeFields(this);
}
}
Các initilizer đã không làm bất cứ điều gì lạ mắt nhưng bất kỳ thay đổi nó cố gắng thực hiện với giao diện tùy chỉnh (MUIComponent) hoặc phi tùy chỉnh phần UI khác chỉ đơn giản là không được xuất hiện trong ứng dụng.
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
// ...
}
}
Sự khác biệt giữa "badInst" và "goodInst" là:
- badInst sử dụng findViewByID của Hoạt động
- goodInst thổi phồng cách bố trí và sử dụng cách bố trí thổi phồng để làm tra cứu
Luôn luôn tốt đẹp để có thể trả lời câu hỏi của riêng bạn :) Hãy chắc chắn đánh dấu bạn là câu trả lời được chấp nhận. – MattC
Thật vậy. Sẽ làm như vậy khi SO cho phép tôi ("Bạn có thể chấp nhận câu trả lời của riêng bạn trong 2 ngày.") –
Ngoài ra, không nên các dòng như '(MyCustomView) foo = findViewById (R.id.foo);' được 'MyCustomView foo = (MyCustomView) findViewById (R.id.foo); '? –