MainActivity类:
package com.example.myfirstapp;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
public class MainActivity extends Activity
{
boolean isPlaying = false;
static int[][] _grid = new int[10][13];
//Fill grid with zeros (just in case)
public void initialiseGrid()
{
for(int i = 0; i < 10; i++)
{
for(int j = 0; j < 13; j++)
{
_grid[i][j] = 0;
}
}
}
//Note addition
public void addToGrid(int x, int y)
{
_grid[x][y] = 1;
}
//Note removal
public void removeFromGrid(int x, int y)
{
_grid[x][y] = 0;
}
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initialiseGrid();
}
//Play button functionality
public void playButton (View v)
{
//button logic
}
//Stop button functionality
public void stopButton (View v)
{
//button logic
}
}
布局xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:paddingLeft="16dp"
android:paddingRight="16dp" >
<com.example.myfirstapp.showImage
android:id="@+id/my_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
... />
<Button
... />
</RelativeLayout>
自定义视图类:
package com.example.myfirstapp;
//imports
class showImage extends View
{
Vector<Pair<Integer, Integer>> _notePositions = new Vector<Pair<Integer, Integer>>();
Canvas _canvas;
Paint _paint = new Paint();
MainActivity _main;
Bitmap _score;
Bitmap _note = BitmapFactory.decodeResource(getResources(), R.drawable.note);
Bitmap _tempNote = BitmapFactory.decodeResource(getResources(), R.drawable.note);
public showImage (Context context)
{
super(context);
}
public showImage (Context context, AttributeSet attrs)
{
super(context);
}
@Override
public void onDraw (Canvas canvas)
{
//irrelevant code
}
@Override
public boolean onTouchEvent(MotionEvent event)
{
//irrelevant code
}
}
答案 0 :(得分:1)
好吧,因为我使用的是静态函数,所以我设法做了一个我称之为解决方法的工作。
在我的MainActivity课程中,我有:
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initialiseGrid();
showImage.getIstance(this); //this is the new line
}
在我的showImage类中,我有:
static MainActivity _main;
.
.
.
public static void getIstance(MainActivity mainActivity)
{
_main = mainActivity;
}
在我的情况下,我不会有任何其他情况,所以这完全有效。
答案 1 :(得分:0)
You can pass the context of your MainActivity class to your Custom view class.
// In Main Activity
public class MainActivity extends Activity
{
onCreate(Bundle b)
{
// Create Instance of your view class & pass context of your MainActivity class
ShowImage showImage=new ShowImage(MainActivity.this);
}
// In Custom View class
public class ShowImage extends View
{
Context context;
// Create constructor ShowImage(with argument Context)
public ShowImage(Context context)
{
this.context=context;
}
}