很早之前实现了一个很简单的自定义布局,即继承自现有的布局,来实现自己功能的一些扩展,虽然比较简单,但是也很具有代表性,所以就记录下来吧
先看下效果吧:
可以看到,这个效果类似于注册登录的文本框,只不过这里我使用了一个布局将多个android提供的原生控件封装起来了
自定义布局的步骤:
- 编写自定义布局的布局文件
- 继承自现有的布局,或者ViewGroup
- 在xml中使用该布局
编写布局文件
activity_zuhe.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:clipToPadding="true"
android:fitsSystemWindows="true" >
<EditText
android:id="@+id/edittext"
android:layout_width="fill_parent"
android:layout_height="80px"
android:background="#009959"
android:singleLine="true" />
<TextView
android:id="@+id/textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="@+id/edittext"
android:background="#00000000"
android:clickable="true"
android:layout_centerVertical="true"
android:text="删除"
android:textColor="#ff0000"
android:visibility="gone" />
</RelativeLayout>
继承自现有布局或ViewGroup
public class CancelEdit extends LinearLayout implements EditInterface{
// 文本框
EditText mEditText = null;
// 删除提示
TextView mTextView = null;
public CancelEdit(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
LayoutInflater layoutInflater = LayoutInflater.from(context);
layoutInflater.inflate(R.layout.activity_zuhe,this,true);
mEditText = (EditText) findViewById(R.id.edittext);
mTextView = (TextView) findViewById(R.id.textview);
mEditText.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
@Override
public void afterTextChanged(Editable s) {
// 根据当前的内容是否==""来决定是否显示删除文字
if (s != null && s.length() == 0) {
hiddenCancel();
} else {
showCancel();
}
}
});
mTextView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
mEditText.setText("");
}
});
}
public CancelEdit(Context context, AttributeSet attrs) {
this(context, attrs,0);
}
public CancelEdit(Context context) {
this(context,null);
}
@Override
public void hiddenCancel() {
mTextView.setVisibility(View.GONE);
}
@Override
public void showCancel() {
mTextView.setVisibility(View.VISIBLE);
}
}
// 自己定义接口,用来控制显示和隐藏当前删除按钮
interface EditInterface {
public void hiddenCancel();
public void showCancel();
}
在xml中使用该布局
<com.example.zuhe.CancelEdit
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#009959"
android:clipToPadding="true"
android:fitsSystemWindows="true" />
ok,代码比较简单,可以看到现在已经实现了一个基本的自定义layout,虽然比较简单,也米有什么太多的技术含量,但是很有代表性,故作此记录。