I have those code:
public class ContentEditText extends EditText {
/*
* Constructors
*/
public ContentEditText(Context context, AttributeSet attrs, int defStyle)
{
super(context, attrs, defStyle);
}
public ContentEditText(Context context, AttributeSet attrs)
{
super(context, attrs);
}
public ContentEditText(Context context)
{
super(context);
}
/*
* Listener
*/
@Override
protected void onSelectionChanged(int selStart, int selEnd)
{
Toast.makeText(getContext(), "selStart is " + selStart + "selEnd is " + selEnd, Toast.LENGTH_LONG).show();
}
}
and
public class Main extends Activity {
private LinearLayout mainLayout;
private Button bBT;
private Button uBT;
private Button iBT;
private Button lBT;
private EditText titleET;
private ContentEditText contentET;
private Markup markup;
/** onCreate Function */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
initLayout();
setContentView(mainLayout);
}
private void initLayout()
{
// initialize some components by XML layout
mainLayout = (LinearLayout) findViewById(R.id.main_layout);
bBT = (Button) findViewById(R.id.boldBT);
uBT = (Button) findViewById(R.id.underlineBT);
iBT = (Button) findViewById(R.id.italicBT);
lBT = (Button) findViewById(R.id.listBT);
titleET = (EditText) findViewById(R.id.titleET);
// initialize a EditText programmatically
contentET = new ContentEditText(this);
contentET.setGravity(Gravity.TOP);
contentET.setLayoutParams(new LinearLayout.LayoutParams(
LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
// add the EditText to the main layout
mainLayout.addView(contentET);
}
I thought I add contentET to the main layout by the right way, but it doesn’t work, the LogCat said “NullPointerException” for variable contentET, I don’t know why. Anyone can tell me where did i do wrong?
Thanks!
Chang your code to this as the first call should be
setContentViewafter thesuper. Since this is not the case in your above code you are trying to access the layout withoutinflatingit there fore it throwingnullpointerexception