简体   繁体   English

动态按钮Android布局

[英]dynamic buttons Android Layout

I want to create a layout in Android in a java class. 我想在Android中的Java类中创建布局。 I need that the user introduce a number between 1 to 20 and this create the number of butttons that the user has chosen.I want to create dynamic buttons and I have this code: 我需要用户输入一个介于1到20之间的数字,然后创建用户选择的对接数量。我要创建动态按钮,并获得以下代码:

package com.example.nuevo;

import android.app.Activity;
import android.os.Bundle;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.LinearLayout;

public class ControladorResuelto extends Activity {


protected Controlador controlador;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
     requestWindowFeature(Window.FEATURE_NO_TITLE);
      getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                         WindowManager.LayoutParams.FLAG_FULLSCREEN);


        LinearLayout buttonsLayout =  (LinearLayout)findViewById(R.id.linearlayoutUp); 

    int nMallas = controlador.getnMallas();

    LinearLayout.LayoutParams layoutParams = new     LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
    for(int i=0;i<nMallas;i++){
        Button button = new Button(this);
        button.setText("Buttin "+(i+1));
        buttonsLayout.addView(button, layoutParams);******
    }

    setContentView(R.layout.panel_resuelto);
}

I have an error at the line with asterisks 我在带星号的行上有错误

I'm pretty sure it's because you have setContentView(R.layout.panel_resuelto); 我很确定这是因为您有setContentView(R.layout.panel_resuelto); at the end of your onCreate . onCreate的末尾。 Put it at the beginning, else findViewById won't work. 将其放在开头,否则findViewById将不起作用。 I'm guessing you're getting a null pointer exception because the LinearLayout couldn't successfully be created since the content view wasn't set yet. 我猜您会收到一个空指针异常,因为由于尚未设置内容视图,因此无法成功创建LinearLayout

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

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