我有一个从FrameLayout扩展的自定义视图:
public class FanView extends FrameLayout {
private static final String TAG = FanView.class.getSimpleName();
private List<FanItem> fanItems = new ArrayList<>();
private float openRatio = 0f;
public FanView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
private void init() {
setStaticTransformationsEnabled(true);
}
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
Log.d(TAG, "onLayout(" + changed + ", " + left + ", " + top + ", " + right + ", " + bottom + ")");
super.onLayout(changed, left, top, right, bottom);
Log.d(TAG, "End onLayout");
}
@Override
protected boolean getChildStaticTransformation(View child, Transformation t) {
final float index = getChildCount() - indexOfChild(child) - 1;
final float height = child.getHeight();
Matrix matrix = t.getMatrix();
matrix.setTranslate((float) (-index * 1.1 * (height/2) * openRatio), (float) (index * height * openRatio * 1.2));
return true;
}
public void setOpenRatio(float r) {
this.openRatio = r;
final int childCount = getChildCount();
for (int i = 0; i < childCount; i++) {
View view = getChildAt(i);
view.invalidate();
}
invalidate();
}
public void setFanItems(List<FanItem> fanItems) {
this.fanItems = fanItems;
removeAllViewsInLayout();
for (int i = 0; i < fanItems.size(); i++) {
int fanItemIndex = fanItems.size() - i - 1;
FanItem fanItem = fanItems.get(fanItemIndex);
View fanView = inflate(getContext(),
fanItemIndex == 0 ? R.layout.fan_item_header : R.layout.fan_item, null);
TextView textView = (TextView) fanView.findViewById(R.id.fan_view_item_title);
textView.setText(fanItem.getTitle());
addViewInLayout(fanView, i,
new LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT));
}
invalidate();
}
}
在xml布局中,我使用具有宽度和高度wrap_content的此自定义视图。 当我将视图添加到该自定义视图时不显示此视图时, 因为自定义布局不会更改其大小。 如何说自定义视图更改其大小
答案 0 :(得分:0)
您当前的代码可能需要另一个构造函数
public FanView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
答案 1 :(得分:0)
请首先提供有效尺寸以使物品膨胀。给至少一个元素以获取布局膨胀后的尺寸。您可以使用布局参数更改项目的大小。
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
xmlns:android="schemas.android.com/apk/res/android"
android:background="@drawable/fan_item_background"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:textDirection="rtl">
<TextView
android:id="@+id/fan_view_item_title"
android:layout_height="200dp"
android:layout_width="200dp"
android:text="ersfsdf"
android:textAlignment="textStart"
android:textColor="#ffffff"/>
</FrameLayout>
要动态更改大小,请尝试如下操作。
// Gets linearlayout
FrameLayout layout = findViewById(R.id.framelaut);// or any layout
// Gets the layout params that will allow you to resize the layout
LayoutParams params = layout.getLayoutParams();
// Changes the height and width to the specified *pixels*
params.height = 100;
params.width = 100;
layout.setLayoutParams(params);