我知道有很多类似的帖子,但是在我看来,这里的一切都是正确的:
自定义小部件:
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);
标准建议是:
所有DoubleTextItems都是LinearLayouts,但并非所有LinearLayouts都是DoubleTextItems。
这意味着您不能将对象从LinearLayout转换为DoubleTextItem,这有太多假设,而Java不允许您这样做。
如果要在布局中使用DoubleTextItem,则需要使用:
<your.package.name.DoubleTextItem
... />
(此外,在
onFinishInflate()
内调用inflate似乎有点愚蠢,特别是因为您不保存已膨胀的项目...如果要对其他布局进行膨胀,请不要对第一个布局进行膨胀。)总的来说,您似乎正在尝试重新创建现在已弃用的TwoLineListItem,也许您可以从source code中学习一些指针(或仅使用TwoLineListItem。)