Updated 1 May 2019
Chips are material design components. Chips can be used to enter information, make selections, filter content, or trigger actions
There are four types of chips 1. Entry Chips, 2.Filter Chips 3.Choice Chips 4. Action Chips
We will make a tag add and remove like functionality using entry chip.
We have defined a ChipGroup in XML file to add Chip view dynamically.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
<?xml version="1.0" encoding="utf-8"?> <LinearLayout android:id="@+id/filter_container" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" > <android.support.design.chip.ChipGroup android:id="@+id/tag_group" android:layout_width="match_parent" android:layout_height="wrap_content" /> </LinearLayout> |
Add Chip View to ChipGroup
Entry chip has a remove icon along with a chip Thumbnail. We have set setOnCloseIconClickListener on entry Chip instance to remove tags.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
import android.os.Bundle; import android.support.design.chip.Chip; import android.support.design.chip.ChipGroup; import android.support.v7.app.AppCompatActivity; import android.util.TypedValue; import android.view.View; import java.util.ArrayList; import java.util.List; public class TagActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_tag); setTag(tagList); //Pass tag list to show tag view. } private void setTag(final List<String> tagList) { final ChipGroup chipGroup = findViewById(R.id.tag_group); for (int index = 0; index < tagList.size(); index++) { final String tagName = tagList.get(index); final Chip chip = new Chip(this); int paddingDp = (int) TypedValue.applyDimension( TypedValue.COMPLEX_UNIT_DIP, 10, getResources().getDisplayMetrics() ); chip.setPadding(paddingDp, paddingDp, paddingDp, paddingDp); chip.setText(tagName); chip.setCloseIconResource(R.drawable.ic_action_navigation_close); chip.setCloseIconEnabled(true); //Added click listener on close icon to remove tag from ChipGroup chip.setOnCloseIconClickListener(new View.OnClickListener() { @Override public void onClick(View v) { tagList.remove(tagName); chipGroup.removeView(chip); } }); chipGroup.addView(chip); } } } |
If you have more details or questions, you can reply to the received confirmation email.
Back to Home
Nice tutorial