我需要执行onClick来调用另一个类的onItemSelected侦听器方法。我不知道如何在图像按钮onClick listener中调用该方法。所以它将移动到HomeFirstFragment类。
ItmeSelectedListener
public interface ItemSelectedListener {
public void onItemSelected(final int position, final String content);
}
LayoutActivity.java:
public class LayoutActivity extends Activity implements OnClickListener {
ImageButton btn_click;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_grid3);
btn_click = (ImageButton) findViewById(R.id.btn_click);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_click:
break;
}
}
}
MainActivity.java:
public class MainActivity extends ActionBarActivity implements OnTabChangeListener,ItemSelectedListener {
private TextView action_bar_hometext;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
public void onItemSelected(int position, String content)
{
if(position==0)
{
action_bar_hometext.setText(content);
FragmentManager manager = getSupportFragmentManager();
FragmentTransaction ft = manager.beginTransaction();
HomeFirstFragment newFragment = new HomeFirstFragment();
ft.replace(R.id.realtabcontent, newFragment);
ft.addToBackStack(null);
ft.commit();
}
}
如果我单击LayoutActivity类中的btn_click,我需要执行onClick以从MainActivity调用接口方法。
任何人都可以帮助我。谢谢。
答案 0 :(得分:2)
您可以创建自己的侦听器,并在您自己的侦听器中添加要执行的代码块。
像
一样创建您的界面Interface MyListener{
public void myClickListener(String content);
}
现在在MainActivity中实现它
public class MainActivity extends ActionBarActivity implements OnTabChangeListener,ItemSelectedListener,MyListener {
public void myClickListener(String content){
action_bar_hometext.setText(content);
FragmentManager manager = getSupportFragmentManager();
FragmentTransaction ft = manager.beginTransaction();
HomeFirstFragment newFragment = new HomeFirstFragment();
ft.replace(R.id.realtabcontent, newFragment);
ft.addToBackStack(null);
ft.commit();
}
}
答案 1 :(得分:1)
您需要在MainActivity
课程中注册LayoutActivity
课程,以便LayoutActivity
课程可以调用界面的方法。
将此添加到您的LayoutActivity.java
:
private static ItemSelectedListener mListener = null;
public static void register(ItemSelectedListener listener){
mListener = listener;
}
@Override
public void onClick(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;
}
}
现在,在MainActivity
课程中,将其注册到LayoutActivity
课程,然后执行以下操作:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LayoutActivity.register(this);
}
希望它有所帮助! :)