下面的代码看起来像
activity_main.xml
...
<com.example.android.demo.MySurface
android:id="@+id/gameSurface"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="5"/>
...
主活动.java
public class MainActivity extends Activity{
boolean playerFlag = false;
...
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
...
MySurface.java
public class MySurface extends SurfaceView implements SurfaceHolder.Callback{
public MySurface(Context context){
super(context);
this.context = context;
}
@Override
public boolean onTouchEvent(MotionEvent event) {
Integer index = getIndexFromCoord(event.getX(),event.getY());
// I need to access the variable playerFlag here
return true;
}
...
}
我需要从MySurface class
的onTouchEvent()
访问变量playerFlag
。有什么建议请。。。
首先创建attrs_your_view_name.xml
<resources>
<declare-styleable name="MyView">
<attr name="playerflag" format="boolean" />
</declare-styleable>
</resources>
那么在你看来类别:
public class MyView extends View {
private boolean playerflag;
public MyView(Context context) {
super(context);
init(null, 0);
}
public MyView(Context context, AttributeSet attrs) {
super(context, attrs);
init(attrs, 0);
}
public MyView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init(attrs, defStyle);
}
private void init(AttributeSet attrs, int defStyle) {
// Load attributes
final TypedArray a = getContext().obtainStyledAttributes(
attrs, R.styleable.MyView, defStyle, 0);
playerflag=a.getBoolean(R.styleable.MyView_playerflag,false);
}
public boolean isPlayerflag() {
return playerflag;
}
public void setPlayerflag(boolean playerflag) {
this.playerflag = playerflag;
}
}
在主活动中:
MyView myview=(MyView)findViewById(R.id.your_id);
myview.setPlayerflag(this.playerflag);
您现在还可以从xml:中指定它
<com.example.myapp.MyView
android:layout_width="match_parent"
android:layout_height="match_parent"
app:playerflag="true"
/>
我希望这将帮助你:)