1
我有一個Android開關,當它打開時,在它下面展開一個LinearLayout。爲此,我使用動畫。當我啓動屏幕時,按鈕關閉,但顯示LinearLayout。當我現在打開開關,然後再次退出時,它確實隱藏了LinearLayout,但正如我所說的,無論何時開始屏幕,默認顯示LinearLayout。有人知道在屏幕啓動時如何默認隱藏LinearLayout嗎?如何在onCreate中隱藏Android LinearLayout?
我現在的代碼如下:
public class MyClass extends Activity implements OnCheckedChangeListener {
Switch mySwitch;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.my_layout);
mySwitch = (Switch) findViewById(R.id.my_switch);
mySwitch.setOnCheckedChangeListener(this);
}
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked){
LinearLayout view = (LinearLayout) findViewById(R.id.view_to_expand);
Animation anim = expand(view, true);
view.startAnimation(anim);
}
else {
LinearLayout view = (LinearLayout) findViewById(R.id.view_to_expand);
Animation anim = expand(view, false);
view.startAnimation(anim);
}
}
public static Animation expand(final View v, final boolean expand) {
try {
Method m = v.getClass().getDeclaredMethod("onMeasure", int.class, int.class);
m.setAccessible(true);
m.invoke(v, MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED), MeasureSpec.makeMeasureSpec(((View) v.getParent()).getMeasuredWidth(), MeasureSpec.AT_MOST));
} catch (Exception e) {
e.printStackTrace();
}
final int initialHeight = v.getMeasuredHeight();
if (expand) {
v.getLayoutParams().height = 0;
} else {
v.getLayoutParams().height = initialHeight;
}
v.setVisibility(View.VISIBLE);
Animation a = new Animation() {
@Override
protected void applyTransformation(float interpolatedTime,
Transformation t) {
int newHeight = 0;
if (expand) {
newHeight = (int) (initialHeight * interpolatedTime);
} else {
newHeight = (int) (initialHeight * (1 - interpolatedTime));
}
v.getLayoutParams().height = newHeight;
v.requestLayout();
if (interpolatedTime == 1 && !expand)
v.setVisibility(View.GONE);
}
@Override
public boolean willChangeBounds() {
return true;
}
};
a.setDuration(250);
return a;
}
}
請出示佈局XML。 LL最初的可見性狀態是什麼? – Simon
爲什麼不在XML中指定'layout_height'爲0,並且'visibility'爲'gone'? –