Create dynamic tables in android. New view vs inflater

925 Views Asked by At

I would like to create dynamic table in android (custom number of rows and columns). Minimum sdk is 3.0

I suppose to crate it via one of 2 ways:

1) via creating new TextView

TableRow tr = ....;

for ( i = 0; i < NumOfRows .... ) {
    TextView tv = new TextView(this);
    tv.setLayoutParams(...);
    tv.setText("Text I wanna to see");
    tr.add(tv);
}

2) via inflater

LayoutInflater inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

for ( i = 0; i < NumOfRows .... ) {
    TextView tv = (TextView) mInflater.inflate(R.layout.my_cell_layout, null, false)
                    .findViewById(R.id.my_cell_item);
    tv.setText("Text I wanna to see");
    tr.add(tv);
}

3) Your way :)

What is faster? What should I select?enter code here

3

There are 3 best solutions below

0
On BEST ANSWER

It's all as per your requirement that which is better.

from link http://www.aslingandastone.com/2010/dynamically-changing-android-views/

Because layouts can be created either in XML or in code, you could probably make do without ever having to do dynamic XML layout loading. That being said, there are some clear advantages as to why I think one may want to do so:

Code cleanliness. Doing anything more than basic layouts in code can get very messy, very fast. Code re-use. It’s extremely easy to inflate an XML layout into a specified view with one or two lines of code Performance. Creating the objects necessary for an in-code layout leads to unnecessary garbage collection. As per the Android Designing for Performance article, “avoid creating short-term temporary objects if you can.” Attribute availability. Defining Views in an XML layout exposes attributes that are not always available by object methods.

* Possible disadvantages:

It make take more time to do an XML layout versus defining the layout in code, especially if there are only one or two interface elements that need to be changed. *

0
On

To find out which is faster, implement both methods and use the method profiling utility, TraceView. That being said, its easier to maintain an XML file when making changes than it is to modify code. So, if I were you, I would prefer technique #2.

0
On

I recently created a class to create and display tables in Android. Please check and complete if needed.

to do: Dynamic style

... TableMaker class:

import android.content.Context;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.LinearLayout;
import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;

/*
IMPORTANT IF YOU NEED PUT TABLE CSS FILE WITH NAME style.css   IN ASSETS FOLDER!
 */
public class SaycoderTableMaker extends LinearLayout {
    WebView webView;

    public SaycoderTableMaker(Context context, LinearLayout rootLayout, ArrayList<String> tableHeadItems, JSONArray dataItemArrayList) {
        super(context);
        initialize(context, rootLayout, tableHeadItems, dataItemArrayList);
    }


    public void initialize(Context context, LinearLayout rootLayout, ArrayList<String> tableHeadItems, JSONArray dataItemArrayList) {
        webView = new WebView(context);
        webView.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
        webView.loadDataWithBaseURL("file:///android_asset/", htmlTableMaker(tableHeadItems, dataItemArrayList), "text/html", "UTF-8", null);
        rootLayout.addView(webView);
    }

    private String htmlTableMaker(ArrayList<String> tableHeadItems, JSONArray jsonDataArray) {
        StringBuilder tabale = new StringBuilder("<HTML><HEAD><LINK href='style.css' type='text/css' rel='stylesheet'/>" +
                "<style>" +
                ".stickyHead {" +
                "    position: sticky;" +
                "    top: 0;" +
                "}" +
                "</style>" +
                "</HEAD><body>" +
                "<table  width='100%' border='0' align='center' cellspacing='0' cellpadding='0'>");
        String newTrEnd = "</tr>";
        String tdStart = "<td width= '20' align='center'><font face='Arial, Helvetica, sans-serif' size='1'>";
        String tdEnd = "</td>";
        //.........append table head
        StringBuilder tableHead = new StringBuilder("<thead  class='stickyHead'> <tr   height='25' bgcolor='#44FFFF'>");
        for (int i = 0; i < tableHeadItems.size(); i++) {
            tableHead.append(tdStart).append("<b>").append(tableHeadItems.get(i)).append("</b>").append(tdEnd);
        }
        tabale.append(tableHead).append("</thead>");
        //...........append table tr and td..............
        String item;
        JSONObject trJsonObject;
        try {
            for (int trIndex = 0; trIndex < jsonDataArray.length(); trIndex++) {
                tabale.append(getTrStart(trIndex));
                trJsonObject = jsonDataArray.getJSONObject(trIndex);
                for (int tdIndex = 0; tdIndex < tableHeadItems.size(); tdIndex++) {
                    item = trJsonObject.getString(tableHeadItems.get(tdIndex));
//                    Log.i("item", "trIndex=>" + trIndex + " " + "tdIndex=>" + tdIndex + " trJsonObject=>" + trJsonObject);
                    tabale.append(tdStart).append("<b>").append(item).append("</b>").append(tdEnd);
                }
                tabale.append(newTrEnd);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        tabale.append("</table</body></HTML>");
        //......return
        return tabale.toString();
    }

    private String getTrStart(int trNum) {
        if ((trNum % 2) == 0) {
            // even
            return "<tr height='25' bgcolor='#EDEEEE'>";

        } else {
            return "<tr height='25' bgcolor='#E2E4E5'>";
        }
    }

    public void setViewPadding(int left, int top, int right, int bottom) {
        webView.setPadding(left, top, right, bottom);

    }

    public void setViewMargin(int left, int top, int right, int bottom) {
        ViewGroup.MarginLayoutParams p = (ViewGroup.MarginLayoutParams) webView.getLayoutParams();
        p.leftMargin = left;
        p.topMargin = top;
        p.rightMargin = right;
        p.bottomMargin = bottom;
        webView.setLayoutParams(p);

    }


}

use lick this:

        //initialize table head items
        ArrayList<String> tableHeadItems = new ArrayList<>();
        tableHeadItems.add("Amount");// this is a td
        tableHeadItems.add("Time");// this is a td
        tableHeadItems.add("Status");// this is a td

        //initialize  tr and td values
        JSONObject itemJsonObject ;// this is td list in one tr
        dataItemArrayList=new JSONArray();// each tr items include td list
        try {// make sample data
            for(int i=0;i<100;i++){
                itemJsonObject = new JSONObject();
                itemJsonObject.put("Amount", i);
                itemJsonObject.put("Time", "9/30/2023");
                itemJsonObject.put("Status", "Success");
                dataItemArrayList.put(itemJsonObject);
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }
         new SaycoderTableMaker(getActivity(),  linearLayoutRoot, tableHeadItems, dataItemArrayList);// new table view - linearLayoutRoot is a empty linerLayout on your activity

The output is like this: The output is like this