1
一個視圖添加到XML佈局我有那些代碼:無法從代碼
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();
}
}
和
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);
}
我想我通過正確的方式添加到contentET主要佈局,但它不起作用,LogCat對變量contentET說「NullPointerException」,我不知道爲什麼。任何人都可以告訴我我在哪裏做錯了? 謝謝!
它仍然是同樣的錯誤在你上面的代碼的情況下:NullPointerException異常,和logcat的點線:的setContentView( mainLayout); – Leo
ahh,對不起,我錯過了仔細閱讀你的答案,它應該是setContentView(R.layout.your_xml_file);它完美的工作。謝謝:) – Leo
NIce聽到:) – ingsaurabh