gpt4 book ai didi

java - 如何以编程方式设置对齐(右或左)TextView?

转载 作者:行者123 更新时间:2023-12-01 22:08:31 27 4
gpt4 key购买 nike

在以下位置设置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);

最佳答案

您正在设置TextView自己的Gravity属性,该属性控制其文本在其自身范围内的呈现方式。您想改为在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);


希望有帮助!

关于java - 如何以编程方式设置对齐(右或左)TextView?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58675048/

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