如何在 ImageView 中显示 TextView 的值?
How to show TextView value in ImageView?
我想让我的用户在 TextView
中输入一个词,然后在 ImageView
中显示相应的图片。例如,用户可能输入 "Moon",然后我会显示 moon.png
.
我怎样才能做到这一点?
Resources
class 有一个方法 getIdentifier()
可以在这里使用。
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.
这意味着你可以写:
String userEntered = myEditText.getText().toString();
int id = getResources().getIdentifier(userEntered, "drawable", getPackageName());
myImageView.setImageResource(id);
// 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);
我想让我的用户在 TextView
中输入一个词,然后在 ImageView
中显示相应的图片。例如,用户可能输入 "Moon",然后我会显示 moon.png
.
我怎样才能做到这一点?
Resources
class 有一个方法 getIdentifier()
可以在这里使用。
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.
这意味着你可以写:
String userEntered = myEditText.getText().toString();
int id = getResources().getIdentifier(userEntered, "drawable", getPackageName());
myImageView.setImageResource(id);
// 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);