【问题标题】:Type mismatch: cannot convert from ViewGroup.LayoutParams to LinearLayout.LayoutParams类型不匹配:无法从 ViewGroup.LayoutParams 转换为 LinearLayout.LayoutParams
【发布时间】:2012-11-24 12:11:33
【问题描述】:

我正在尝试按照以下示例编写每周日历:
How can I create a weekly calendar view for an Android Honeycomb application?
我已经在 XML 文件中添加了一个时间标记行,该行假设在当前时间。为此,我使用:

<LinearLayout
    android:id="@+id/currentTimeMarkerLinearLayout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginLeft="0dp"
    android:layout_marginTop="120dp"
    android:baselineAligned="false"
    android:orientation="horizontal"
    android:padding="0dp" >

  <View
      android:layout_width="0dp"
      android:layout_height="3dp"
      android:layout_weight="1" />

  <View
      android:id="@+id/currentTimeLineView"
      android:layout_width="0dp"
      android:layout_height="1dp"
      android:layout_weight="14"
      android:background="@color/dark_blue" />
</LinearLayout>

这个LinearLayout 在RelativeLayout 内,它们都在ScrollView 内。
我正在尝试通过编程“移动”这一行,方法是用这些行修改layout_margintTop:

int dipValue = 720; // we want to convert this dip value to pix
Resources r = getResources();
float pix = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
    dipValue, r.getDisplayMetrics());

LinearLayout lay =(LinearLayout) findViewById(R.id.currentTimeMarkerLinearLayout);
LinearLayout.LayoutParams lp = lay.getLayoutParams();
lp.setMargins(0, (int) pix, 0, 0);
lay.setLayoutParams(lp);  

但我在lp = lay.getLayoutParams() 中收到一个错误,告诉我它无法从ViewGroup.LayoutParams 转换为LinearLayout.LayoutParams。

我做错了什么?

【问题讨论】:

    标签: java android xml android-layout


    【解决方案1】:

    但是我在 lp = lay.getLayoutParams() 中收到一个错误,告诉我它 无法从 ViewGroup.LayoutParams 转换为 LinearLayout.LayoutParams.

    如果LinearLayout 被RelativeLayout 包裹,则其LayoutpParams 的类型为RelativeLayout.LayoutParams(子级从父级获取LayoutParams)。您也很可能为您在代码中使用的 LayoutParams 导入了错误的类。

    LinearLayout lay = (LinearLayout) findViewById(R.id.currentTimeMarkerLinearLayout);
    RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams)lay.getLayoutParams();
    

    【讨论】:

    • 非常感谢 Luksprog,因为这个问题我浪费了很多时间。现在工作得很好!
    猜你喜欢
    • 1970-01-01
    • 2019-01-16
    • 2016-03-13
    • 2014-02-12
    • 2014-04-16
    • 2017-12-31
    • 1970-01-01
    • 2015-11-18
    • 2014-04-07
    相关资源
    最近更新 更多