Android TextView 左对齐和右对齐文本在同一行

Android TextView Left Align and Right Align Text on the Same Line

我需要在同一行上创建 TextView 左对齐和右对齐文本,并像这样输出。我正在使用 HTML 文本或 属性 左文本和右文本之类的方法搜索解决方案,例如方法 setCompoundDrawables

这是当前的 输出

这是当前代码

PackageInfo packageInfo = (PackageInfo) getItem(position);
Drawable appIcon = packageManager.getApplicationIcon(packageInfo.applicationInfo);
int inPixels= (int) context.getResources().getDimension(R.dimen.iconsize);
appIcon.setBounds(0, 0, inPixels, inPixels);
holder.apkName.setCompoundDrawables(appIcon, null, null, null);
holder.apkName.setCompoundDrawablePadding(15);

String appName = packageManager.getApplicationLabel(packageInfo.applicationInfo).toString();
Date date=new Date(packageInfo.firstInstallTime);
SimpleDateFormat df2 = new SimpleDateFormat("dd.MM.yyyy");
String dateText = df2.format(date);
holder.apkName.setText(Html.fromHtml("<b>"+appName+"</b>("+dateText+")"));

使用两个 textView 会给你结果: 这是一个例子:

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:weight="1"
        android:gravity="left"
        android:text="Text on the Left" />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:weight="1"
        android:gravity="right"
        android:text="Text on the Right" />
</LinearLayout>

如果您试图避免创建单独的 TextView,那么您可能需要使用 SpannableString

我想,解决方案已经演示了here

您可能会通过 this link

获得更多想法

这是使用 SpannableString 后的样子。这就是我想要的。谢谢!

最终代码是:

PackageInfo packageInfo = (PackageInfo) getItem(position);
Drawable appIcon = packageManager.getApplicationIcon(packageInfo.applicationInfo);
int inPixels= (int) context.getResources().getDimension(R.dimen.iconsize);
appIcon.setBounds(0, 0, inPixels, inPixels);
holder.apkName.setCompoundDrawables(appIcon, null, null, null);
holder.apkName.setCompoundDrawablePadding(15);

String appName = packageManager.getApplicationLabel(packageInfo.applicationInfo).toString();
Date date=new Date(packageInfo.firstInstallTime);
SimpleDateFormat df2 = new SimpleDateFormat("dd.MM.yyyy");
String dateText = df2.format(date);
String LeftText=appName;
String RightText=dateText;
final String resultText = LeftText + "\n" + RightText;
final SpannableString styledResultText = new SpannableString(resultText);
styledResultText.setSpan(new AlignmentSpan.Standard(Layout.Alignment.ALIGN_OPPOSITE), LeftText.length() , LeftText.length() +RightText.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
holder.apkName.setText(styledResultText);