gpt4 book ai didi

java - 查看布局中的位置

转载 作者:行者123 更新时间:2023-12-01 05:15:39 27 4
gpt4 key购买 nike

加载类( View ):

public class Loading extends View {

private long movieStart;
private Movie movie;

public Loading(Context context, InputStream inputStream) {
super(context);
movie = Movie.decodeStream(inputStream);
}

@Override
protected void onDraw(Canvas canvas) {
canvas.drawColor(Color.WHITE);
super.onDraw(canvas);
final long now = SystemClock.uptimeMillis();
if(movieStart == 0)
movieStart = now;
final int relTime = (int)((now - movieStart) % movie.duration());
movie.setTime(relTime);
movie.draw(canvas, 100, 100);
this.invalidate();
}

}

Activity onCreate方法:

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
InputStream inputStream = null;
try {
inputStream = getAssets().open("loading.gif");
} catch(IOException e) {
e.printStackTrace();
}
Loading loading = new Loading(this, inputStream);
setContentView(loading);
}

我想将 View 设置在设备布局的中心。就像在 XML 布局中一样,我们可以设置 android:layout_centerHorizo​​ntal="true"。我该怎么做?

最佳答案

您需要为View设置LayoutParams。我要做的是将您的自定义 View 放入容器中,例如 FrameLayout。然后,创建 View 并设置 View 的 FrameLayout.LayoutParams,并将重力设置为 CENTER_HORIZONTAL。它看起来像这样

FrameLayout frame = new FrameLayout(context);

FrameLayout.LayoutParams flParams = new FrameLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT,
Gravity.CENTER_HORIZONTAL
);

Loading loading = new Loading(this, inputStream);
loading.setLayoutParams(flParams);
frame.addView(loading);
setContentView(frame);

您可能想要配置 FrameLayout 以使其按照您想要的方式显示。

这是我使用的 LayoutParams 构造函数的文档:http://developer.android.com/reference/android/widget/FrameLayout.LayoutParams.html#FrameLayout.LayoutParams%28int,%20int,%20int%29

请务必记住,扩展 ViewParent 的每个 View 都有自己的 LayoutParams 类,因此,例如,如果您想使用 LinearLayout 而不是 FrameLayout,则可以使用 LinearLayout.LayoutParams。不同类型的 Params 有不同的构造函数选项,因此您可以使用它并找到最适合您的。祝你好运。

关于java - 查看布局中的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11265747/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com