简体   繁体   English

Android:将EditText添加到View错误

[英]Android: Add EditText to View error

bascially I want to have two views. 我基本上要有两种看法。 One view is for the canvas, used for drawing rectangles and another view or adding of new editText boxes whenever a rectangle is drawn. 一个视图用于画布,用于绘制矩形,另一种视图或在绘制矩形时添加新的editText框。 When I run my program, an error occured "java.lang.NullPointerException". 当我运行程序时,发生错误“ java.lang.NullPointerException”。 Is it possible to add the edittext boxes onto the canvas view so that I keep only one view? 是否可以在画布视图上添加edittext框,以便仅保留一个视图?

My code are as follows: 我的代码如下:

public class MainActivity extends Activity {
        public static DrawRect DR;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        DR = new DrawRect(this);

        rectbutton = (Button) findViewById(R.id.rectbutton);

        RelativeLayout mainLayout = (RelativeLayout) findViewById(R.id.RelativeLayout);

        RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
                RelativeLayout.LayoutParams.MATCH_PARENT,
                RelativeLayout.LayoutParams.MATCH_PARENT);


        lp.addRule(RelativeLayout.BELOW, R.id.rectbutton);

        DR.setLayoutParams(lp);

        mainLayout.addView(DR);


    rectbutton.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {

                     addRect(); // in my DrawRect class i have this method to draw rect on canvas
              addEditText();

                     }// onclick

        });
}

    private void addEditText(){

        RelativeLayout editTextLayout = new RelativeLayout(this);
          EditText editText = new EditText(this);
          editTextLayout.addView(editText);
           mainLayout.addView(editTextLayout);

    }
}

Please Advice. 请指教。 Thank you. 谢谢。

Which line its giving error. 哪一行给出错误。 if its giving error in 如果在

 mainLayout.addView(editTextLayout);

means mainLayout is null.you can add EditText in canvas. 表示mainLayout为null。您可以在画布中添加EditText。 the problem is in 问题出在

RelativeLayout mainLayout = (RelativeLayout) findViewById(R.id.RelativeLayout);

check the id in layout xml. 检查布局xml中的ID。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM