Android 如何定位自定义视图?
我创建了一个自定义视图,但在屏幕中央定位时遇到了困难Android 如何定位自定义视图?,android,android-layout,view,Android,Android Layout,View,我创建了一个自定义视图,但在屏幕中央定位时遇到了困难 public class CurvedText extends View { private static final String MY_TEXT = "Select A Mode"; private Path mArc; private Paint mPaintText; public CurvedText(Context context, AttributeSet attrs) { sup
public class CurvedText extends View {
private static final String MY_TEXT = "Select A Mode";
private Path mArc;
private Paint mPaintText;
public CurvedText(Context context, AttributeSet attrs) {
super(context, attrs);
mArc = new Path();
RectF oval = new RectF(0,0,200,200);
mArc.addArc(oval, -45, 200);
mPaintText = new Paint(Paint.ANTI_ALIAS_FLAG);
mPaintText.setStyle(Paint.Style.FILL_AND_STROKE);
mPaintText.setColor(Color.WHITE);
mPaintText.setTextSize(20f);
}
@Override
protected void onDraw(Canvas canvas) {
canvas.drawTextOnPath(MY_TEXT, mArc, 0, 10, mPaintText);
invalidate();
}
}
我知道我可以使用设置RectF坐标来解决问题,但我希望这个文本位于屏幕中心。那么如何动态地获得屏幕中心的坐标呢?或以任何其他方式将其定位在屏幕中心
添加声明:
<com.pkg.CurvedText
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center" >
</com.pkg.CurvedText>
这会让你知道屏幕的宽度和高度。屏幕的中心仅为宽度/2和高度/2。当然,要做到这一点,您需要对活动的引用
下面是我如何使用我向您展示的代码。在我的项目中,我有一个只包含公共静态方法的实用程序类。在该类中,我保留了一个私有的静态引用,指向保存这些维度的int数组。每当调用带有上述代码的公共静态函数时,我只需填充私有静态int数组。请注意,函数接受活动以获取值。在方法中,我检查传入的活动是否为null。如果为null,我只返回私有静态int数组的值。这样,我可以在应用程序启动时(从任何活动)调用此方法一次,并存储这些值。然后,如果以后我再次需要这些值,我只需调用相同的方法,但使用null参数,然后我就可以取回存储的值。希望这有意义 将设备屏幕大小除以2,这样做行吗?这样做是否完美?我的意思是像centerVertical和other一样精确?你能定义你视图的重心到中心,并定义它的宽度和高度以匹配父视图吗?@Akagami不起作用!请参阅更新的问题。请参阅已批准的答案。我真的以为我的话会让你自己去发现。我不是从任何活动中提出这种观点:(!您将其放置在何处?创建此视图并将其作为类放置在新包中!然后简单地将其放置在布局中!这是对MainActivity的引用我编辑了我的答案以添加我如何使用此代码。如果您有任何问题,请告诉我。因此,我应该将设备的DIM存储在UTIL中,并在每次用户加载该ui时提取?我会给出答案试试看。
private static int [] screenDimens;
/**
* Gets the width and height of the screen. If null is passed, this method returns the previously
* requested parameters.
*
* @param activity {@link android.app.Activity}
* @return int [0] = width, int[1] = height
*/
public static int [] getScreenDimensInPx(Activity activity) {
if(activity != null) {
Display display = activity.getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int width = size.x;
int height = size.y;
screenDimens = new int[]{width, height};
}
return screenDimens;
}