【发布时间】:2016-07-09 01:56:12
【问题描述】:
我制作了一个 XML 元素,它自动创建一个 Button,然后是一个带有 LinearLayout 的 ScrollView。 Button 在按下时应该会改变颜色并改变 ScrollView 的可见性。现在,它只改变了 Button 的颜色,但 Scroll View 中的 Text 保持可见。
这在我通过 XML 创建 Button 和 ScrollView 并通过主活动中的 onCreate() 方法创建 onClickListeners 之前有效。
我的代码:
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();
}
}
【问题讨论】:
标签: java android scrollview