[英]Inflate custom android widget
I know there are dozens similar post, but it looks to me everything is correct here: 我知道有几十个类似的帖子,但它在我看来一切都是正确的:
The custom 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);
}
}
The custom widget layout xml: 自定义窗口小部件布局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>
ANd here inside an activity function i get a casting error, 在一个活动函数里面我得到一个转换错误,
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"));
Here, the root View is a LinearLayout but you try to cast it your custom class: 这里,根视图是一个LinearLayout,但您尝试将其转换为自定义类:
DoubleTextItem item = (DoubleTextItem) inflater.inflate(R.layout.widget_double_text_item, layout);
The standard advice is: 标准建议是:
All DoubleTextItems are LinearLayouts, but not all LinearLayouts are DoubleTextItems.
所有DoubleTextItem都是LinearLayouts,但并非所有LinearLayout都是DoubleTextItems。
Meaning you cannot downcast objects from a LinearLayout to a DoubleTextItem, there are too many assumptions and Java won't let you do it. 意味着你不能将对象从LinearLayout向下转换为DoubleTextItem,有太多的假设,Java不会让你这么做。
If you want a DoubleTextItem in your layout you need to use: 如果您想在布局中使用DoubleTextItem,则需要使用:
<your.package.name.DoubleTextItem
... />
(Also, calling inflate inside onFinishInflate()
seems a little silly especially since you don't save the inflated item... If you want to inflate a different layout, don't inflate the first one.) (另外,在
onFinishInflate()
里面调用onFinishInflate()
似乎有点傻,特别是因为你没有保存膨胀的项目......如果你想膨胀不同的布局,不要给第一个膨胀。)
Overall it looks like you are trying to recreate the now deprecated TwoLineListItem , perhaps you can learn some pointers from it's source code (or just use the TwoLineListItem.) 总的来说,您似乎正在尝试重新创建现已弃用的TwoLineListItem ,也许您可以从它的源代码中学习一些指针(或者只是使用TwoLineListItem。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.