如何从SurfaceView访问父活动变量?

时间:2015-12-31 18:40:57

标签: android android-activity surfaceview

我的代码看起来像

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"/>
...

MainActivity.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;
    }
...
}

我需要从playerFlag的{​​{1}}访问变量onTouchEvent()。有任何建议请...

1 个答案:

答案 0 :(得分:0)

首先创建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;
    }
}
MainActivity中的

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"
        />

我希望这会对你有所帮助:)。