动态添加布局到父级。 (空指针异常)

时间:2018-02-20 20:19:32

标签: android-layout

我想在我的Activity的RelativeLayout中添加一个Linear Layout,这是Activity附带的一个。但是当我添加时,我得到一个nullpointerException。

我想要实现这种层次结构:

  Layout principal

     Layout contenedor

          edittext    edittext    edittext

我做错了什么?

Hier是守则:

LinearLayout contenedorPuntajes;
Button cargarPuntajes;
RelativeLayout principal;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    principal = (RelativeLayout) findViewById(R.id.layoutPrincipal);//i have given an id to the main RelativeLayout that comes with the activity (default) 


    setContentView(R.layout.activity_cargar_puntajes);

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

    contenedorPuntajes= new LinearLayout(this);
    contenedorPuntajes.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));


    contenedorPuntajes.setOrientation(LinearLayout.HORIZONTAL);

    ArrayList<EditText> editTexts = new ArrayList<>();
    for (int i=0; i<3;i++){
        EditText etxt = new EditText(this);
        etxt.setHint("00");
        etxt.setMaxEms(2);
        editTexts.add(etxt);
        contenedorPuntajes.addView(etxt);
    }

    cargarPuntajes.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            principal.addView(contenedorPuntajes);//here i get the exception
        }
    });

三江源

1 个答案:

答案 0 :(得分:0)

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    principal = (RelativeLayout) findViewById(R.id.layoutPrincipal);//i have given an id to the main RelativeLayout that comes with the activity (default) 


    setContentView(R.layout.activity_cargar_puntajes);

您应该重新排序setContentViewfindViewById行。首先设置内容视图,然后查找视图。