package com.eternity;import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
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 clearButton;
public ClearableEditText(Context context) {
super(context);
// 使用布局资源扩充视图
LayoutInflater li;
li = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
li.inflate(R.layout.clearable_edit_text, this, true);
editText = (EditText) findViewById(R.id.editText);
clearButton = (Button) findViewById(R.id.clearButton);
hookupButton();
}
public ClearableEditText(Context context, AttributeSet atts) {
super(context, atts);
//
// clearButton = (Button) findViewById(R.id.clearButton);
// hookupButton();
}
private void hookupButton() {
Log.w("w", "hookup");
clearButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Log.w("w", "click");
editText.setText("");
}
});
} }
目前可以运行。
但是把:
// clearButton = (Button) findViewById(R.id.clearButton);
// hookupButton();
注释去掉之后,就不能运行,抛InflateException。请问是为什么啊?
LayoutInflater li;
li = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
li.inflate(R.layout.clearable_edit_text, this, true);
正如ls所说,你应该先为其指定一个View