[英]Set gravity of a View Programmatically
Im working on a View
over Android Source Code. 我在Android源代码上
View
。 I was wondering how can we setup multiple gravities, to a custom View
我想知道我们如何设置多个重力,到自定义
View
This is the XML 这是XML
<com.android.systemui.statusbar.policy.Clock
android:id="@+id/clock"
android:textAppearance="@style/TextAppearance.StatusBar.Clock"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:singleLine="true"
android:paddingLeft="6dip"
android:gravity="center_vertical|left"
/>
As you see, default gravity is center_vertical|left, so my Java code should be something like this 如你所见,默认引力是center_vertical | left,所以我的Java代码应该是这样的
View clock = mStatusBarView.findViewById(R.id.clock);
if (clock != null) {
SOMEHOW SET GRAVITY -> mCenterClock ? Gravity.CENTER : (Gravity.CENTER_VERTICAL | Gravity.LEFT);
}
setGravity method don't work on View
. setGravity方法对
View
不起作用。 So is there an alternative of setting gravity without losing the width and height by default?. 那么是否可以选择设置重力而不会丢失宽度和高度?
Thanks in advance. 提前致谢。
Since com.android.systemui.statusbar.policy.Clock extends TextView just cast it to a TextView and set the gravity. 由于com.android.systemui.statusbar.policy.Clock扩展TextView,只需将其转换为TextView并设置重力。
TextView clock = (TextView) mStatusBarView.findViewById(R.id.clock);
clock.setGravity(mCenterClock ? Gravity.CENTER : (Gravity.CENTER_VERTICAL | Gravity.LEFT));
Ref: Source code 参考: 源代码
Have you tried? 你有没有尝试过?
clock.setGravity(Gravity.CENTER | Gravity.CENTER_VERTICAL);
Edit: 编辑:
Since you cannot use setGravity
for a plain View
, do something like this, 既然您不能将
setGravity
用于普通View
,请执行以下操作,
You can use a RelativeLayout
and set a rule like this... 你可以使用
RelativeLayout
并设置这样的规则......
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
params.addRule(RelativeLayout.CENTER_HORIZONTAL|RelativeLayout.CENTER_IN_PARENT, clock.getId());
com.android.systemui.statusbar.policy.Clock clock = (com.android.systemui.statusbar.policy.Clock)mStatusBarView.findViewById(R.id.clock);
clock.setGravity(Gravity.CENTER_VERTICAL);
try the above code and remove View clock = mStatusBarView.findViewById(R.id.clock); 尝试上面的代码并删除View clock = mStatusBarView.findViewById(R.id.clock);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.