Gab*_*han 19 android android-layout
我有一组想要一直使用的视图.这方面的一个例子可能是这样的:
<LinearLayout>
<TextView />
<EditView />
</LinearLayout>
Run Code Online (Sandbox Code Playgroud)
文本视图是一个提示,编辑视图就是答案.我想给这个组合命名,并能够使用该名称将其弹出到xml中.我喜欢它是一个自定义视图,所以我可以很好地把它放在一个类中,并为它创建各种实用程序功能.有什么方法可以做到吗?我知道我可以继承LinearLayout并在java代码中动态创建子项,但这使我无法通过xml轻松进行更改.有更好的路线吗?
是的,我还有一些我想要做的事情,而不仅仅是提示.
sta*_*ej2 50
此示例适用于水平数字选择器窗口小部件,但它是相同的概念.
首先为自定义组件创建XML布局
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
<Button
android:id="@+id/btn_minus"
android:layout_width="50dp"
android:layout_height="wrap_content"
android:text="-" />
<EditText
android:id="@+id/edit_text"
android:layout_width="75dp"
android:layout_height="wrap_content"
android:inputType="number"
android:gravity="center"
android:focusable="false"
android:text="0" />
<Button
android:id="@+id/btn_plus"
android:layout_width="50dp"
android:layout_height="wrap_content"
android:text="+" />
</LinearLayout>
Run Code Online (Sandbox Code Playgroud)
然后创建java类
public class HorizontalNumberPicker extends LinearLayout {
public HorizontalNumberPicker(Context context, AttributeSet attrs) {
super(context, attrs);
LayoutInflater inflater = LayoutInflater.from(context);
inflater.inflate(R.layout.horizontal_number_picker, this);
}
}
Run Code Online (Sandbox Code Playgroud)
将所需的逻辑添加到该java类中,然后您可以在XML布局中包含自定义组件,如下所示:
<com.example.HorizontalNumberPicker
android:id ="@+id/horizontal_number_picker"
android:layout_width ="wrap_content"
android:layout_height ="wrap_content" />
Run Code Online (Sandbox Code Playgroud)
有关更多信息,请查看此链接:http://developer.android.com/guide/topics/ui/custom-components.html#compound
| 归档时间: |
|
| 查看次数: |
16136 次 |
| 最近记录: |