patternjavaMinor
Android Compound View Usage
Viewed 0 times
compoundusageviewandroid
Problem
I have 2 buttons for Terms and Conditions in my project, that I need to implement in multiple activities. I created the following class:
And the terms.xml file:
Is this a good way of reusing a group of views?
My colleagues say that it's not ok to use an XML which can be modified easily because I should modify in the code also (for example changing the order of the views) and if I am not careful the app might crash and it might take some time to figure out from where the problem comes from.
So, what's the best way of reusing this group of Terms and Conditions buttons?
public class TermsAndConditionsView extends LinearLayout implements View.OnClickListener {
private Context context;
public TermsAndConditionsView(Context context) {
super(context);
this.context = context;
}
public TermsAndConditionsView(Context context, AttributeSet attrs) {
super(context, attrs);
this.context = context;
}
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
super.onLayout(changed, left, top, right, bottom);
setUpLayout();
}
private void setUpLayout() {
LinearLayout container = (LinearLayout) this.getChildAt(1);
Button terms1 = (Button) container.findViewById(R.id.terms1);
Button terms2 = (Button) container.findViewById(R.id.terms2);
terms1.setOnClickListener(this);
terms2.setOnClickListener(this);
}
@Override
public void onClick(View v) {
if (v.getId() == R.id.terms1) {
String url = "myUrl1";
ActivityUtil.openBrowser((Activity) context, url);
} else if (v.getId() == R.id.terms2) {
String url = "myUrl2";
ActivityUtil.openBrowser((Activity) context, url);
}
}
}And the terms.xml file:
Is this a good way of reusing a group of views?
My colleagues say that it's not ok to use an XML which can be modified easily because I should modify in the code also (for example changing the order of the views) and if I am not careful the app might crash and it might take some time to figure out from where the problem comes from.
So, what's the best way of reusing this group of Terms and Conditions buttons?
Solution
Usually I use this approach when I want to create custom views but I don't implement actions inside the view, instead I am using a callback like the click listener :).
Also another minor thing is that there is no need to do
Also another minor thing is that there is no need to do
getChildAt() so you can find a specific view from a child view if you don't happen to have id's with the same names. Instead you can call findViewById directly on this(the root view).Context
StackExchange Code Review Q#80264, answer score: 3
Revisions (0)
No revisions yet.