一旦布局被创建,我想要一个按钮被自动点击,为此我使用了button.performClick()。
问题是它不起作用。看起来我不能在onCreate, onStart, onResume方法中做到这一点。按钮及其事件是在什么时候创建的,这样我就可以单击它了?
这
@Override
protected void onResume() {
super.onResume();
mybutton.performClick();
}不起作用。
发布于 2013-03-05 21:34:27
在一个类似的案例中,这对我很有效:
mybutton.post(new Runnable(){
@Override
public void run() {
mybutton.performClick();
}
});这样,只有当按钮已经加载到布局中时,runnable才会运行。
发布于 2013-03-05 21:33:46
您需要使用ViewTreeObserver
ViewTreeObserver vto = mybutton.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
vto.removeOnGlobalLayoutListener(this);
mybutton.performClick();
}
});发布于 2013-03-05 21:43:43
我闻到的似乎是你忘记将onClicklistner添加到你的视图中,我测试了你的方法,它工作得很好,我做了如下操作:
全局定义按钮Button btn;
在onCreate()中
btn=(Button)findViewById(R.id.button);
btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
dialog();
}
});在onResume()中
@Override
protected void onResume() {
btn.performClick();
super.onResume();
}它成功地显示了一个对话框!
https://stackoverflow.com/questions/15225036
复制相似问题