问题描述
我有一个viewPager,并在第二页我有一个按钮。我希望它做一些事情的onClick但它没有这样做。
I've got a viewPager, and in second page i've got a button. I want it to do something onClick but it's not doing.
我已经在XML文件中完成:机器人:的onClick =buttonClick
I've done on xml file:android:onClick="buttonClick"
同时,我已经试过onCreat ...
And also i've tried setOnClickListener both inside and outside of onCreat...
这些都不摸索出...
Neither of these worked out...
我的viewPagerAdapter工作正常!我可以看到的网页,并在它们之间切换。但我只是不能让一个按钮做任何事情。它可以在适配器完成,但我会做很多事情,所以它不会是有用的......
My viewPagerAdapter works fine! I can see pages, and switch between them. But I'm just not able to make a button do anything. It can be done in adapter, but i'll do lots of things so it's not gonna be useful...
任何帮助是AP preciated。
Any help is appreciated.
下面是code:
public class ViewPagerProjectActivity extends Activity {
Button btn;
AbsoluteLayout l;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ViewPagerAdapter adapter = new ViewPagerAdapter( this );
ViewPager pager = (ViewPager)findViewById( R.id.viewpager );
pager.setAdapter( adapter );
pager.setCurrentItem(0);
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
l = (AbsoluteLayout) findViewById(R.id.layout2);
btn = (Button) l.findViewById(R.id.button1);
// btn.setOnClickListener(this);
}
public void buttonClick(View v) {
if(v.equals(btn)) {
l.setBackgroundDrawable(getResources().getDrawable(R.drawable.background));
}
}
}
推荐答案
我看到了一些问题,您的code:
I see a few problems with your code:
- 您不应除了...节能状态在做
的onSaveInstanceState
东西。的onSaveInstanceState
当活动即将暂停时,才会调用;它不会被调用,直到那时,因此附加监听器在那里什么都不会做。 :( - 您不能做
btn.setOnClickListener(本)
除非你的ViewPagerProjectActivity
实现onClickListener。所以,你可以实现的,或者仅使用低于code。
- You should not be doing anything in
onSaveInstanceState
aside from...saving state.onSaveInstanceState
is only called when the activity is about to be paused; it will not be called until then, therefore attaching a listener in there will not do anything. :( - You can't do
btn.setOnClickListener(this)
unless yourViewPagerProjectActivity
implements onClickListener. So you could implement that, or just use the code below.
的setContentView(R.layout.main)后,将这个code到
:的onCreate
Button btn = (Button) findViewById(R.id.button1);
OnClickListener listener = new OnClickListener(){
@Override
public void onClick(View v) {
v.setBackgroundDrawable(getResources().getDrawable(R.drawable.background));
}};
if (btn != null)
btn.setOnClickListener(listener);
这篇关于按钮的onClick在viewPager?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!