我有一个 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 文件:android:onClick="buttonClick"
I've done on xml file: android:onClick="buttonClick"
而且我在 onCreat 内外都尝试过 setOnClickListener...
And also i've tried setOnClickListener both inside and outside of onCreat...
这些都没有成功...
我的 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...
感谢任何帮助.
代码如下:
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));
}
}
}
我发现你的代码有一些问题:
I see a few problems with your code:
onSaveInstanceState
中做任何事情.onSaveInstanceState
仅在activity即将暂停时调用;在那之前它不会被调用,因此在其中附加一个监听器不会做任何事情.:(ViewPagerProjectActivity
实现 onClickListener,否则您不能执行 btn.setOnClickListener(this)
.所以你可以实现它,或者只使用下面的代码.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. :(btn.setOnClickListener(this)
unless your ViewPagerProjectActivity
implements onClickListener. So you could implement that, or just use the code below.将此代码移动到 setContentView(R.layout.main)
之后的 onCreate
中:
Move this code into onCreate
after setContentView(R.layout.main)
:
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);
这篇关于viewPager中的按钮onClick?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!