我有一个android应用程序,让我们的用户修改一些布局参数。我的一个功能让用户决定TextView是否与图片的顶部或底部对齐。Android:TextView.setLayoutParams有时工作,有时不工作
这是函数:
private void setAlign(String align) {
/* Get Preferences */
SharedPreferences prefs = getSharedPreferences("prefs", Context.MODE_WORLD_READABLE);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("align", align);
editor.commit();
Log.d("ALIGN", align);
paramAlign = align;
FrameLayout.LayoutParams floLP = new FrameLayout.LayoutParams(
FrameLayout.LayoutParams.WRAP_CONTENT,
FrameLayout.LayoutParams.WRAP_CONTENT,
(align == "TOP") ? Gravity.TOP : Gravity.BOTTOM);
txtGoal.setLayoutParams(floLP);
int res = paramAlign == "TOP" ? R.drawable.btn_toolbar_align_top_up : R.drawable.btn_toolbar_align_bottom_up ;
btnAlign.setImageResource(res);
}
现在,一旦活动开始时,此功能工作正常。但是,当我初始化活动时,在检索对齐首选项后,我在onGlobalLayout方法中调用setAlign()函数。
这是相关代码:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.personalize);
/* Get Preferences */
SharedPreferences prefs = getSharedPreferences("prefs", Context.MODE_WORLD_READABLE);
paramAlign = prefs.getString("align", "BOTTOM");
Log.d("ALIGN", paramAlign);
// Get screen dimensions and initialize preview
ViewTreeObserver vto = rootView.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
setAlign(paramAlign);
ViewTreeObserver obs = rootView.getViewTreeObserver();
obs.removeGlobalOnLayoutListener(this);
}
});
}
现在,如果你注意到的日志功能,它们都返回“TOP”当我开始活动。而setAlign()函数显然被调用。然而,TextView在底部对齐。这是TextView的在XML:
<TextView
android:id="@+id/txtGoal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dip"
android:textColor="@color/color_white"
android:textSize="8sp"
android:shadowColor="@color/color_black"
android:shadowDx="1.2"
android:shadowDy="1.2"
android:shadowRadius="1.2"
/>
任何想法,为什么setLayoutParams创建活动时,不发生?当布局完成绘制时,该函数被激发,所以它不应该成为问题。 XML没有指定开始的重力。
我在这里错过了什么?
我还要提到的是它没有任何更新的按钮图像。 – ReX357 2012-08-05 16:57:02