2015-11-26 89 views
2

我一直在搜索并尝试解决自定义视图和相对布局中的问题。 我发现了多种解决方案,但只有很少的解决方案是有用的,但他们没有完全满足我的要求。 如何在自定义视图中设置android:layout_centerInParent =“true”属性

partial solution 1

partial solution 2

通过这些解决方案,我可以管理我的自定义视图的高度和宽度,但我只想将我的自定义视图对齐到父亲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 。任何帮助将不胜感激。

i want result like this. but result of my code is

检查两个图像的比对,我试图为属性的android:layout_centerInParent =“真”,根据相对布局支持“恭喜形象”应该是中心,但它没有发生。

所以我想,我错过了我的自定义视图类中的东西,但那是什么,我不知道。

+0

您能否更详细地描述您的问题,并提供实际结果的屏幕截图。 –

+0

你能展示什么是实际结果?或者至少描述一下。编辑原始问题,以便其他人可以更好地了解问题。 –

+0

图片和额外的支持线添加请检查@Roberto –

回答

0

在相对布局中将android:gravity =“center”更改为android:gravity =“center”。我认为这对你有帮助。

+0

靶心!但是,我已经尝试过......但没有结果.... –

相关问题