I'm trying to "link" 2 buttons together, without hardcoding references. Basically, if i press Button_1, i want my app to know, that i am referencing link_1 to which i then could apply some changes (like switching color). I'm using 2 different Views containing these buttons. I can't put them in the same view, because the link-view is laid over an image and thus has to resize, while the buttons-view don't. I don't want to hardcode this, because my dataset will expand to about 330 buttons and links total
Example xml-file:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_height="wrap_content"
android:layout_width="wrap_content">
<Button
android:id="@+id/button_1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:onClick="getConnection"
android:text="Button 1" />
<Button
android:id="@+id/button_2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:onClick="getConnection"
android:text="Button 2" />
</LinearLayout>
<LinearLayout
android:id="@+id/link_layout"
android:layout_height="wrap_content"
android:layout_width="wrap_content">
<Button
android:id="@+id/link_1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="" />
<Button
android:id="@+id/link_2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="" />
</LinearLayout>
If i remember correctly, i cant use IDs, because they are generated dynamically. Conveying information by other means like the contentDescription of the Button would be hardcoding AND bad convention.
I had the idea, that i could get the desired link-button by iterating over the corresponding viewgroups. First the parent of the button to retrieve the information, on which position the button is in the viewgroup and then use this to retrieve the link from the second viewgroup.
My rough idea for the code:
public View getConnection(View view) {
int buttonId = view.getId();
LinearLayout buttonLayout =(LinearLayout) view.getParent();
LinearLayout linkLayout =(LinearLayout) findViewById(R.id.link_layout);
for (int i = 0; i < buttonLayout .getChildCount(); i++) {
if (buttonLayout .getChildAt(i).getId() == buttonId) {
return linkLayout .getChildAt(i);
}
}
return null;
}
For this i would have to make sure, that they are positioned correctly in the viewgroups. But i'm not sure if this would even work since i don't know, if the parent.getChildAt() call would result in the same child every time if i expand the dataset.
Are there better methods for this?