按钮的onClick在viewPager

按钮的onClick在viewPager

本文介绍了按钮的onClick在viewPager?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个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:

  1. 您不应除了...节能状态在做的onSaveInstanceState 东西。 的onSaveInstanceState 当活动即将暂停时,才会调用;它不会被调用,直到那时,因此附加监听器在那里什么都不会做。 :(
  2. 您不能做 btn.setOnClickListener(本)除非你的 ViewPagerProjectActivity 实现onClickListener。所以,你可以实现的,或者仅使用低于code。
  1. 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. :(
  2. You can't do btn.setOnClickListener(this) unless your ViewPagerProjectActivity 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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 05:30