膨胀自定义Android小部件

时间:2013-02-10 19:17:15

标签: java android custom-component

我知道有几十个类似的帖子,但它在我看来一切都是正确的:

自定义小部件:

public class DoubleTextItem extends LinearLayout {

private TextView txtMain;
private TextView txtDescription;

public DoubleTextItem(Context context) {
    super(context);
}
public DoubleTextItem(Context context, AttributeSet attrs) {
    super(context, attrs);
}

@Override
protected void onFinishInflate() {
    super.onFinishInflate();
    ((Activity)getContext()).getLayoutInflater().inflate(R.layout.widget_double_text_item, this);
    setupViewItems();
}

private void setupViewItems() {
    txtMain = (TextView) findViewById(R.id.txtMain);
    txtDescription = (TextView) findViewById(R.id.txtDecription);
}
public void setDescription(String text) {
    txtDescription.setText(text);
}
}

自定义窗口小部件布局xml:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >

    <TextView
    android:id="@+id/txtMain"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" />

    <TextView
    android:id="@+id/txtDecription"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" />

</LinearLayout>

这里有一个活动函数,我得到一个转换错误,

LayoutInflater inflater = LayoutInflater.from(this);
DoubleTextItem item = (DoubleTextItem) inflater.inflate(R.layout.widget_double_text_item, layout);              
item.setText(som-txt);
item.setDescription("#"+athlete.getString("position"));

1 个答案:

答案 0 :(得分:2)

此处,根视图是一个LinearLayout,但您尝试将其转换为自定义类:

DoubleTextItem item = (DoubleTextItem) inflater.inflate(R.layout.widget_double_text_item, layout);              

标准建议是:

  

所有DoubleTextItem都是LinearLayouts,但并非所有LinearLayout都是DoubleTextItems。

意味着你不能将对象从LinearLayout向下转换为DoubleTextItem,有太多的假设,Java也不允许你这样做。

如果您想在布局中使用DoubleTextItem,则需要使用:

<your.package.name.DoubleTextItem 
    ... />

(另外,在onFinishInflate()内调用inflate似乎有点傻,特别是因为你没有保存膨胀的项目...如果你想要膨胀不同的布局,不要给第一个布局充气。)< / p>


总的来说,您似乎正在尝试重新创建现已弃用的TwoLineListItem,也许您可​​以从它的source code学习一些指针(或者只使用TwoLineListItem。)