クラス内外でのインスタンス操作でお悩み中
無料テキスト11章のp.19あたり、ペイントアプリの拡張で悩んでいた。追加したい機能は2つ。
- 描画のクリア
- 筆色の変更
アプリの完成イメージはこんな感じだ。筆色の選択を別画面にして、筆色を格納するグローバルな変数をまた別クラスにして共有する感じ。なんとかかんとか描画クリアは実装できたが、View継承クラスでインスタンスが呼べなくて悩んでいるところ。
Viewがね、MainActivityに埋め込まれてるような作りなので、いろいろ操作しづらいのよね。
private CustomView cView;
これでクラスのインスタンス化をしてるつもりだったので、そこでヌルポを返されても何を入れてやればいいのか悩んだ悩んだww 結果、idだったのですが、何でもかんでもid呼ぶ感じだな、泥は。
MainActivity.java
public class MainActivity extends Activity { private CustomView cView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); if (id == R.id.action_settings) { // 画面遷移 Intent intent = new Intent(this, SettingsPage.class); startActivity(intent); return true; } else if (id == R.id.action_clear) { // リセットが押されたらキャンバスクリア if (cView != null) { cView.clear_Canvas(); } else { // cViewがnullならIDを格納 CustomView cView = (CustomView)this.findViewById(R.id.paintView); cView.clear_Canvas(); } return true; } return super.onOptionsItemSelected(item); } }
CustomView.java
public class CustomView extends View { // -------中略-------- @Override protected void onDraw(Canvas canvas) { // Viewの描画関数で、パスを描画する canvas.drawBitmap(mBitmap, 0, 0, mPaint); canvas.drawPath(mPath, mPaint); } // -------中略-------- // キャンバスクリア用のメソッド public void clear_Canvas() { mCanvas.drawColor(0,Mode.CLEAR); invalidate(); } }
main_activity.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:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context=".MainActivity" > <com.example.appsdk_customview1.CustomView android:id="@+id/paintView" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </RelativeLayout>