I want to programmatically add a TextView and other widgets. Here is how I do it at the moment (everything works):
public void AddTextInput(View view) { // Указываем через ID контейнерный элемент, куда будем добавлять виджет LinearLayout AddItemContainer = (LinearLayout) findViewById(R.id.AddItemContainer); // Устанавливаем разметы виджета LinearLayout.LayoutParams AddedItemsSizing = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT); EditText TextInputA = new EditText(this); // Создаём объект EditText TextInputA.setLayoutParams(AddedItemsSizing); // Задаём ему размеры TextInputA.setHint(R.string.TextInputAValue); // Устанавливаем параметры AddItemContainer.addView(TextInputA); // Добавляем виджет } This method adds only a text input field, but now I want to create a method that adds other widgets (via helper methods). Here is my wrong code:
public void AddItem(int Item_ID){ // Указываем через ID контейнерный элемент, куда будем добавлять виджет LinearLayout AddItemContainer = (LinearLayout) findViewById(R.id.AddItemContainer); // Устанавливаем разметы виджета LinearLayout.LayoutParams AddedItemsSizing = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT); switch (Item_ID){ case 1: AddTextInput(); break; case 2: AddPenInput(); break; case 3: AddPhoto(); break; case 4: AddVideo(); break; case 5: AddSoundRec(); break; } } public void AddTextInput(View view) { EditText TextInputA = new EditText(this); // Создаём объект EditText TextInputA.setLayoutParams(AddedItemsSizing); // Задаём ему размеры TextInputA.setHint(R.string.TextInputAValue); // Устанавливаем параметры AddItemContainer.addView(TextInputA); // Добавляем виджет } Now AddTextInput is an auxiliary method that is called from the main AddItem . The size settings and all widgets will be the same, so I brought them to the main method.
So the questions are:
- How to make
AddItemContainerandAddedItemsSizingavailable inAddTextInputand other helper methods? - In the Switch block, I incorrectly call helper methods. What exactly is incorrect? (I also tried
AddTextInput(View view)andAddTextInput(view)) - The
AddItemmethod has an argument - the widget ID. Did I set theOnClickmethodOnClickin the XML markup?
