テキストを2列に表示したい。
元。最初の列に最初の文字列を追加し、画面の高さの終わりを取得した後、テキストを2列目に追加する必要があります。新聞のように。
以下のコードを試してみましたが、java.lang.StringIndexOutOfBoundsExceptionが表示されます
Java コード
final TextView tvl = (TextView)findViewById(R.id.textl);
final TextView tvr = (TextView)findViewById(R.id.textr);
final String text = "sdf";
tvl.post(new Runnable() {
@Override
public void run() {
TextMeasure(text,tvl,tvr);
}
});
private void TextMeasure(String text,
TextView tvl,TextView tvr) {
// Get number of lines of text that will fit on the screen
int linesPerScreen = tvl.getHeight()/(tvl.getLineHeight() );
// Measure how much text will fit across the TextView
Paint paint = tvl.getPaint();
int textWidth = paint.breakText(text, 0, text.length(),
true, tvl.getWidth(), null);
// Total amount of text to fill the TextView is
// approximately:
int totalText = textWidth * linesPerScreen;
String leftText = text.substring(0,totalText);
String rightText = text.substring(totalText,
text.length());
tvl.setText(leftText);
tvr.setText(rightText);
}
xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:weightSum="2"
tools:context=".MainActivity" >
<TextView
android:id="@+id/textl"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="@string/hello_world" />
<TextView
android:id="@+id/textr"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="@string/hello_world" />
</LinearLayout>