facebook twitter hatena line email

Android/UIテキスト

提供: 初心者エンジニアの簡易メモ
移動: 案内検索

テキスト書き換え

  • xmlレイアウト
<TextView android:id="@+id/textView1"
          android:text="@string/hello"
          android:layout_width="match_parent"
          android:layout_height="wrap_content" />
  • java
TextView textView1 = (TextView)findViewById(R.id.textView1);
textView1.setText("テスト");

テキストアウトライン設定

  • xml
<TextView android:layout_width="match_parent"
           android:layout_height="wrap_content"
           android:textColor="#ffffffff"
           android:shadowColor="#ff000000"
           android:shadowDy="0"
           android:shadowDx="0"
           android:shadowRadius="4"
           android:text="test"/>

改行テキスト

  • xml
<TextView android:layout_width="match_parent"
           android:layout_height="wrap_content"
           android:text="1、\nテストです\n\n2、てすとです"
           android:singleLine="false"
/>

¥nでなく\n (macだとoption+nで入力)でなければならない。

中央寄せ

android:gravity="center"

フォントサイズ

android:textSize="18sp"

余白

android:paddingTop="10sp"
android:paddingBottom="10sp"
android:paddingLeft="10sp"
android:paddingRight="10sp"

match_parentとmatch_parent

同じ意味だが、match_parentの方が推奨(android 2.2[API 8]以上)

参考: http://android49.blog.fc2.com/blog-entry-20.html

テキスト表示

Paint paint = new Paint();
paint.setColor(Color.BLUE);
// アンチエイリアス
paint.setAntiAlias(true);
// 文字の大きさ
paint.setTextSize(40);
// 指定した位置に文字列を描く
canvas.drawText("テキスト表示", 0, 0, paint);

テキストを傾ける(回転)

// Pathに沿って文字を書く
paint.setColor(Color.RED);
Path path = new Path();
path.moveTo(50, 200);
path.lineTo(450, 500);
canvas.drawTextOnPath("文字列を傾ける", path, 0, 0, paint);
paint.setColor(Color.GREEN);

テキストを傾ける(回転)メソッド化

  // テキスト回転描画
  public static void drawTextRota(Canvas canvas, String str, int x, int y, int degrees, int size) {
    Paint paint = new Paint();
    // Pathに沿って文字を書く
    paint.setColor(Color.RED);
    // アンチエイリアス
    paint.setAntiAlias(true);
    // 文字の大きさ
    paint.setTextSize(size);
    Path path = new Path();
    // 文字列の幅を取得
    float textWidth = paint.measureText(str);
    float rad = (float)(degrees * Math.PI / 180);
    int x1 = (int)(- textWidth / 2 * Math.cos(rad) + x);
    int y1 = (int)(- textWidth / 2 * Math.sin(rad) + y);
    int x2 = (int)(textWidth / 2 * Math.cos(rad) + x);
    int y2 = (int)(textWidth / 2 * Math.sin(rad) + y);
    path.moveTo(x1, y1);
    path.lineTo(x2, y2);
    canvas.drawTextOnPath(str, path, 0, 0, paint);
  }