问题描述
我创建基于一个LinearLayout中自定义的ViewGroup。
I've created a custom ViewGroup based on a LinearLayout.
ClearableEditText.java
package test.todolist;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
public class ClearableEditText extends LinearLayout{
private EditText editText;
private Button button;
public ClearableEditText (Context context){
super (context);
String service = Context.LAYOUT_INFLATER_SERVICE;
LayoutInflater li = (LayoutInflater)getContext ().getSystemService (service);
li.inflate (R.layout.clearable_edit_text, this, true);
editText = (EditText)findViewById (R.id.clearEditText);
button = (Button)findViewById (R.id.clearButton);
configButton ();
}
private void configButton (){
button.setOnClickListener (new Button.OnClickListener (){
public void onClick (View v){
editText.setText ("");
}
});
}
}
clearable_edit_text.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<EditText
android:id="@+id/clearEditText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
<Button
android:id="@+id/clearButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/clear"
/>
</LinearLayout>
如何我现在用ClearableEditText?
How can I use ClearableEditText now?
我试图把一个节点的布局(main.xml中)里面2种方式:
I've tried to put a node inside a layout (main.xml) in 2 ways:
<test.todolist.ClearableEditText/>
和
<test.todolist.clearable_edit_text/>
但他们没有工作过。
but none of them have worked.
我的 main.xml中
<?xml version="1.0" encoding="utf-8"?>
<test.todolist.ClearableEditText/>
我的 ToDoList.java (主要活动):
package test.todolist;
import android.app.Activity;
import android.os.Bundle;
public class ToDoList extends Activity{
@Override
public void onCreate (Bundle savedInstanceState){
super.onCreate (savedInstanceState);
setContentView (R.layout.main);
}
}
感谢。
推荐答案
解决。在main.xml中应该是这样的:
Solved. The main.xml should be like:
<?xml version="1.0" encoding="utf-8"?>
<merge xmlns:android="http://schemas.android.com/apk/res/android">
<test.todolist.ClearableEditText
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</merge>
首先,,因为它是使用自定义视图时,需要合并
标记。我的自定义视图有一个的LinearLayout
根,所以它的效率不高,如果我main.xml中设置另外的LinearLayout或根的FrameLayout使用我的自定义视图。 合并
解决了。
First, merge
tag because it is needed when using custom views. My custom view have a LinearLayout
root, so it's inefficient if I set another LinearLayout or FrameLayout root in main.xml to use my custom view. merge
solves that.
第二,所有意见必须具有 layout_width
和 layout_height
属性。
And second, all views must have the layout_width
and layout_height
attributes.
这篇关于如何使用复合控件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!