在Android中将参数设置为布局时崩溃
预期结果
单击切换按钮将显示菜单并向右滑动内容视图。 动画完成后,内容视图的布局参数将更新到最终位置。
问题
更新内容视图的最终位置时,语句mViewContent.setLayoutParams(params);
导致崩溃。 错误消息是java.lang.ClassCastException: android.widget.LinearLayout$LayoutParams
源代码
Main.java > public class MainActivity extends Activity {}
public void onToggleButtonMenuClicked(View view) { // Is the toggle on? boolean toggleTurnedOn = ((ToggleButton) view).isChecked(); if (toggleTurnedOn) { // If the toggle is turned on // Show menu LinearLayout mViewMenu = (LinearLayout) findViewById(R.id.linear_layout_menu); Animation animMenuOn = AnimationUtils.loadAnimation(MainActivity.this, R.anim.anim_menu_on); mViewMenu.startAnimation(animMenuOn); LinearLayout mViewContent = (LinearLayout) findViewById(R.id.linear_layout_content); Animation animContentOff = AnimationUtils.loadAnimation(MainActivity.this, R.anim.anim_content_off); mViewContent.startAnimation(animContentOff); LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(480, 800); params.leftMargin = 384; // Shift 384 pixels from left screen border params.rightMargin = -96; // Exceed 96 pixels from right screen border mViewContent.setLayoutParams(params); // This statement causes crash! } else { // Hide menu... } // End of toggle events handling } // End of onToggleButtonMenuClicked()
activity_main.xml
mViewContent
params应该与resp一起添加到Parent视图中,假设你有父视图为LinearLayout
那么必须使用LinearLayout.LayoutParams
。
解释 : –
以LinearLayout.LayoutParams
和RelativeLayout.LayoutParams
为例,它们是不同的独立类。 他们存储有关儿童观点的不同附加信息…说..
-
LinearLayout.LayoutParams
可以将权重值与每个视图相关联,而RelativeLayout.LayoutParams
则不能。 -
RelativeLayout.LayoutParams
可以below
每个视图的above
,below
使用alightWithParent
,而LinearLayout.LayoutParams
则不能。
虽然代码不会给出编译时错误,因为所有LayoutParams
都有相同的父类,即ViewGroup.LayoutParams
。 因此,总是必须为父布局分配Layout
参数。
确保导入了正确的布局参数
import android.widget.LinearLayout.LayoutParams;