Adding children views to a FrameLayout programmatically, then change their positions

jul picture jul · Jul 18, 2011 · Viewed 15.1k times · Source

I'm doing an Augmented Reality app and I need to show some objects on the camera view. I'm creating a FrameLayout to which I add my camera view and then I add my AR objects (now I'm trying with TextView). In the code below the TextView I add to my FrameLayout is not shown...

Anybody can help? And once I get fs shown, how can I change its position programmatically?

UPDATE

I tried with an ImageView instead of the TextView, and it works... Why!?

public class ARActivity extends Activity{

    private CBCameraView cv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

            super.onCreate(savedInstanceState);

            cv = new CBCameraView(this);

            FrameLayout rl = new FrameLayout(this);

            rl.addView(cv, GlobalVars.screenWidth, GlobalVars.screenHeight); 

            setContentView(rl);

            // this works...
            /*ImageView fs = new ImageView(this);
            fs.setImageResource(R.drawable.icon);
            rl.addView(fs);*/

            TextView fs = new TextView(this);
            fs.setText("Bar seco");
            fs.setTextColor(android.R.color.white);
            fs.setTextSize(1,14);
            fs.setLayoutParams(new ViewGroup.LayoutParams(
                    LayoutParams.WRAP_CONTENT,
                    LayoutParams.WRAP_CONTENT));
            rl.addView(fs);

    }    
}

Answer

algrid picture algrid · Aug 27, 2017

The problem may be in the way you're setting the text color. setTextColor() takes a color value argument, not a resource id. You should call

fs.setTextColor(ContextCompat.getColor(context, android.R.color.white));

If you want programmatically change your subview position you can adjust margins via layout params or use setX/setY methods. Take a look here How can I dynamically set the position of view in Android?