我必须使用按钮单击从另一个活动调用接口覆盖方法。在GridActivity类中,我使用了图像按钮。
如果我单击此按钮,我需要调用另一个活动界面覆盖方法。
GridActivity3.java:
public class GridActivity3 extends Activity implements OnClickListener {
ImageButton btn_home;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_grid3);
btn_home = (ImageButton) findViewById(R.id.btn_home);
btn_home.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_home:
break;
}
}
}
ArticleSelectedListener:
public interface ArticleSelectedListener {
public void onArticleSelected(final int position, final String content);
}
MainActivity.java:
public class MainActivity extends ActionBarActivity implements OnTabChangeListener,ArticleSelectedListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
public void onArticleSelected(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();
}
}
我不知道如何通过按钮点击从另一个活动调用接口方法。任何人都可以帮助我。谢谢。
答案 0 :(得分:0)
在您的MainActivity中,创建一个公共方法,如下所示......
public void articleSelected(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();
}
}
然后在Main活动中,用以下内容替换OnArticle中的代码...
articleSelected(position,content);
然后使用相同的方法从GridActivity调用...
MainActivity main= new MainActivity();
main.articleSelected(0,"Home");