我的目标是从布局中扩充我的自定义视图
自定义视图布局:
<net.rhyboo.com.game_test.Piece xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:scaleType="fitXY"
android:id="@+id/piece_view">
</net.rhyboo.com.game_test.Piece>
与此布局相关联的类:
package net.rhyboo.com.game_test;
import android.content.Context;
import android.util.AttributeSet;
import android.widget.ImageView;
public class Piece extends ImageView {
public Piece(Context context, AttributeSet atrs) {
super(context,atrs);
}
public Piece(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
}
但是当我尝试用代码充气时:
//get layout inflater
LayoutInflater li=(LayoutInflater)activity.getSystemService(Service.LAYOUT_INFLATER_SERVICE);
//parent view for my custom view
FrameLayout gf =(FrameLayout)fragment.getView().findViewById(R.id.game_field);
//inflation attempt
Piece p=(Piece) li.inflate(R.layout.piece_view,gf);
我收到了错误
java.lang.ClassCastException:android.widget.FrameLayout无法强制转换为net.rhyboo.com.game_test.Piece
为什么layout inflater生成FrameLayout而我的视图类型是Piece,它是ImageView的子类?
答案 0 :(得分:0)
而不是:
//get layout inflater
LayoutInflater li=(LayoutInflater)activity.getSystemService(Service.LAYOUT_INFLATER_SERVICE);
//parent view for my custom view
FrameLayout gf =(FrameLayout)fragment.getView().findViewById(R.id.game_field);
//inflation attempt
Piece p=(Piece) li.inflate(R.layout.piece_view,gf);
尝试
//get layout inflater
LayoutInflater li =(LayoutInflater)activity.getSystemService(Service.LAYOUT_INFLATER_SERVICE);
//parent view for my custom view
FrameLayout gf = (FrameLayout)fragment.getView().findViewById(R.id.item);
//inflation attempt
Piece p = li.inflate(R.layout.piece_view, null);
gf.addView(p);
编辑:要查看原始尺寸的图片,请将此参数添加到ImageView
:
android:scaleType="center"
答案 1 :(得分:0)
我认为你应该以这两种方式尝试:
查看视图= inflater.inflate(R.layout.your_custom_layout,mFrameLayout,true);
查看视图= inflater.inflate(R.layout.your_custom_layout,parent,false);
代码中可能的更正:
查看视图= li.inflate(R.layout.piece_view,gf);
或者 查看视图= inflater.inflate(R.layout.piece_view,gf);
最后返回视图;
根据错误,您似乎错误地将Frame Layout投射到您的自定义布局
//通胀尝试 Piece p =(Piece)li.inflate(R.layout.piece_view,gf);