Androidアプリ入門 No.08 TextViewのActivityからの操作
今風に書き直した記事がありますので、合わせて参照ください。
blog.webarata3.link
TextView
Activityからの操作
Javaからの操作は以下のように行う。まず、main.xmlを以下のように設定する。
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="#ffffff" > <TextView android:id="@+id/normalText" android:layout_width="fill_parent" android:layout_height="fill_parent" android:textColor="#000" android:textSize="28sp" android:text="ABCabc123-normal" android:textStyle="normal" /> </LinearLayout>
次に、MainActivity.javaを以下のように記述する。
package sample.at; import android.app.Activity; import android.graphics.Color; import android.os.Bundle; import android.widget.TextView; public class MainActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); // @+id/で指定したidでコンポーネントを取得 // R.id.取得するコンポーネントのidで取得できる。 // 補完がきくので間違えない。 TextView textView = (TextView) findViewById(R.id.normalText); textView.setText("Java側で属性を好きなように設定することができます。"); textView.setBackgroundColor(Color.argb(255, 255, 255, 0)); textView.setTextColor(Color.parseColor("#ffff0000")); textView.setTextScaleX(2.5f); } }
main.xmlの指定よりJavaからの指定が優先される。色の指定について補足する。色は、Colorクラスを用いて指定する。Colorクラスでは主に以下のstaticメソッドで色を指定する。
メソッド | 説明 |
---|---|
argb(int alpha, int red, int green, int blue) | alpha(透明度)、red(赤)、green(緑)、blue(青)で色を指定する。それぞれ0〜255を指定する。alphaは0が透明、255が不透明となる。 |
parseColor(String colorString) | colorStringは#aarrggbbで指定する。aaはalpha、rrはred、ggはgreen、bbはblueで16進数で指定する。たとえば、#ffff0000と指定する。 |