【问题标题】:Android: NullPointerException when adding a button to a layout programmatically?Android:以编程方式将按钮添加到布局时出现 NullPointerException?
【发布时间】:2014-04-26 16:43:16
【问题描述】:

我正在尝试编写代码,该代码将弹出一个输入框并将一个按钮添加到 LinearLayout 中,并将用户输入的任何内容作为按钮的文本。这是我的弹出框代码

public void submitPublicQuestion(View view) {
    AlertDialog.Builder question = new AlertDialog.Builder(this);

    question.setTitle("Submit Question");
    question.setMessage("Enter question: ");

    // Set an EditText view to get user input 
    final EditText input = new EditText(this);
    final View queue = this.findViewById(R.layout.activity_main_class);
    final Button newBtn = new Button(this);
    newBtn.setId((int) (Math.random() * 0xFFFFFFFF));
    question.setView(input);

    question.setPositiveButton("Submit", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int whichButton) {
            String value = input.getText().toString();

            newBtn.setText(value);
            newBtn.setMinWidth(550);
            newBtn.setTextSize(24);
            newBtn.setVisibility(View.VISIBLE);


            LinearLayout ll = (LinearLayout)findViewById(R.id.CSQuestionsLayout);
            LayoutParams lp = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);

            newBtn.setLayoutParams(lp);

            ll.addView(newBtn);
            goToQueue(queue);
        }
    });

    question.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int whichButton) {

        }
    });

    question.show();

}

当我调用ll.addView(newBtn); 时,此代码会导致 NullPointerException。这里有什么问题?

【问题讨论】:

    标签: android android-layout nullpointerexception android-view android-button


    【解决方案1】:

    我猜它抱怨 ll 是空的。 在你的 xml 中确保有 id 为 CSQuestionsLayout 的线性布局

    LinearLayout ll = (LinearLayout)findViewById(R.id.CSQuestionsLayout);
    

    【讨论】:

    • 我在 XML 中有一个具有该 ID 的对象。它与附加此代码的 XML 不同是否重要? 编辑: 确实如此。我是个白痴。你知道如何在代码中引用不同的 XML 文件吗?
    • 也许你可以在设置肯定按钮之前尝试将final LinearLayout ll = (LinearLayout)findViewById(R.id.CSQuestionsLayout);放在onclick之外。
    【解决方案2】:

    我认为您可以使用 LayoutInflator 来引用另一个未在 setContentView 中使用的 xml y,如下所示

       LayoutInflater layoutInflater = (LayoutInflater)getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);    
                         View view = layoutInflater.inflate(R.layout.y, null );
        ImageView img=(ImageView)view.findViewById(R.id.imgView);
    

    【讨论】:

      【解决方案3】:

      你应该添加,

              final Button newBtn = new Button(this);
              setContentView(newBtn);
      

      用于在 xml 中没有 id 的按钮

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-03-30
        • 1970-01-01
        • 2013-05-03
        • 1970-01-01
        • 2011-11-03
        • 2020-10-22
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多