My aim is to inflate my custom view from layout
custom view layout:
<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>
class associated with this layout:
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);
}
}
But when I try to inflate with the code:
//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);
I got the error
java.lang.ClassCastException: android.widget.FrameLayout cannot be cast to net.rhyboo.com.game_test.Piece
Why layout inflater generates FrameLayout while type of my view is Piece which is subclass of the ImageView?
Instead of:
//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);
try
//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);
EDIT: To see Image in original size add this parameters to ImageView
:
android:scaleType="center"
I think you should try it in these two ways:
View view = inflater.inflate(R.layout.your_custom_layout, mFrameLayout, true);
View view = inflater.inflate(R.layout.your_custom_layout, parent, false);
Possible correction in your code:
View view =li.inflate(R.layout.piece_view,gf);
Or View view =inflater.inflate(R.layout.piece_view,gf);
Finally return view;
According to the error it seems you are wrongly casting Frame Layout to your custom layout here
//inflation attempt Piece p=(Piece) li.inflate(R.layout.piece_view,gf);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.