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。请问是为什么啊?

解决方案 »

  1.   

    本来就应该错啊,没有View,哪来的findViewById??findViewById默认是要在当前的View里面去找的。如果不是当前的View,那也要指定一个。
      

  2.   

    把下面代码添加上去应该就可以了
            LayoutInflater li;
            li = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            li.inflate(R.layout.clearable_edit_text, this, true);
    正如ls所说,你应该先为其指定一个View
      

  3.   

    简单来说,就是根据xml布局文件实例化出来一个对应的view