I made a XML element that automatically creates a Button, then a ScrollView with a LinearLayout inside. The Button, when pressed, is supposed to change color and change the Visibility of the ScrollView. Right now, it only changes the color of the Button, but the Text inside the Scroll View stays visible.
This worked before when I created the Button and ScrollView through XML and created onClickListeners
through the onCreate()
method in the main activity.
my code:
public class AccordionWidget extends LinearLayout{
public AccordionWidget(Context c, AttributeSet attrs) {
super(c, attrs);
final Context context = c;
final Button btn = new Button(context);
final LinearLayout ll = new LinearLayout(context);
final ScrollView sv = new ScrollView(context);
TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.accordion);
LayoutParams btnparams = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
btn.setText(a.getString(R.styleable.accordion_text));
btn.setBackgroundColor(ContextCompat.getColor(context, R.color.button_not_pressed));
LayoutParams llparams = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
llparams.weight = 1f;
LayoutParams swparams = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
btn.setLayoutParams(btnparams);
ll.setOrientation(LinearLayout.VERTICAL);
ll.setLayoutParams(llparams);
sv.setVisibility(View.GONE);
sv.setLayoutParams(swparams);
this.addView(sv);
this.addView(btn);
sv.addView(ll);
btn.setOnClickListener(new OnClickListener() {
boolean btnstate = false;
@Override
public void onClick(View v) {
if (btnstate) {
btn.setBackgroundColor(ContextCompat.getColor(context, R.color.button_pressed));
sv.setVisibility(View.VISIBLE);
btnstate = false;
} else {
btn.setBackgroundColor(ContextCompat.getColor(context, R.color.button_not_pressed));
sv.setVisibility(View.GONE);
btnstate = true;
}
}
});
a.recycle();
}
}