Adding EditText to a layout in android with for-loop

你说的曾经没有我的故事 提交于 2019-12-12 18:48:03

问题


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).


回答1:


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);
 }



回答2:


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');


来源:https://stackoverflow.com/questions/21554985/adding-edittext-to-a-layout-in-android-with-for-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!