How to create a Textview and Imageview via code?

Asked

Viewed 1,153 times

1

I would like to know how it creates via code a TextView and a ImageView and destroy it via code.

1 answer

5


To create any view in memory is simple, but most problems are when nothing appears on the screen, so make sure that it is visible as in the case of Imageview if you do not have an image will not appear at all, and if you don’t add to any layout it’s totally impossible to appear. So in the case of Textview:

TextView textView = new TextView(this);
textView.setText("Alguma coisa");

//Suponhamos que temos uma layout com um id layoutVertical
LinearLayout linear = (LinearLayout)findViewById(R.id.layoutVertical);
linear.addView(textView);

In the case of imageView it would be something like this minus the part where you have to add an image:

ImageView imagem = new ImageView(this);
imagem.setBackgroundResource(R.drawable.imagemqualquer);

In case of deleting what you would have to do would remove the views from the layout they were in, in the case of the previous example to remove the textView we would have to do:

linear.removeView(textView);

From the moment when the Textview object is no longer used or called garbage Collector clean and no longer occupies memory. But you can still hide the view without deleting it:

textView.setVisibility(View.GONE);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.