我正在尝试在纸板覆盖视图中对自定义视图进行充气,只有父视图正在膨胀,即相对布局。
以下是CardboardOverlayView的代码:
public class CardboardOverlayView extends LinearLayout {
private final CardboardOverlayEyeView leftView;
private final CardboardOverlayEyeView rightView;
public CardboardOverlayView(Context context, AttributeSet attrs) {
super(context, attrs);
setOrientation(HORIZONTAL);
LayoutParams params = new LayoutParams(
LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT, 1.0f);
params.setMargins(0, 0, 0, 0);
leftView = new CardboardOverlayEyeView(context, attrs);
leftView.setLayoutParams(params);
addView(leftView);
rightView = new CardboardOverlayEyeView(context, attrs);
rightView.setLayoutParams(params);
addView(rightView);
setDepthOffset(0.016f);
setVisibility(View.VISIBLE);
}
private void setDepthOffset(float offset) {
leftView.setOffset(offset);
rightView.setOffset(-offset);
}
private class CardboardOverlayEyeView extends ViewGroup {
private float offset;
private ListView listView;
private View view;
private String[] item = new String[]{"Item1", "Item2", "Item3", "Item4", "Item5"};
public CardboardOverlayEyeView(Context context, AttributeSet attrs) {
super(context, attrs);
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.my_layout, null, true);
this.listView = (ListView) view.findViewById(R.id.listView);
final ArrayAdapter<String> adapter = new ArrayAdapter<String>(context, android.R.layout.simple_list_item_1, item);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Toast.makeText(getContext(), "Item Clicked: " + adapter.getItemId(i), Toast.LENGTH_SHORT).show();
}
});
this.addView(view);
}
public void setOffset(float offset) {
this.offset = offset;
}
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
final int width = right - left;
final int height = bottom - top;
final float imageSize = 0.1f;
final float verticalImageOffset = -0.07f;
final float verticalTextPos = 0.52f;
float adjustedOffset = offset;
float imageMargin = (1.0f - imageSize) / 2.0f;
float leftMargin = (int) (width * (imageMargin + adjustedOffset));
float topMargin = (int) (height * (imageMargin + verticalImageOffset));
leftMargin = adjustedOffset * width;
topMargin = height * verticalTextPos;
view.layout((int) 100, (int) 100, (int) (width - 100), (height - 100));
}
}
}
这是我试图膨胀的自定义布局:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#1bd5b9">
<ListView
android:id="@+id/listView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
附上截图: