[英]inflater.inflate(R.layout.) doesn't find Fragment.xml
[英]Custom view does not inflate from XML when referenced in Fragment.xml Android Application Development
我在Android中創建了一個自定義視圖,可以將其稱為MyCustomView,其XML文件為MyCustomView.xml。 我在片段中引用MyCustomView時,將其稱為MyFragment和MyFragment.xml。 該引用只是XML引用,而不是代碼。 當我的片段膨脹時,它利用MyFragment.xml膨脹。 然后,我可以檢索指向該視圖的指針。 這是我的問題。 除了MyCustomView不會從MyCustomView.xml中膨脹外,其他所有操作均按預期進行,因此,在屏幕上看不到MyCustomView.xml中定義的按鈕或布局。 我可能做錯了什么? 如何使MyFragment.xml中的XML引用隨MyCustomView.xml一起膨脹?
MyFragment.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.domain.MyFragment"
android:id="@+id/MyFragment">
<com.domain.MyCustomView
android:id="@+id/MyCustomView"
android:background="@android:color/transparent"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
</com.domain.MyCustomView>
</FrameLayout>
MyCustomView.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:orientation="horizontal"
android:layout_gravity="bottom"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<Button
android:id="@+id/btnCancel"
android:layout_width="200dp"
android:layout_height="100dp"
android:text="Cancel"
android:layout_weight="1" />
<Button
android:id="@+id/btnNext"
android:layout_width="200dp"
android:layout_height="100dp"
android:text="Next"
android:layout_weight="1" />
</LinearLayout>
</FrameLayout>
MyFragment.java
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_signature_capture, container, false);
myCustomView = (MyCustomView) v.findViewById(R.id.signatureView);
//At this point I would like to be able to
//access my buttons declared in MyCustomView.xml
//via the following call
Button b1 = (Button) myCustomView.findViewById(R.id.btnCancel);
//The above line returns null because it cant find the view.
return v ;
}
如果您已經為xml定義了一個自定義視圖,則該自定義視圖只能在View
類或其任何后代的子級中使用,而您必須為其定義源(java)文件。 由於您僅定義了自定義布局,沒有構造函數,因此無法像View
一樣誇大它。 您應該更改:
<com.domain.MyCustomView
android:id="@+id/MyCustomView"
android:background="@android:color/transparent"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
</com.domain.MyCustomView>
有:
<include
layout=@layout/MyCustomView
android:id="@+id/MyCustomView"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
</include>
然后將此屬性移到MyCustomView.xml
根FrameLayout
android:background="@android:color/transparent"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.