我一直在搜索並嘗試解決自定義視圖和相對佈局中的問題。 我發現了多種解決方案,但只有很少的解決方案是有用的,但他們沒有完全滿足我的要求。 如何在自定義視圖中設置android:layout_centerInParent =「true」屬性
通過這些解決方案,我可以管理我的自定義視圖的高度和寬度,但我只想將我的自定義視圖對齊到父親RelativeLayout的中心, 代碼,我正在嘗試投擲並且運行在下面。 ;) Java代碼
public class MyActiveView extends View {
public Movie mMovie;
public long movieStart;
private int gifId;
public MyActiveView(Context context, AttributeSet attrs) {
super(context, attrs);
initializeView();
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int parentWidth = MeasureSpec.getSize(widthMeasureSpec);
int parentHeight = MeasureSpec.getSize(heightMeasureSpec);
this.setMeasuredDimension(parentWidth/2, parentHeight);
}
private void initializeView() {
InputStream is = getContext().getResources().openRawResource(R.raw.pj_logo1);
mMovie = Movie.decodeStream(is);
}
@Override
protected void onDraw(Canvas canvas) {
canvas.drawColor(Color.TRANSPARENT);
super.onDraw(canvas);
long now = android.os.SystemClock.uptimeMillis();
if (movieStart == 0) {
movieStart = now;
}
if (mMovie != null) {
int relTime = (int) ((now - movieStart) % mMovie.duration());
mMovie.setTime(relTime);
mMovie.draw(canvas, getWidth() - mMovie.width(), getHeight() - mMovie.height());
this.invalidate();
}
}
public int getActiveResource() {
return this.gifId;
}
public void setActiveResource(int resId) {
this.gifId = resId;
initializeView();
}
}
XML代碼
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="@+id/backsourceImagesplash"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="fitXY"
android:src="@drawable/bg_blur" />
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="@color/colorTransparentWhite" />
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="256dp"
android:layout_centerVertical="true"
android:gravity="centre">
<pj.com.pjlib.activity_base.support_class.MyActiveView
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
我想設置我的自定義活動視圖佈局在其父相對佈局的中心,但它stuked 。任何幫助將不勝感激。
檢查兩個圖像的比對,我試圖爲屬性的android:layout_centerInParent =「真」,根據相對佈局支持「恭喜形象」應該是中心,但它沒有發生。
所以我想,我錯過了我的自定義視圖類中的東西,但那是什麼,我不知道。
您能否更詳細地描述您的問題,並提供實際結果的屏幕截圖。 –
你能展示什麼是實際結果?或者至少描述一下。編輯原始問題,以便其他人可以更好地瞭解問題。 –
圖片和額外的支持線添加請檢查@Roberto –