TextView多行结尾的控件变化

1、需求

控件textview的内容超过多行后结尾跟着控件(textView,icon,ImageView等)

2、效果:

在这里插入图片描述

3、主要代码实现:

①xml文件:

使用RelativeLayout布局将两个控件进行排列
两个控件:TextView,TextView

②java文件:

加载控件
代码实现
public class MainActivity extends AppCompatActivity {
    
    
	final static String TAG = "MainActivity";
	@Override
	protected void onCreate(Bundle savedInstanceState) {
    
    
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		TextView text = findViewById(R.id.text);
		TextView mTextElse = findViewById(R.id.text_other);
		String title = "qwerutiitorjdndkcmkdeeiidkdkmsmmmem,kdkdhhhhhhhhhhhhhhhhhhkekkdd ";
		//先设置原始文本
		text.setText(title);
		//使用post方法,在TextView完成绘制流程后在消息队列中被调用
		text.post(new Runnable() {
    
    
			@Override
			public void run() {
    
    

				int left = (int) text.getLayout().getLineWidth(text.getLineCount()-1);
				Log.i(TAG, "run: s " + left);
				int top =  text.getLayout().getHeight() / text.getLineCount() *(text.getLineCount()-1);
				RelativeLayout.LayoutParams layout = (RelativeLayout.LayoutParams) mTextElse.getLayoutParams();
				layout.setMargins(left, top , 0, 0);//设置位置左上右下
				Log.i(TAG, "run:heght " + text.getLayout().getHeight() / text.getLineCount() *(text.getLineCount()-1));
				mTextElse.setLayoutParams(layout);

			}
		});

左边的距离表示的是某行文字中代码的文字的长度,上面的距离为行数减一的高度即可。

如果TextView多行文字时出现换行出现混乱

//获取第一行的宽度
float lineWidth = text.getLayout().getLineWidth(0);
//获取第一行最后一个字符的下标
int lineEnd = text.getLayout().getLineEnd(0);
Log.i(TAG, "run:lineEnd " + lineEnd);
//计算每个字符占的宽度
float widthPerChar = lineWidth / (lineEnd + 1);
//计算TextView一行能够放下多少个字符
int numberPerLine = (int) Math.floor(text.getWidth() / widthPerChar);
Log.i(TAG, "run: " + numberPerLine);
//在原始字符串中插入一个空格,插入的位置为numberPerLine - 1
StringBuilder stringBuilder = new StringBuilder(title).insert(numberPerLine - 1, " ");

日志:

在这次的效果的实现过程中,就是一直在考虑如何使用较为简单的方式进行效果的实现,能够确定不同控件之间实现效果,在网络中查询较多的实现效果都是主要针对于图文之间的呈现,发现通过位置的更改可以更好地实现效果。

猜你喜欢

转载自blog.csdn.net/qq_51108920/article/details/127364241