Androidでテキストエディタ その2
アプリ作成の要とも言える画面作成です(途中まで)。
画面作成
Androidでは画面をxmlファイルを作成するので、以下を参考にボタンを追加(各画面でBlank Activityを使用)。
なお、ファイルはプロジェクト名>app>src>main>res>layoutに作成されます。Android StudioであればGUIで追加も可能ですが、テキストエディタでファイルを開いて編集した方が速いかもしれません。
Android Studioで始める!レイアウト超入門 - nanapi TechBlog
メインページには編集ページに遷移するためのボタンを配置します(activity_main_view.xml)。
<RelativeLayout 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:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
android:background="#FFFFFF"
tools:context="com.notenotenote.app.MainViewActivity">
<Button
android:adjustViewBounds="true"
android:layout_width="match_parent"
android:layout_height="250dp"
android:layout_marginTop="20dp"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:layout_marginBottom="20dp"
android:id="@+id/btnLastText"
android:textSize="22sp"
android:textColor="#000000"
android:gravity="top|left"
android:background="#D8F781"
android:onClick="openEditView"
/>
</RelativeLayout>
Activityを作成したときのものをほぼそのまま使っているので(背景色は指定していますが)、具体的にはButtonのタグですね。
adjustViewBoundsをTrueにすることで画面サイズに合わせて縦横の長さが調整されるようにする。
gravityで"top|left"を指定してテキストが左上から表示されるようにする。
onClickでクリックされたときに呼ばれるメソッドを指定する。
参考書籍
ボタンが押されたらメソッドを実行して編集画面に遷移する
メインページのクラス"MainViewActivity"で以下のように記述してページ遷移できるようにします。
("android.view.View"、"android.content.Intent"のインポートが必要になります)
public void openEditView(View v){
Intent ittMoveView = new Intent(MainViewActivity.this, EditViewActivity.class);
// 次画面のアクティビティ起動
startActivity(ittMoveView);
}
メソッドの実行
メソッド名はactivity_main_view.xmlで指定したものを、引数にはViewを記述します(引数なしにするとメソッドが見つからないとエラーになります)。
画面遷移
画面遷移を、Intentを使って行います。今表示しているActivity、遷移後のActivityを指定して、startActivityで切り替え。
参考
画面を遷移する - Androidプログラマへの道 〜 Moonlight 明日香 〜
なお、Activityを切り替えると、最初にそのActivityを開いたときと同じようにまずonCreate()が呼ばれます。
前回オブジェクトに値を格納していても初期化されてしまうので、データをActivity間で共有したい場合は別に値を渡したり、どこかに保存しておく必要があります。
この辺りはまた後ほど...。