Tuesday, January 5, 2016

Android, Add New Element on the Fly with LayoutInflater

Adding new element in Android view not as easy as using jquery.js and add an element
into html document. After googling for a while i found out that LayoutInflater is the tool.

I found good answer in StackOverflow pointing this out:

  1. First declare your inflater.
    LayoutInflater inflater = (LayoutInflater)getApplicationContext().getSystemService
  2. Identify and inflate the new view you seek to project on the current view.
    View view = inflater.inflate(R.layout.new_layout,null);
  3. You would want to add your new inflated view to your layout.

Plug that code into my app becomes:

# ...
LayoutInflater li = (LayoutInflater) LayoutInflater.from(getApplicationContext() );
View cv = li.inflate(R.layout.list_targetitem, null);
TextView item1 = (TextView) cv.findViewById(R.id.targetlist_tview);
item1.setText( "TARGET " + MyActivity.indexTarget + "\n" + locationName );

And that code works just the same as jquery.js/HTML. But one question was arised,
how i got the id of the element? Well no luck of finding how to set new element' ID attribute.
One of the StackOverflow shares or somewhere i don`t remember at all did mention that
to hold the new element into HashMap that we could easily retreived later.

This is the way i done it

public class MyActivity extends AppCompatActity implements ... {

    LinearLayout targetHashMapView;

    protected void onCreate(Bundle svdInstance){
        // Noticed that R.id.init_target_location is pointing to a LinearLayout tag/element
        // inside MyActivity layout xml file
        targetHashMapView = (LinearLayout) findViewById(R.id.init_target_location);

Thus adding the new element, append the R.id.init_target_location LinearLayout element. ^,^

No comments: