Thyago S
Thyago S

Reputation: 5

How to show TextView value in ImageView?

I would like to allow my users to type a word into a TextView and then display a corresponding picture in an ImageView. For example, the user might type "Moon", and then I would display moon.png.

How could I achieve this?

Upvotes: 0

Views: 179

Answers (2)

AppyFizz
AppyFizz

Reputation: 14

// Find TextView and ImageView, if required
TextView myTextView = (TextView) findViewById(R.id.tv);
ImageView myImageView = (ImageView) findViewById(R.id.iv);

// Get text from TextView
String myText = textView.getText().toString();

// Get ID of drawable with name entered by user
Context context = myImageView.getContext();
int id = context.getResources().getIdentifier(myText, "drawable", context.getPackageName());

// Set that drawable as the image to be displayed in the ImageView
myImageView.setImageResource(id);

Upvotes: 0

Ben P.
Ben P.

Reputation: 54204

The Resources class has a method getIdentifier() that you can use here.

int getIdentifier(String name, String defType, String defPackage)

Return a resource identifier for the given resource name. A fully qualified resource name is of the form "package:type/entry". The first two components (package and type) are optional if defType and defPackage, respectively, are specified here.

Note: use of this function is discouraged. It is much more efficient to retrieve resources by identifier than by name.

That means you could write:

String userEntered = myEditText.getText().toString();
int id = getResources().getIdentifier(userEntered, "drawable", getPackageName());
myImageView.setImageResource(id);

Upvotes: 1

Related Questions