如何在android layout .xml中为自定义视图组引用java文件



在我的应用程序中,我想创建一个搜索小部件,这将是可重用的。java文件,我需要反映到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"/>

最新更新