Search code examples
javaandroidandroid-5.0-lollipop

Accessing TextView from MainActivity


So I created a Navigation Drawer Activity using Android Studio 2.1.2 by doing File-> New -> Project -> Navigation Drawer Activity. I've got 4 layout files as

  1. nav_header_main.xml
  2. content_main.xml
  3. app_bar_main.xml
  4. activity_main.xml

content.main.xml has a TextView with an id of helloTextView (I have set it manually). On the MainActivity, a method handles the Navigation Item Selection Event. Now my goal is to change the text of the text view of content.main.xml and set the text to the content of user selection. Please note the comment on the following code block--

@SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();

        if (id == R.id.nav_camera) {
            // Handle the camera action
            // I want to change the content of helloTextView here
            // I.E setText("You Selected Camera!")
        } else if (id == R.id.nav_gallery) {

        } else if (id == R.id.nav_slideshow) {

        } else if (id == R.id.nav_manage) {

        } else if (id == R.id.nav_share) {

        } else if (id == R.id.nav_send) {

        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

How can I go about to establish this?


Solution

  • ((TextView) findViewById(R.id.helloTextView)).setText("You Selected Camera!"); should work.

    Normally, you would declare a variable such as: TextView myTextView; as a class-wide variable and then in your onCreate() or onCreateView() you'd put:

    myTextView = (TextView) findViewById(R.id.helloTextView); (similar to what you did with DrawerLayout)

    Then, you could just put:

    myTextView.setText("You Selected Camera!");

    Then anywhere else in your Activity you could just use myTextView instead of having to use findViewById() every time.

    For now though, the line of code at the very top of this answer will work for you. :)