2011-11-30 43 views
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”,我不知道为什么。任何人都可以告诉我我在哪里做错了? 谢谢!

回答

2

长您的代码作为第一个电话应该是setContentViewsuper。因为这不是你想不inflating有访问布局它脱颖而出它抛出nullpointer异常

@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.your_xml_file);   
    initLayout(); 
} 
+0

它仍然是同样的错误在你上面的代码的情况下:NullPointerException异常,和logcat的点线:的setContentView( mainLayout); – Leo

+0

ahh,对不起,我错过了仔细阅读你的答案,它应该是setContentView(R.layout.your_xml_file);它完美的工作。谢谢:) – Leo

+0

NIce听到:) – ingsaurabh