[英]How to set align (right or left) programmatically TextView?
What did I do wrong when setting textview in the following position?在下面的 position 中设置 textview 时我做错了什么?
- Linear Layout - -线性布局-
(left)imageview -textview-------------------------------------------- (right)imageview -textview (左)imageview -textview-------------------------------------------- (右)imageview -textview
parent.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT));
parent.setOrientation(LinearLayout.HORIZONTAL);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,convertDpToPixel(23));
textView.setLayoutParams(params);
icFeature.setLayoutParams(params);
icFeature2.setLayoutParams(params);
textView2.setLayoutParams(params);
textView2.setGravity(Gravity.RIGHT);
parent.addView(textView);
parent.addView(icFeature);
parent.addView(icFeature2);
parent.addView(textView2);
linearLayout.addView(parent);
Give below a try.下面试一试。 It can be helpful,可能会有所帮助,
RelativeLayout.LayoutParams textViewLayoutParams = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
// add a rule to align to the left
textViewLayoutParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
//align right
textViewLayoutParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
// make sure the rule was applied
textView.setLayoutParams(textViewLayoutParams);
You are setting the TextView's own Gravity attribute which controls how its text renders within its own bounds.您正在设置 TextView 自己的 Gravity 属性,该属性控制其文本在其自身范围内的呈现方式。 You want to set the Gravity attribute on the LayoutParams instead:您想在 LayoutParams 上设置 Gravity 属性:
https://developer.android.com/reference/android/widget/LinearLayout.LayoutParams#gravity https://developer.android.com/reference/android/widget/LinearLayout.LayoutParams#gravity
parent.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT));
parent.setOrientation(LinearLayout.HORIZONTAL);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT, convertDpToPixel(23));
textView.setLayoutParams(params);
// Create new params for second view
LinearLayout.LayoutParams params2 = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT, convertDpToPixel(23));
params2.gravity = Gravity.RIGHT | Gravity.END; // Set gravity on layout params
textView2.setLayoutParams(params2);
// textView2.setGravity(Gravity.RIGHT); // Remove this
icFeature.setLayoutParams(params);
icFeature2.setLayoutParams(params);
parent.addView(textView);
parent.addView(icFeature);
parent.addView(icFeature2);
parent.addView(textView2);
linearLayout.addView(parent);
Hope that helps!希望有帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.