[英]How to Refrence java file in android layout .xml for a coustom Viewgroup
在我的應用程序中,我想創建一個可重用為.java文件的Search小部件,我需要將它反映到layout.xml文件中,以便我可以使用它。 直接.....這是我的代碼有一個編輯框,兩個按鈕。
public class SearchWidget extends ViewGroup{
Context mContext;
LinearLayout layout;
EditText edit;
Button searchButton;
Button clear;
LinearLayout.LayoutParams params=new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
public SearchWidget(Context context) {
super(context);
this.mContext=context;
layout=new LinearLayout(context);
edit=new EditText(context);
searchButton=new Button(context);
clear=new Button(context);
params.setMargins(10, 10, 10, 10);
layout.setOrientation(LinearLayout.HORIZONTAL);
layout.setLayoutParams(params);
edit.setMaxLines(1);
edit.setWidth(100);
layout.addView(searchButton);
layout.addView(clear);
}
}
請建議我如何將這個java文件引用到我的layout.xml中。
您可以使用包名和文件名來使用它
<com.myapp.SearchWidget android:layout_width="fill_parent"
android:layout_height="wrap_content">
</com.myapp.SearchWidget>
使用xml放置自定義視圖時,需要使用帶有2個參數的構造函數。
在檢查代碼之后,會出現許多錯誤,例如您最終沒有向搜索小部件添加“布局”。 所以什么都不會出現。 我不確定你的最終結果是什么。 但這就是我認為你要做的事情。
public class SearchWidget extends LinearLayout {
public SearchWidget(Context context, AttributeSet attrs) {
super(context, attrs);
EditText edit = new EditText(context);
LinearLayout.LayoutParams elp = new LinearLayout.LayoutParams(0,
LayoutParams.WRAP_CONTENT, 1.0f);
edit.setLayoutParams(elp);
Button searchButton = new Button(context);
searchButton.setLayoutParams(new ViewGroup.LayoutParams(
LayoutParams.WRAP_CONTENT,LayoutParams.FILL_PARENT));
searchButton.setText("Search");
Button clearButton = new Button(context);
clearButton.setLayoutParams(new ViewGroup.LayoutParams(
LayoutParams.WRAP_CONTENT,LayoutParams.FILL_PARENT));
clearButton.setText("Clear");
addView(edit);
addView(searchButton);
addView(clearButton);
}
}
在這里,我擴展了LinearLayout
在你的xml代碼中。 在引用類名之前添加完整的包名,然后添加類名,例如
<com.my.test.SearchWidget
android:id="@+id/large_photo_gallery"
android:layout_height="fill_parent"
android:layout_width="fill_parent"
/>
package yourpackage;
... ...
public class SearchWidget extends ViewGroup
{
// Please use this constructor.
public SearchWidget(Context context, AttributeSet attrs)
{
super(context, attrs);
}
... ...
}
<yourpackage.SearchWidget
android:id="@+id/searchWidget"
android:layout_width="fill_parent"
android:layout_height="fill_parent"/>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.