繁体   English   中英

膨胀自定义Android小部件

[英]Inflate custom android widget

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

自定义小部件:

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"));

这里,根视图是一个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()里面调用onFinishInflate()似乎有点傻,特别是因为你没有保存膨胀的项目......如果你想膨胀不同的布局,不要给第一个膨胀。)


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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM