Подтвердить что ты не робот

Динамически добавлять текстовые элементы в линейный режим

Я читал это где-то здесь, и я полностью потерял его, но мог бы использовать некоторую помощь.

Мое приложение вытаскивает имена столбцов из sqlite в массив. Я хочу создать текстовое представление и отредактировать текст для каждого из них (через размер массива), и я помню, где-то читал, что вы можете рассматривать имена переменных textViews как массив, но я не знаю, где это сейчас.

Итак, как бы я динамически создавал textView и editText, но многие ли перечислены в массиве?

Это было что-то вроде

TextView tv[] = new TextView()...

for(...){
tv[i]...
}

Правильно ли это?

Я ценю вашу помощь!

4b9b3361

Ответ 1

Что-то вроде следующего должно быть тем, что вам нужно:

final int N = 10; // total number of textviews to add

final TextView[] myTextViews = new TextView[N]; // create an empty array;

for (int i = 0; i < N; i++) {
    // create a new textview
    final TextView rowTextView = new TextView(this);

    // set some properties of rowTextView or something
    rowTextView.setText("This is row #" + i);

    // add the textview to the linearlayout
    myLinearLayout.addView(rowTextView);

    // save a reference to the textview for later
    myTextViews[i] = rowTextView;
}

Ответ 2

Вы можете добавить TextView во время выполнения, используя следующий код:

LinearLayout lLayout = (LinearLayout) findViewById(R.id.linearlayout2); // Root ViewGroup in which you want to add textviews
for (int i = 0; i < 5; i++) {
    TextView tv = new TextView(this); // Prepare textview object programmatically
    tv.setText("Dynamic TextView" + i);
    tv.setId(i + 5);
    lLayout.addView(tv); // Add to your ViewGroup using this method
}

Ответ 3

Я думаю, что это будет полезно:

int j = 0;

context.getSystemService(Context.WINDOW_SERVICE);
WindowManager manager = (WindowManager) context
                        .getSystemService(Context.WINDOW_SERVICE);
Display display = manager.getDefaultDisplay();

for (int i = 0; i < tabsize; i++) {
    Tab tab = tabSet.get(i);
    if (i == selectedTabId)
        tab.setSelected(true);
    View view = tab.getView();

    TableRow.LayoutParams pCol = new TableRow.LayoutParams();
    pCol.width = display.getWidth() / tabSet.size();

    rowBottom.addView(view, pCol);
}

Ответ 4

Использование ArrayList может помочь вам добавить любое количество текстовых элементов динамически. Вы даже можете удалить определенный TextView из родительского линейного макета. Это эффективный способ памяти. Ниже приведен фрагмент.

ArrayList<TextView> mTextViewList = new ArrayList<>(); //empty list of TextViews

if(condition){ 
    /* can repeat several times*/

    //Create a temporary instance which will be added to the list
    final TextView mTextView = new TextView(this);

    //Add the instance to the ArrayList
    mTextViewList.add(mTextView);

    //Add view to the Parent layout in which you want to add your views
    mLinearLayout.addView(mTextView);
}

//Change the text of 6th(index:5) TextView which was added
mTextViewList.get(5).setText("My Text");

//Remove 2nd(index:1) TextView from the parent LinearLayout
mLinearLayout.removeView(mTextViewList.get(1));

Ответ 5

Итак, скажем, вы создали linearlayout внутри .xml файла, например:

<LinearLayout
    android:orientation="vertical"
    android:id="@+id/linear"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">
</LinearLayout>

теперь код для динамического добавления 5 текстовых просмотров

  LinearLayout linearLayout= (LinearLayout)findViewById(R.id.linear);      //find the linear layout
    linearLayout.removeAllViews();                              //add this too
    for(int i=0; i<5;i++){          //looping to create 5 textviews

        TextView textView= new TextView(this);              //dynamically create textview
        textView.setLayoutParams(new LinearLayout.LayoutParams(             //select linearlayoutparam- set the width & height
                ViewGroup.LayoutParams.MATCH_PARENT, 48));
        textView.setGravity(Gravity.CENTER_VERTICAL);                       //set the gravity too
        textView.setText("Textview: "+i);                                    //adding text
        linearLayout.addView(textView);                                     //inflating :)
    }

Ответ 6

Для меня это решение.

//Установить переменные

TextView t;
ArrayList<TextView> textViewArrayList;
LayoutInflater layoutInflater;
LinearLayout ll_itensobrigatorios

//Расскажите в вашем onCreate

layoutInflater = getLayoutInflater();
createViewItem(new String[]{"Fabio", "Santos", "Programador", "Natal"});

//Это создает вид в макете

    private void createViewItem(String[] nomes) {
            textViewArrayList = new ArrayList<>();

            for(int i = 0; i < nomes.length; i++) {
                View vll = layoutInflater.inflate(R.layout.nomes_tec_item, ll_itensobrigatorios, false);
                t = (TextView) vll.findViewById(R.id.txt_tec_item);
                textViewArrayList.add(t);
                ll_itensobrigatorios.addView(vll);
            }

            for(int i = 0; i < textViewArrayList.size(); i++) {
                textViewArrayList.get(i).setText((i + 1) + " - " + nomes[i]);
            }
}