简体   繁体   中英

Call override method from another activity

I have to call interface override method from another activity using button click.In GridActivity class I have using the image button.

If I click this button I need to call the other activity interface override method.

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();
        }
     }

I don't know how to call the interface method from another activity on button click.Anyone can help me with this.Thank You.

In your MainActivity, create a public method as follows...

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();
    }
  }

Then in the Main activity, replace the code inside OnArticle selected with the following...

articleSelected(position,content);

Then use the same method to call from GridActivity...

     MainActivity main= new MainActivity();
     main.articleSelected(0,"Home");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM