我正在开发一个基于安卓源代码的View
。我想知道如何才能将多个重力设置为自定义的View
这是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"
/>
如您所见,缺省重力是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方法在View
上不起作用。那么有没有一种默认设置重力而不丢失宽度和高度的替代方法呢?
提前谢谢。
发布于 2012-04-28 02:21:10
由于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));
参考:Source code
发布于 2012-04-28 02:05:09
你试过了吗?
clock.setGravity(Gravity.CENTER | Gravity.CENTER_VERTICAL);
编辑:
由于您不能对普通View
使用setGravity
,因此可以这样做:
您可以使用RelativeLayout
并像这样设置规则...
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
params.addRule(RelativeLayout.CENTER_HORIZONTAL|RelativeLayout.CENTER_IN_PARENT, clock.getId());
发布于 2012-04-28 02:02:54
com.android.systemui.statusbar.policy.Clock clock = (com.android.systemui.statusbar.policy.Clock)mStatusBarView.findViewById(R.id.clock);
clock.setGravity(Gravity.CENTER_VERTICAL);
尝试上面的代码并删除View clock = mStatusBarView.findViewById(R.id.clock);
https://stackoverflow.com/questions/10355603
复制相似问题