RelativeLayout使用标签替代ID:动态操作XML视图的技术问询
Hey there! Great question—let's walk through how to handle dynamic View manipulation in Java, whether you stick with tags or explore another approach using string-based ID lookup.
Using Tags to Identify Views
Your initial plan to use android:tag is totally valid and a common pattern in Android development for marking views you need to target dynamically. Here's how to implement it properly:
First, your XML (formatted for clarity):
<RelativeLayout android:layout_width="match_parent" android:layout_height="wrap_content"> <View <!-- To be colored dynamically in Java --> android:tag="color0" android:layout_width="40dp" android:layout_height="40dp" android:layout_alignParentStart="true" android:id="@+id/view1"/> <!-- Add your TextView and other views here --> </RelativeLayout>
Then in your Java code (Activity/Fragment):
// Option 1: If you already have the View's direct ID reference View colorView = findViewById(R.id.view1); // Option 2: If you need to find it by tag (useful for bulk operations) RelativeLayout parentLayout = findViewById(R.id.your_parent_layout_id); // Add an ID to your RelativeLayout first! View colorViewByTag = parentLayout.findViewWithTag("color0"); // Modify the color once you have the View reference if (colorView != null) { // Use a direct color value or a theme-aware resource color colorView.setBackgroundColor(Color.RED); // For API 23+: colorView.setBackgroundColor(getResources().getColor(R.color.your_custom_color, getTheme())); }
Note: If multiple views share the same tag, findViewWithTag() will only return the first matching View. Always ensure your tags are unique if you're targeting individual views.
Bonus: Using Strings to Look Up View IDs
You mentioned thinking you couldn't use strings directly for IDs—but Android actually has a method for that! The getResources().getIdentifier() method lets you retrieve a resource ID using its string name. Here's how it works:
// Get the View ID from its string name (matches the android:id="@+id/view1" in XML) int viewId = getResources().getIdentifier("view1", "id", getPackageName()); View colorView = findViewById(viewId); // Update the color just like before if (colorView != null) { colorView.setBackgroundColor(Color.BLUE); }
A quick heads-up: This method is slightly less performant than directly referencing R.id.view1 since it does a dynamic lookup. For frequent use cases, cache the ID or stick with tags. Also, double-check that the string matches the exact ID name in your XML (it's case-sensitive!).
Final Thoughts
Both approaches work well:
- Use tags if you need flexible, custom identifiers (you can even attach objects to tags with
setTag()for more complex data). - Use
getIdentifier()if you just need to map a string to an existing XML View ID.
内容的提问来源于stack exchange,提问作者Rafael Tavares

