Search code examples
androidandroid-fragmentsandroid-tabhostfragment-tab-host

How do I call an Activity within a TabHost?


I have a fragment and within that Fragment I have a button that can called another Activity

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

  // Inflate the layout for this fragment
  View view = inflater.inflate(R.layout.fragment_test_fragment, container, false);

  Button button = (Button) view.findViewById(R.id.button2);
  button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
          Intent i = new Intent(getActivity(), AnotherPage.class);
          startActivity(i);
        }
    });

Now this works fine.

But however, now I want to do the Same thing but within a TabHost that I created in this Fragment.

So how do I call getActivity() within my Tab?

I tried doing:

public class tab_two_graph extends AppCompatActivity {

  View v;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_tab_two_graph);

     Intent intent = getParent().getIntent();
     v = intent.getParcelableExtra("view");

    Button b = (Button) findViewById(R.id.button2);
    b.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
           Intent i = new Intent(v.getActivity(), Alert_main_page.class);
            startActivity(i);
        }
    });

  }

But it just throws errors.


Solution

  • Just to add more information to the answers here.

    You do not have to pass an Activity to start another activity. You need to pass a context, which can be accessed by using tab_two_graph.this. Which is why the following works :

    startActivity(new Intent(tab_two_graph.this, Alert_main_page.class));