質問

I have two files MainActivity.java and GestureListener.java In MainActivity's onActivityCreate(), am starting a thread GestureListener.start(). GestureListener has a thread which waits for the gesture event. When the event comes, i want to transfer to a function in MainActivity.java.

Is it possible to do this?

役に立ちましたか?

解決

Make parameterized constructor of GestureListener and when you make of object of GestureListener then simply pass object of MainActivity into that constructor and inside GestureListener class where you want to call MainActivity's method then simply call that method from that Object.

check following code :

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    GestureListener listener = new GestureListener(this);
    listener.start();
}

@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;
}

public void makeSomeCalculation() {
    //logic to change some UI 
}
}

and check GestureListener class :

public class GestureListener extends Thread {

MainActivity mainActivity;

public GestureListener(MainActivity mainActivity) {
    // TODO Auto-generated constructor stub

    this.mainActivity = mainActivity;
}

public void run() {
   //write other logic
        mainActivity.makeSomeCalculation();
   //write other logic
 }
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top