Search code examples
androidandroid-relativelayoutprogrammatically-created

How do I access a textview or progressbar in relative layout programatically when multiple?


I am creating multiple relative layouts in an activity, programmatically. Each is identical and has a textview as well as a ProgressBar spinner.

I want to programmatically change them when needed but not sure how to access the appropriate one. I believe I need to add a unique SetId() to each item (or maybe the relativelayout itself) but not sure the best way to do so.

I also am not sure if I use findViewById to access the views once created to make the changes (SetText, SetVisibility, etc).

Here is the code

RelativeLayout.LayoutParams tvpName = new RelativeLayout.LayoutParams(
            RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
    tvpName.addRule(RelativeLayout.ALIGN_PARENT_LEFT);

RelativeLayout.LayoutParams pbpSpinner = new RelativeLayout.LayoutParams(
            RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
    pbpSpinner.addRule(RelativeLayout.CENTER_IN_PARENT);
    pbpSpinner.addRule(RelativeLayout.ALIGN_PARENT_TOP);

 for (int i = 0; i < 5; i++) {
        RelativeLayout acctrl = new RelativeLayout(this);

        TextView tvName = new TextView(this);

        ProgressBar pbSpinner = new ProgressBar(this);
        pbSpinner.setVisibility(View.GONE);

        // Add items to Account Interal Layout
        acctrl.addView(tvName, tvpName);
        acctrl.addView(pbSpinner, pbpSpinner);
 }

Any recommendations / suggestions?


Solution

  • When you create a View programatically, it's a good practice to setId(). Additionally, you can go ahead and setTag() also. By setting a Tag, you can know what each RelativeLayout or any other view. This way you can get a hold of the view that you are looking for.

    If you are not going to access or modify the RelativeLayout then you need not set ID for it, but setting an id for it makes this easier, so that you can just send the ID of the RelativeLayout as a parameter to a method and it will perform all operations on the Views it holds, since you said all RelativeLayouts are identical.

    If you are using setId(), then you can use the findViewById() to get the view.
    If you are using setTag(), the you can refer this on how to use it to get the view: https://stackoverflow.com/a/5291891/4747587