【发布时间】:2016-11-22 11:06:36
【问题描述】:
我尝试通过扩展 android.widget.FrameLayout 来制作自定义 MySquareFrame 类,并通过传递自定义宽度和高度来覆盖 onMeasure 方法。
public class MySquareFrame extends FrameLayout {
public MySquareFrame(Context context) {
super(context);
}
public MySquareFrame(Context context, AttributeSet attrs) {
super(context, attrs);
}
public MySquareFrame(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public MySquareFrame(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int width = MeasureSpec.getSize(widthMeasureSpec);
int height = MeasureSpec.getSize(heightMeasureSpec);
int size = width > height ? height : width;
setMeasuredDimension(size, size);
}
}
并像这样在xml中使用它
<com.example.akash.view.MySquareFrame
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/background3">
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="@drawable/fuel_meter"
android:rotation="120"
/>
<com.triggertrap.seekarc.SeekArc
android:id="@+id/seekArc"
android:layout_width="match_parent"
android:layout_height="match_parent"
seekarc:max="120"
android:padding="70dp"
seekarc:rotation="180"
seekarc:startAngle="30"
seekarc:sweepAngle="300"
seekarc:touchInside="false"
seekarc:clockwise="false"
seekarc:thumb="@drawable/nob" />
</com.example.akash.view.MySquareFrame>
所以我希望 MySquareFrame 类在 xml 中查看 Square。请帮忙..
--------已更新--------------
DisplayMetrics displaymetrics = new DisplayMetrics();
((Activity) getContext()).getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
int height = displaymetrics.heightPixels;
int width = displaymetrics.widthPixels;
int size = width > height ? height : width;
setMeasuredDimension(size, size);
这有助于我根据屏幕尺寸获得方形框架。
【问题讨论】:
-
使用显示度量来获取显示的宽度,并在代码中设置高度与宽度相同,使其显示为正方形
-
谢谢。它奏效了。
-
更新你的代码“声明
updated”这将对其他人有所帮助
标签: java android android-layout android-view android-framelayout