java - 无法从代码向 XML 布局添加 View

标签 java android layout android-edittext

我有那些代码:

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”,我不知道为什么。谁能告诉我我哪里做错了? 谢谢!

最佳答案

将您的代码更改为此,因为第一个调用应该是 super 之后的 setContentView。因为在你上面的代码中不是这种情况,你试图在没有 inflating 的情况下访问布局,因此它抛出 nullpointer exception

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

关于java - 无法从代码向 XML 布局添加 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8321558/

相关文章:

java - 当 JButton 上的文本发生变化时创建 JButton 的永久隐藏值

java - 如何限制Firestore中添加和删除监听器的数量?

Android布局打包

java - 编译器错误 "archive for required library could not be read"- Spring Tool Suite

java - 如何解决 "Unhandled exception type ClassNotFoundException"和 "Vector is a raw type"错误?

android - 如何从异常中找到资源名称

android - React-native:在 Android 中不会调用切换组件 onValueChange

java - 自定义可拖动布局管理器

layout - Dijit.Dialog 中的 Dojo/Dijit BorderContainer

java - java类的字段应该总是final的吗?这是一个很好的做法吗?