我想在android中的textview中获取上标和下标。我使用了sup标签,但仍然没有效果。 请告诉我在stackoverflow上建议的问题是什么。
答案 0 :(得分:1)
您可以使用此处,R.id.text
是textView的ID
TextView tv = (TextView) findViewById(R.id.text);
tv.setText(Html.fromHtml("X<sup>2</sup>")); //for SuperScript
tv.setText(Html.fromHtml("X<sub>2</sub>")); //for SubScript
答案 1 :(得分:0)
尝试这种方式它会对你有用
public class MainActivity extends AppCompatActivity {
private Context mContext;
private Activity mActivity;
private CoordinatorLayout mCLayout;
private TextView mTextView;
private String mText;
private SpannableStringBuilder mSSBuilder;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Get the application context
mContext = getApplicationContext();
mActivity = MainActivity.this;
// Get the widget reference from XML layout
mCLayout = (CoordinatorLayout) findViewById(R.id.coordinator_layout);
mTextView = (TextView) findViewById(R.id.tv);
// Initialize a new String variable
mText = "Test text to show SubscriptSpan X2 and SuperscriptSpan Y5 example.";
// Initialize a new SpannableStringBuilder instance
mSSBuilder = new SpannableStringBuilder(mText);
// Initialize a new SubscriptSpan instance
SubscriptSpan subscriptSpan = new SubscriptSpan();
// Initialize a new SuperscriptSpan instance
SuperscriptSpan superscriptSpan = new SuperscriptSpan();
// Apply the SubscriptSpan
mSSBuilder.setSpan(
subscriptSpan, // Span to add
mText.indexOf("2"), // Start of the span (inclusive)
mText.indexOf("2") + String.valueOf("2").length(), // End of the span (exclusive)
Spanned.SPAN_EXCLUSIVE_EXCLUSIVE // Do not extend the span when text add later
);
// Apply the SuperscriptSpan
mSSBuilder.setSpan(
superscriptSpan,
mText.indexOf("5"),
mText.indexOf("5") + String.valueOf("5").length(),
Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
);
// Minimize the Subscript and Superscript text size
showSmallSizeText("2");
showSmallSizeText("5");
// Display the spannable text to TextView
mTextView.setText(mSSBuilder);
}
// Custom method to make text size small
protected void showSmallSizeText(String textToSmall){
// Initialize a new RelativeSizeSpan instance
RelativeSizeSpan relativeSizeSpan = new RelativeSizeSpan(.5f);
// Apply the RelativeSizeSpan to display small text
mSSBuilder.setSpan(
relativeSizeSpan,
mText.indexOf(textToSmall),
mText.indexOf(textToSmall) + String.valueOf(textToSmall).length(),
Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
);
}
}
http://www.android--tutorials.com/2016/08/android-subscript-and-superscript.html
https://thinkandroid.wordpress.com/2009/12/28/quickly-add-superscript-subscript/