Adding EditText to a layout in android with for-lo

2019-07-17 02:24发布

let me introduce you to my issue:

I have just begun with programming for android. Now I want to create a little app that asks for the amount of players and then a new screen pops up with as many as EditText fields as the amount of players.

Example: I type in the amount of players (4), then I press send, the next screen is filled with 4 EditText fields asking for the players names.

Here's the code:

Method that asks for the amount of players:

    public void gaVerder (View view){
    Intent i = new Intent(getApplicationContext(), NamenPersonen.class);

    String aantal = e.getText().toString();
    i.putExtra("aantal", aantal);

    startActivity(i);
}

Method that delivers the EditText fields:

LinearLayout ll;
EditText editText;

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


    Intent intent = getIntent();

    int aantal = Integer.parseInt(intent.getStringExtra("aantal"));


    List<EditText> myList = new ArrayList<EditText>();

    EditText myEt1 = new EditText(this);
    myEt1.setHint("Geef uw naam in.");
    myList.add(myEt1);


    for(int i=0;i<aantal;i++)
    {
        editText = new EditText(this);
        editText.setHint("Geef een naam in");


        ll.addView(editText);
    }


    setupActionBar();
    setContentView(R.layout.namenpersonenxml);
}

It's the for-loop part and adding it to the lay-out that isn't working. Also I can't figure out how to debug it, I'm used to debugging Java applications in Netbeans (for android I'm using Eclipse).

2条回答
淡お忘
2楼-- · 2019-07-17 02:58

You need to initialize LinearLayout ll.

 LinearLayout ll;
 EditText editText;
 @Override
 protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.namenpersonenxml);
 ll = (LinearLayout) findViewById(R.id.linearlayout);
 Intent intent = getIntent();
 int aantal = Integer.parseInt(intent.getStringExtra("aantal"));
 for(int i=0;i<aantal;i++)
 {
    editText = new EditText(this);
    editText.setHint("Geef een naam in");
    ll.addView(editText);
 }
查看更多
放荡不羁爱自由
3楼-- · 2019-07-17 03:18

You forgot to initialize your LinearLayout in which you're adding your EditTexts. At the moment, the program doesn't know which layout you would like to add your views to. So, in your onCreate() method, you should add the following code:

ll = (LinearLayout) findViewById(R.id.'nameOfYourLayout');
查看更多
登录 后发表回答