0

I have searched the internet and havent found out exactly how to do this. I mostly have not looked correctly so dont start the repost and other comments. Just direct me to a revellant post or answer my question. Thankyou.

How do you dynamically add values to an xml view and add it to an activity. This should be done multiple times with different values which I get from an API.

What I currently am doing is (This is on Async Thread in onPostExecute):

RelativeLayout rl = new RelativeLayout(mContext);
            rl.setPadding(0, 0, 0, 10);
            ImageView img = new ImageView(mContext);
            img.setLayoutParams(new Toolbar.LayoutParams(Toolbar.LayoutParams.FILL_PARENT, Toolbar.LayoutParams.FILL_PARENT));
            img.setScaleType(ImageView.ScaleType.CENTER_CROP);
            //img.setMaxHeight(300);
            Picasso.with(mContext).load(imageURL[i]).into(img);
            rl.addView(img);
            TextView tv = new TextView(mContext);
            tv.setText(uri[i]);
            tv.setGravity(Gravity.CENTER | Gravity.BOTTOM);
            tv.setTextSize(20);
            tv.setBackgroundColor(Color.parseColor("#80000000"));
            tv.setLayoutParams(new Toolbar.LayoutParams(Toolbar.LayoutParams.FILL_PARENT, Toolbar.LayoutParams.WRAP_CONTENT));
            if(tv.getText()!= null) rl.addView(tv);
            rootView.addView(rl);

Is there a better way to do this so I have more control, like a pre defined layout and I just add the different values into it. Also how do I make each view clickable? (adding onClick)

Thanks

Alok Narasiman
  • 144
  • 1
  • 8

1 Answers1

0

First, you need to use RelativeLayout.LayoutParams rather than Toolbar.LayoutParams when setting the LayoutParams for something added to RelativeLayout.

Next, you need to ensure that the RelativeLayout you have created has the proper layout params set for the container type it is being added to (the rootView).

Use setOnClickListener to make each view clickable, like the following:

view.setOnClickListener(new OnClickListener()
{
    @Override
    public void onClick(View v)
    {

    }
});
jor
  • 41
  • 3