web-dev-qa-db-fra.com

Ajouter et supprimer des vues dans Android dynamiquement?

Comment ajouter et supprimer des vues telles que TextViews à partir de Android comme sur le stock d'origine Android dans l'écran des contacts où vous appuyez sur une petite icône à droite du champ et il ajoute ou supprime un champ qui consiste en un TextView et un editTextView (d'après ce que je peux voir).

Des exemples sur comment y parvenir?

113
jonney

ViewParents en général ne peut pas supprimer les vues, mais ViewGroups le peut. Vous devez attribuer à votre parent un ViewGroup (s'il s'agit d'un ViewGroup) pour accomplir ce que vous voulez.

Par exemple:

View namebar = View.findViewById(R.id.namebar);
((ViewGroup) namebar.getParent()).removeView(namebar);

Notez que tous les Layouts sont ViewGroups.

201
Thomas Ahle

J'ai besoin de la même fonctionnalité décrite dans cette question. Voici ma solution et le code source: https://github.com/laoyang/Android-dynamic-views . Et vous pouvez voir la vidéo de démonstration en action ici: http://www.youtube.com/watch?v=4HeqyG6FDhQ

Disposition

En gros, vous aurez deux fichiers de mise en page XML:

  • Une vue horizontale de lignes LinearLayout avec une TextEdit, une Spinner et une ImageButton à supprimer.
  • Une vue de conteneur verticale LinearLayout avec juste un bouton Ajouter nouveau .

Contrôle

Dans le code Java, vous allez ajouter et supprimer des vues de lignes dans le conteneur de manière dynamique, en utilisant les options inflate, addView, removeView, etc. Il existe un contrôle de la visibilité pour une meilleure expérience utilisateur dans l'application stock Android. Vous devez ajouter un TextWatcher pour la vue EditText dans chaque ligne: lorsque le texte est vide, vous devez masquer le bouton Ajouter nouveau et le bouton Supprimer. Dans mon code, j'ai écrit une fonction d'assistance void inflateEditRow(String) pour toute la logique.

Autres astuces

  • Définissez Android:animateLayoutChanges="true" in xml pour activer l'animation
  • Utilisez un fond transparent personnalisé avec le sélecteur enfoncé pour que les boutons soient visuellement identiques à ceux de l'application stock Android.

Code source

Le code Java de l'activité principale (Cela explique toute la logique, mais quelques propriétés sont définies dans les fichiers de présentation XML, veuillez vous reporter à la source Github pour obtenir une solution complète):

public class MainActivity extends Activity {
// Parent view for all rows and the add button.
private LinearLayout mContainerView;
// The "Add new" button
private Button mAddButton;
// There always should be only one empty row, other empty rows will
// be removed.
private View mExclusiveEmptyView;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.row_container);
    mContainerView = (LinearLayout) findViewById(R.id.parentView);
    mAddButton = (Button) findViewById(R.id.btnAddNewItem);

    // Add some examples
    inflateEditRow("Xiaochao");
    inflateEditRow("Yang");
}

// onClick handler for the "Add new" button;
public void onAddNewClicked(View v) {
    // Inflate a new row and hide the button self.
    inflateEditRow(null);
    v.setVisibility(View.GONE);
}

// onClick handler for the "X" button of each row
public void onDeleteClicked(View v) {
    // remove the row by calling the getParent on button
    mContainerView.removeView((View) v.getParent());
}

// Helper for inflating a row
private void inflateEditRow(String name) {
    LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    final View rowView = inflater.inflate(R.layout.row, null);
    final ImageButton deleteButton = (ImageButton) rowView
            .findViewById(R.id.buttonDelete);
    final EditText editText = (EditText) rowView
            .findViewById(R.id.editText);
    if (name != null && !name.isEmpty()) {
        editText.setText(name);
    } else {
        mExclusiveEmptyView = rowView;
        deleteButton.setVisibility(View.INVISIBLE);
    }

    // A TextWatcher to control the visibility of the "Add new" button and
    // handle the exclusive empty view.
    editText.addTextChangedListener(new TextWatcher() {

        @Override
        public void afterTextChanged(Editable s) {

            // Some visibility logic control here:
            if (s.toString().isEmpty()) {
                mAddButton.setVisibility(View.GONE);
                deleteButton.setVisibility(View.INVISIBLE);
                if (mExclusiveEmptyView != null
                        && mExclusiveEmptyView != rowView) {
                    mContainerView.removeView(mExclusiveEmptyView);
                }
                mExclusiveEmptyView = rowView;
            } else {
                if (mExclusiveEmptyView == rowView) {
                    mExclusiveEmptyView = null;
                }
                mAddButton.setVisibility(View.VISIBLE);
                deleteButton.setVisibility(View.VISIBLE);
            }
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                int after) {
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before,
                int count) {
        }
    });

    // Inflate at the end of all rows but before the "Add new" button
    mContainerView.addView(rowView, mContainerView.getChildCount() - 1);
}
37
xy uber.com

C'est ma manière générale:

View namebar = view.findViewById(R.id.namebar);
ViewGroup parent = (ViewGroup) namebar.getParent();
if (parent != null) {
    parent.removeView(namebar);
}
9
Cabezas

Bonjour, Vous pouvez essayer de cette façon en ajoutant une disposition relative et en ajoutant du texte dans cela.

LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
            (LayoutParams.WRAP_CONTENT), (LayoutParams.WRAP_CONTENT));

RelativeLayout relative = new RelativeLayout(getApplicationContext());
relative.setLayoutParams(lp);

TextView tv = new TextView(getApplicationContext());
tv.setLayoutParams(lp);

EditText edittv = new EditText(getApplicationContext());
edittv.setLayoutParams(lp);

relative.addView(tv);
relative.addView(edittv);
6
krunal shah

Pour ajouter le bouton

LinearLayout dynamicview = (LinearLayout)findViewById(R.id.buttonlayout);
LinearLayout.LayoutParams  lprams = new LinearLayout.LayoutParams(  LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT);

Button btn = new Button(this);
btn.setId(count);
final int id_ = btn.getId();
btn.setText("Capture Image" + id_);
btn.setTextColor(Color.WHITE);
btn.setBackgroundColor(Color.rgb(70, 80, 90));
dynamicview.addView(btn, lprams);
btn = ((Button) findViewById(id_));
btn.setOnClickListener(this);

Pour enlever le bouton

ViewGroup layout = (ViewGroup) findViewById(R.id.buttonlayout);
View command = layout.findViewById(count);
layout.removeView(command);
4
Amaresh Jana
4
Asahi

Utilisez simplement myView.setVisibility(View.GONE); pour le supprimer complètement. Mais si vous voulez réserver l’espace occupé dans son parent, utilisez myView.setVisibility(View.INVISIBLE);

4
Soheil Setayeshi

Salut Commencez par écrire la classe d'activité. La classe suivante a un nom de catégorie et un petit bouton d'ajout. Lorsque vous appuyez sur le bouton Ajouter (+), il ajoute la nouvelle ligne qui contient un EditText et un ImageButton qui supprime la ligne.

package com.blmsr.manager;

import Android.app.Activity;
import Android.app.ListActivity;
import Android.content.Intent;
import Android.graphics.Color;
import Android.graphics.drawable.Drawable;
import Android.os.Bundle;
import Android.util.Log;
import Android.view.Menu;
import Android.view.MenuItem;
import Android.view.View;
import Android.widget.Button;
import Android.widget.EditText;
import Android.widget.ImageButton;
import Android.widget.LinearLayout;
import Android.widget.ScrollView;
import Android.widget.TableLayout;
import Android.widget.TableRow;
import Android.widget.TextView;

import com.blmsr.manager.R;
import com.blmsr.manager.dao.CategoryService;
import com.blmsr.manager.models.CategoryModel;
import com.blmsr.manager.service.DatabaseService;

public class CategoryEditorActivity extends Activity {
    private final String CLASSNAME = "CategoryEditorActivity";
    LinearLayout itsLinearLayout;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_category_editor);

        itsLinearLayout = (LinearLayout)findViewById(R.id.linearLayout2);
    }
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_category_editor, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    switch (item.getItemId()) {
        case R.id.action_delete:
            deleteCategory();
            return true;
        case R.id.action_save:
            saveCategory();
            return true;
        case R.id.action_settings:
            return true;
        default:
            return super.onOptionsItemSelected(item);
    }
}

/**
 * Adds a new row which contains the EditText and a delete button.
 * @param theView
 */
public void addField(View theView)
{
    itsLinearLayout.addView(tableLayout(), itsLinearLayout.getChildCount()-1);
}

// Using a TableLayout as it provides you with a neat ordering structure

private TableLayout tableLayout() {
    TableLayout tableLayout = new TableLayout(this);
    tableLayout.addView(createRowView());
    return tableLayout;
}

private TableRow createRowView() {
    TableRow tableRow = new TableRow(this);
    tableRow.setPadding(0, 10, 0, 0);

    EditText editText = new EditText(this);
    editText.setWidth(600);
    editText.requestFocus();

    tableRow.addView(editText);
    ImageButton btnGreen = new ImageButton(this);
    btnGreen.setImageResource(R.drawable.ic_delete);
    btnGreen.setBackgroundColor(Color.TRANSPARENT);
    btnGreen.setOnClickListener(anImageButtonListener);
    tableRow.addView(btnGreen);

    return tableRow;
}

/**
 * Delete the row when clicked on the remove button.
 */
private View.OnClickListener anImageButtonListener = new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        TableRow anTableRow = (TableRow)v.getParent();
        TableLayout anTable = (TableLayout) anTableRow.getParent();
        itsLinearLayout.removeView(anTable);

    }
};

/**
 * Save the values to db.
 */
private void saveCategory()
{
    CategoryService aCategoryService = DatabaseService.getInstance(this).getCategoryService();
    aCategoryService.save(getModel());
    Log.d(CLASSNAME, "successfully saved model");

    Intent anIntent = new Intent(this, CategoriesListActivity.class);
    startActivity(anIntent);

}

/**
 * performs the delete.
 */
private void deleteCategory()
{

}

/**
 * Returns the model object. It gets the values from the EditText views and sets to the model.
 * @return
 */
private CategoryModel getModel()
{
    CategoryModel aCategoryModel = new CategoryModel();
    try
    {
        EditText anCategoryNameEditText = (EditText) findViewById(R.id.categoryNameEditText);
        aCategoryModel.setCategoryName(anCategoryNameEditText.getText().toString());
        for(int i= 0; i< itsLinearLayout.getChildCount(); i++)
        {
            View aTableLayOutView = itsLinearLayout.getChildAt(i);
            if(aTableLayOutView instanceof  TableLayout)
            {
                for(int j= 0; j< ((TableLayout) aTableLayOutView).getChildCount() ; j++ );
                {
                    TableRow anTableRow = (TableRow) ((TableLayout) aTableLayOutView).getChildAt(i);
                    EditText anEditText =  (EditText) anTableRow.getChildAt(0);
                    if(StringUtils.isNullOrEmpty(anEditText.getText().toString()))
                    {
                        // show a validation message.
                        //return aCategoryModel;
                    }

                    setValuesToModel(aCategoryModel, i + 1, anEditText.getText().toString());
                }
            }
        }
    }
    catch (Exception anException)
    {
        Log.d(CLASSNAME, "Exception occured"+anException);
    }

    return aCategoryModel;
}

/**
 * Sets the value to model.
 * @param theModel
 * @param theFieldIndexNumber
 * @param theFieldValue
 */
private void setValuesToModel(CategoryModel theModel, int theFieldIndexNumber, String theFieldValue)
{
    switch (theFieldIndexNumber)
    {
        case 1 :
            theModel.setField1(theFieldValue);
            break;
        case 2 :
            theModel.setField2(theFieldValue);
            break;
        case 3 :
            theModel.setField3(theFieldValue);
            break;
        case 4 :
            theModel.setField4(theFieldValue);
            break;
        case 5 :
            theModel.setField5(theFieldValue);
            break;
        case 6 :
            theModel.setField6(theFieldValue);
            break;
        case 7 :
            theModel.setField7(theFieldValue);
            break;
        case 8 :
            theModel.setField8(theFieldValue);
            break;
        case 9 :
            theModel.setField9(theFieldValue);
            break;
        case 10 :
            theModel.setField10(theFieldValue);
            break;
        case 11 :
            theModel.setField11(theFieldValue);
            break;
        case 12 :
            theModel.setField12(theFieldValue);
            break;
        case 13 :
            theModel.setField13(theFieldValue);
            break;
        case 14 :
            theModel.setField14(theFieldValue);
            break;
        case 15 :
            theModel.setField15(theFieldValue);
            break;
    }
}
}

2. Écrivez le code XML Layout comme indiqué ci-dessous.

<LinearLayout xmlns:Android="http://schemas.Android.com/apk/res/Android"
xmlns:tools="http://schemas.Android.com/tools"
Android:layout_width="fill_parent"
Android:layout_height="fill_parent"
Android:orientation="vertical"
Android:background="#006699"
Android:paddingBottom="@dimen/activity_vertical_margin"
Android:paddingLeft="@dimen/activity_horizontal_margin"
Android:paddingRight="@dimen/activity_horizontal_margin"
Android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.blmsr.manager.CategoryEditorActivity">

<LinearLayout
    Android:id="@+id/addCategiryNameItem"
    Android:layout_width="wrap_content"
    Android:layout_height="wrap_content"
    Android:orientation="horizontal">

    <TextView
        Android:id="@+id/categoryNameTextView"
        Android:layout_width="200dp"
        Android:layout_height="wrap_content"
        Android:text="@string/lbl_category_name"
        Android:textStyle="bold"
        />

    <TextView
        Android:id="@+id/categoryIconName"
        Android:layout_width="100dp"
        Android:layout_height="wrap_content"
        Android:text="@string/lbl_category_icon_name"
        Android:textStyle="bold"
        />

</LinearLayout>

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

    <EditText
        Android:id="@+id/categoryNameEditText"
        Android:layout_width="200dp"
        Android:layout_height="wrap_content"
        Android:hint="@string/lbl_category_name"
        Android:inputType="textAutoComplete" />


    <ScrollView
        Android:id="@+id/scrollView1"
        Android:layout_width="match_parent"
        Android:layout_height="wrap_content">

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

        <LinearLayout
            Android:id="@+id/linearLayout3"
            Android:layout_width="match_parent"
            Android:layout_height="wrap_content"
            Android:orientation="horizontal">


            </LinearLayout>

            <ImageButton
                Android:id="@+id/addField"
                Android:layout_width="50dp"
                Android:layout_height="50dp"
                Android:layout_below="@+id/addCategoryLayout"
                Android:src="@drawable/ic_input_add"
                Android:onClick="addField"
                />
        </LinearLayout>
    </ScrollView>
</LinearLayout>
  1. Une fois que vous avez terminé votre vue sera comme indiqué ci-dessous enter image description here
3
Sudhakar
//MainActivity :





 package com.edittext.demo;
    import Android.app.Activity;
    import Android.os.Bundle;
    import Android.text.TextUtils;
    import Android.view.Menu;
    import Android.view.View;
    import Android.view.View.OnClickListener;
    import Android.widget.Button;
    import Android.widget.EditText;
    import Android.widget.LinearLayout;
    import Android.widget.Toast;

    public class MainActivity extends Activity {

        private EditText edtText;
        private LinearLayout LinearMain;
        private Button btnAdd, btnClear;
        private int no;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);

            edtText = (EditText)findViewById(R.id.edtMain);
            btnAdd = (Button)findViewById(R.id.btnAdd);
            btnClear = (Button)findViewById(R.id.btnClear);
            LinearMain = (LinearLayout)findViewById(R.id.LinearMain);

            btnAdd.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (!TextUtils.isEmpty(edtText.getText().toString().trim())) {
                        no = Integer.parseInt(edtText.getText().toString());
                        CreateEdittext();
                    }else {
                        Toast.makeText(MainActivity.this, "Please entere value", Toast.LENGTH_SHORT).show();
                    }
                }
            });

            btnClear.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    LinearMain.removeAllViews();
                    edtText.setText("");
                }
            });

            /*edtText.addTextChangedListener(new TextWatcher() {
                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {

                }
                @Override
                public void beforeTextChanged(CharSequence s, int start, int count,int after) {
                }
                @Override
                public void afterTextChanged(Editable s) {
                }
            });*/

        }

        protected void CreateEdittext() {
            final EditText[] text = new EditText[no];
            final Button[] add = new Button[no];
            final LinearLayout[] LinearChild = new LinearLayout[no];
            LinearMain.removeAllViews();

            for (int i = 0; i < no; i++){

                View view = getLayoutInflater().inflate(R.layout.edit_text, LinearMain,false);
                text[i] = (EditText)view.findViewById(R.id.edtText);
                text[i].setId(i);
                text[i].setTag(""+i);

                add[i] = (Button)view.findViewById(R.id.btnAdd);
                add[i].setId(i);
                add[i].setTag(""+i);

                LinearChild[i] = (LinearLayout)view.findViewById(R.id.child_linear);
                LinearChild[i].setId(i);
                LinearChild[i].setTag(""+i);

                LinearMain.addView(view);

                add[i].setOnClickListener(new View.OnClickListener() {
                    public void onClick(View v) {
                        //Toast.makeText(MainActivity.this, "add text "+v.getTag(), Toast.LENGTH_SHORT).show();
                        int a = Integer.parseInt(text[v.getId()].getText().toString());
                        LinearChild[v.getId()].removeAllViews();
                        for (int k = 0; k < a; k++){

                            EditText text = (EditText) new EditText(MainActivity.this);
                            text.setId(k);
                            text.setTag(""+k);

                            LinearChild[v.getId()].addView(text);
                        }
                    }
                });
            }
        }

        @Override
        public boolean onCreateOptionsMenu(Menu menu) {
            // Inflate the menu; this adds items to the action bar if it is present.
            getMenuInflater().inflate(R.menu.main, menu);
            return true;
        }

    }

// Ajoute maintenant xml main

<LinearLayout xmlns:Android="http://schemas.Android.com/apk/res/Android"
xmlns:tools="http://schemas.Android.com/tools"
Android:layout_width="match_parent"
Android:layout_height="match_parent"
Android:orientation="vertical"
tools:context=".MainActivity" >

<LinearLayout
    Android:layout_width="match_parent"
    Android:layout_height="wrap_content"
    Android:layout_marginTop="10dp"
    Android:orientation="horizontal" >

    <EditText
        Android:id="@+id/edtMain"
        Android:layout_width="0dp"
        Android:layout_height="wrap_content"
        Android:layout_marginLeft="20dp"
        Android:layout_weight="1"
        Android:ems="10"
        Android:hint="Enter value" >

        <requestFocus />
    </EditText>

    <Button
        Android:id="@+id/btnAdd"
        Android:layout_width="wrap_content"
        Android:layout_height="wrap_content"
        Android:layout_marginLeft="10dp"
        Android:text="Add" />

    <Button
        Android:id="@+id/btnClear"
        Android:layout_width="wrap_content"
        Android:layout_height="wrap_content"
        Android:layout_marginLeft="5dp"
        Android:layout_marginRight="5dp"
        Android:text="Clear" />
</LinearLayout>

<ScrollView
    Android:layout_width="match_parent"
    Android:layout_height="match_parent"
    Android:layout_margin="10dp" >

    <LinearLayout
        Android:id="@+id/LinearMain"
        Android:layout_width="match_parent"
        Android:layout_height="match_parent"
        Android:orientation="vertical" >
    </LinearLayout>
</ScrollView>

// ajoute maintenant le fichier XML de la vue.

<LinearLayout xmlns:Android="http://schemas.Android.com/apk/res/Android"
Android:layout_width="match_parent"
Android:layout_height="wrap_content"
Android:orientation="vertical" >

<LinearLayout
    Android:layout_width="match_parent"
    Android:layout_height="wrap_content"
    Android:layout_marginTop="10dp"
    Android:orientation="horizontal" >

    <EditText
        Android:id="@+id/edtText"
        Android:layout_width="wrap_content"
        Android:layout_height="wrap_content"
        Android:layout_marginLeft="20dp"
        Android:ems="10" />

    <Button
        Android:id="@+id/btnAdd"
        Android:layout_width="wrap_content"
        Android:layout_height="wrap_content"
        Android:layout_marginLeft="10dp"
        Android:text="Add" />
</LinearLayout>

<LinearLayout
    Android:id="@+id/child_linear"
    Android:layout_width="match_parent"
    Android:layout_height="wrap_content"
    Android:layout_marginLeft="30dp"
    Android:layout_marginRight="10dp"
    Android:layout_marginTop="5dp"
    Android:orientation="vertical" >
</LinearLayout>
0
Dev 9