我想调用一个方法showMessage(),它在我的主要活动中从扩展Button的TestButton类中定义。我在下面使用的代码抛出一个空指针异常。我不知道如何解决这个问题。你能帮我吗?
MainActivity
public class MainActivity extends MultiTouchActivity {
TestButton btn;
@Override
public void onCreate(final Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btn = (TestButton)findViewById(R.id.button4);
btn.setOnTouchListener(this);
}
public void showMessage()
{
Toast.makeText(this, "hello", Toast.LENGTH_SHORT).show();
}
TestButton类
public class TestButton extends Button {
MainActivity m;
public TestButton(final Context context, final AttributeSet attrs)
{
super(context, attrs);
// TODO Auto-generated constructor stub
}
@Override
public boolean onTouchEvent(final MotionEvent event)
{
if (event.getAction() == MotionEvent.ACTION_UP)
{
m = new MultitouchtestActivity();
m.showMessage();
}
return super.onTouchEvent(event);
}
}
修改 谢谢@ΦXoce웃Пepeúpa这解决了我的问题,但我做了一点改动。
btn.setCallback(this); from btn.setCallback();
和
public void setCallback(final ICallback iCallback)
答案 0 :(得分:0)
2件事:
实施回复,例如:
interface ICallback{
void showMessage();
}
public class MainActivity extends MultiTouchActivity implements ICallback{
TestButton btn;
@Override
public void onCreate(final Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btn = (TestButton)findViewById(R.id.button4);
btn.setOnTouchListener(this);
//register here the callback
btn.setCallback(this);
}
@Override
public void showMessage()
{
Toast.makeText(this, "hello", Toast.LENGTH_SHORT).show();
}
public class TestButton extends Button {
MainActivity m;
ICallback iCallback;
public setCallback(final ICallback iCallback)
{
this.iCallback = iCallback;
}
public TestButton(final Context context, final AttributeSet attrs)
{
super(context, attrs);
// TODO Auto-generated constructor stub
}
@Override
public boolean onTouchEvent(final MotionEvent event)
{
if (event.getAction() == MotionEvent.ACTION_UP)
{
iCallback.showMessage();
}
return super.onTouchEvent(event);
}
}