java - setLayoutParams() 在 API <= 23 中不起作用
问题描述
我正在尝试将句子拆分为单词并将单词作为 TextViews 放入 RelativeLayout,但是当我将 layoutparams 设置为 TextView 时,在 API 23 及更早版本中不起作用。仅当我使用 LinearLayout.LayoutParams 而不是 RelativeLayout.LayoutParams 时,它才能在 API 24 和更新版本中正常工作。
这是我的拆分方法:
public void splitWords(){
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
int size = 0;
int bgId = 0;
leftM = convertToDp(5);
String [] splitSentence = sentence.split(" ");
size = splitSentence.length;
bgId = R.drawable.word_bg;
for (int i = 0;i < size;i++){
final TextView word = new TextView(this);
word.setText(splitSentence[i]);
word.setBackgroundResource(bgId);
word.measure(0, 0);
int butonWidth = word.getMeasuredWidth();
if(width - convertToDp(60) - leftM <= butonWidth){
leftM = convertToDp(5);
topM += butonWidth + 5;
}
params.leftMargin = leftM + 2;
params.topMargin = topM;
word.setLayoutParams(params);
leftM += butonWidth;
wordsContainer.addView(word);
}
wordsContainer.setGravity(Gravity.CENTER); }
这是我的相对布局:
<RelativeLayout
android:id="@+id/wordsContainer"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:layout_marginLeft="2dp"
android:layout_marginTop="20dp"
android:layout_marginRight="2dp"
android:background="@drawable/white_bg_no_border"
android:elevation="2dp"
android:orientation="vertical"
android:paddingLeft="20dp"
android:paddingTop="30dp"
android:paddingRight="20dp"
android:paddingBottom="50dp" />
解决方案
您需要为子视图创建单独的布局参数,而不是全部使用一个。在您的代码中将其更改为内部循环
推荐阅读
- python - 如何在熊猫的数据框中获得具有某些条件的先前值
- java - 如果嵌套的 Optional 为空,则返回另一个 Optional
- javascript - TypeError:e.removeHeader 不是 nextjs 中的函数
- nexus - 如何在 Sonatype Nexus 3 中删除具有给定版本的所有软件包
- node.js - 如何合计计算字段的每个枚举的总数?
- python - 删除flask-sqlalchemy中对另一个对象具有外键的所有对象
- java - 如何在网格中生成点流(X 和 Y 坐标)?
- sql - 如何计算在大查询中执行多个事件的用户数?
- spring-security-oauth2 - 将现有的用户名/密码帐户连接到 OpenID
- elasticsearch - pod重启时,如果想在pod定义文件中运行shell脚本怎么办?