How to Make dynamic Android View using json2view library

In previous article we discuss about changes Android layout dynamically and here we discuss some more examples about How we can make dynamic Android layouts using json2view library.

You can check installation and implementation of json2view Android library.

  • Create and attach view in the specific Parent (created from xml)
/* load xml layout */
setContentView(R.layout.main);
ViewParent viewParent = (ViewParent) findViewById(R.id.parent_view_id)
JSONObject jsonObject = ... // load from network, sdcard etc
View sampleView = DynamicView.createView(this, jsonObject, viewParent);
  • Create and attach view in the activity
JSONObject jsonObject = ... // load from network, sdcard etc
View sampleView = DynamicView.createView(this, jsonObject);
sampleView.setLayoutParams(
   new WindowManager.LayoutParams(
      WindowManager.LayoutParams.MATCH_PARENT,
      WindowManager.LayoutParams.MATCH_PARENT));
setContentView(sampleView);
  • Create a view and get reference to specific children in the view tree
static public class SampleViewHolder {
   /* we need the View with id testClick */
   @DynamicViewId(id = "testClick")
   public View clickableView;

   /* Constructor must be public */
   public SampleViewHolder() {}
}

...

@Override
protected void onCreate(Bundle savedInstanceState) {
   /* load xml layout */
   setContentView(R.layout.main);
   ViewParent viewParent = (ViewParent) findViewById(R.id.parent_view_id)
   JSONObject jsonObject = ... // load from network, sdcard etc
   /* attach the view from the json in parent and add a tag in sampleView. */
   View sampleView = 
      DynamicView.createView(this, jsonObject, viewParent, SampleViewHolder.class);
/*
   The tag's class is SampleViewHolder. 
   The variables that Annotated @DynamicViewId will be the reference,
   to the actual view created, with id (that is the argument of the annotation).
   In this example the json contains a view with id "testClick"
   and the View return in clickableView
*/
   ((SampleViewHolder) sampleView.getTag())
      .clickableView.setOnClickListener( /* attach to click listener */ );

}

Next Example:

json2view : Some important properties and types

Hope you like this tutorial and if you’ve any problem then comment box is for you.

By Tell Me How

It is a technology blog and admin has excellent experience in programming from 5+ year. You can contact us at ceo.tellmehow@gmail.com

Share your thoughts

Leave a Reply

Loading Facebook Comments ...
Loading Disqus Comments ...