自定义了一个组合控件,继承自LinearLayout,逻辑很简单,就是想实现一个带title的EditText。为了便于分析问题,已经将代码中的attrs.xml的属性删除,只留下导致问题出现的部分。
自定义控件的JAVA代码:
package com.shuda.epmms.customview;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
/**
- 自定义带Title的文本编辑输入框
- @author Justin Z
-
*/
public class CusEditText extends LinearLayout {/**
- title / private TextView titleView; /*
- content */ private EditText contentView;
public CusEditText(Context context) {
super(context);
}/**
- 构造方法
- @param context
-
@param attrs
*/
public CusEditText(Context context, AttributeSet attrs) {
super(context, attrs);LayoutInflater.from(context).inflate(R.layout.cus_edit_text_layout,
this, true);// title
this.titleView = (TextView) findViewById(R.id.cusEditTextTitle);
// content
this.contentView = (EditText) findViewById(R.id.cusEditTextContent);this.setBackgroundDrawable(getResources().getDrawable(
R.drawable.title_edit_normal));
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
System.out.println("调用onDraw()");}
}
布局文件cus_edit_text_layout.xml
<?xml version="1.0" encoding="utf-8"?>
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:gravity="center_vertical">
<TextView
android:id="@+id/cusEditTextTitle"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="4"/>
<EditText
android:id="@+id/cusEditTextContent"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:singleLine="true"
android:background="@color/none"/>
Activity代码:
package com.shuda.epmms.customview;
import android.app.Activity;
import android.os.Bundle;
public class CusEditTextActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
}
布局文件 main.xml
<?xml version="1.0" encoding="utf-8"?>
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@color/white"
android:orientation="vertical"
android:paddingLeft="10dp"
android:paddingRight="10dp">
<com.shuda.epmms.customview.CusEditText
android:layout_width="fill_parent"
android:layout_height="50dp"
android:background="@drawable/title_edit_selector"
android:focusable="true"
/>
<EditText
android:layout_width="fill_parent"
android:layout_height="50dp"
android:background="@drawable/title_edit_selector"
android:text="输入框"
/>
程序运行起来之后,会发现logcat中不停的打印“调用onDraw()”,在模拟机中改变当前的焦点到另外一个EditText中,打印就会停止,如果焦点切换回自定义控件中,打印又会继续
删除自定义控件类中的setBackgroundDrawable方法之后就不会出现上述问题,求解答??