在我的应用程序中,我想创建一个可重用为.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 在此先感谢。
答案 0 :(得分:2)
您可以使用包名称和文件名(如
)来使用它<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
答案 1 :(得分:0)
在你的xml代码中。在引用类名之前添加完整的包名称,然后添加类名称,例如
<com.my.test.SearchWidget
android:id="@+id/large_photo_gallery"
android:layout_height="fill_parent"
android:layout_width="fill_parent"
/>
答案 2 :(得分:0)
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"/>