Onclick To Call Interface Method From Mainactivity
I need to perform onClick to call the onItemSelected listener method of another class.I don't know how to call that method in Image button onClick listener.So that it will move to
Solution 1:
You may create your own listener and add the block of code that you want to execute on click in your own listener.
Create your Interface like
InterfaceMyListener{
publicvoid myClickListener(String content);
}
Now implement this in your MainActivity
publicclassMainActivityextendsActionBarActivityimplementsOnTabChangeListener,ItemSelectedListener,MyListener {
publicvoidmyClickListener(String content){
action_bar_hometext.setText(content);
FragmentManagermanager= getSupportFragmentManager();
FragmentTransactionft= manager.beginTransaction();
HomeFirstFragmentnewFragment=newHomeFirstFragment();
ft.replace(R.id.realtabcontent, newFragment);
ft.addToBackStack(null);
ft.commit();
}
}
Solution 2:
You need to register your MainActivity
class in the LayoutActivity
class, so that LayoutActivity
class can invoke the interface's method.
Add this to your LayoutActivity.java
:
privatestaticItemSelectedListener mListener = null;
publicstaticvoidregister(ItemSelectedListener listener){
mListener = listener;
}
@OverridepublicvoidonClick(View v) {
switch (v.getId()) {
case R.id.btn_click:
if(mListener!=null){
// ADD THIS LINE
mListener.onItemSelected(POS/*Your position*/, CONTENT/*Your content*/);
}
break;
}
}
Now, in your MainActivity
class, register it to the LayoutActivity
class and follows:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LayoutActivity.register(this);
}
Hope it helps! :)
Post a Comment for "Onclick To Call Interface Method From Mainactivity"