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.
I've done on xml file: android:onClick="buttonClick"
And also i've tried setOnClickListener both inside and outside of onCreat...
Neither of these worked out...
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...
Any help is appreciated.
Here's 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));
}
}
}
I see a few problems with your code:
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.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);