Skip to content

Instantly share code, notes, and snippets.

@nissuk
Created November 10, 2012 08:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nissuk/4050375 to your computer and use it in GitHub Desktop.
Save nissuk/4050375 to your computer and use it in GitHub Desktop.
Androidのイベントリスナ…
package com.example.listener;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Toast;
public class MainActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// findViewById(R.id.button1).setOnClickListener("onButton1Click"); とか
// findViewById(R.id.button1).setOnClickListener("onButton1Click", this);
// とかが全イベントで標準でできればいいような…
setOnClickListener(findViewById(R.id.button1), "onButton1Click");
}
public void onButton1Click(View v) {
Toast.makeText(this, "Hello !", Toast.LENGTH_LONG).show();
}
public void setOnClickListener(final View view, final String handlerName) {
view.setOnClickListener(new OnClickListener() {
private Method handler;
public void onClick(View v) {
if (handler == null)
try {
handler = view.getContext().getClass()
.getMethod(handlerName, View.class);
} catch (NoSuchMethodException e) {
// throw ...
return;
}
try {
handler.invoke(view.getContext(), view);
} catch (IllegalArgumentException e) {
// throw ...
} catch (IllegalAccessException e) {
// throw ...
} catch (InvocationTargetException e) {
// throw ...
}
}
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment