繁体   English   中英

如何在Android布局.xml中为一个coustom Viewgroup引用java文件

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM