【问题标题】:Can't find TextView from MainActivity [duplicate]无法从 MainActivity 中找到 TextView [重复]
【发布时间】:2018-03-13 20:22:39
【问题描述】:

我的 android 应用中有一个 DrawerLayout,它有一个使用 nav_header_main2 布局的 NavigationView。在 nav_header_main2 布局文件中有一个 ImageView 和 2 个 TextView,在我的 MainActivity 中,我试图获取这些 TextView 项目,以便我可以使用用户名和电子邮件地址动态填写内容,但是每当我尝试时,我总是得到一个空引用访问它们。 这是主布局文件...

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:openDrawer="start">

    <include
        layout="@layout/app_bar_main2"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

    <android.support.design.widget.NavigationView
        android:id="@+id/nav_view"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:fitsSystemWindows="true"
        app:headerLayout="@layout/nav_header_main2"
        app:menu="@menu/activity_main2_drawer"/>

</android.support.v4.widget.DrawerLayout>

如您所见,NavigationView 正在使用“nav_header_main2”,这是该文件...

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="@dimen/nav_header_height"
    android:background="@drawable/side_nav_bar"
    android:gravity="bottom"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:theme="@style/ThemeOverlay.AppCompat.Dark">

    <de.hdodenhof.circleimageview.CircleImageView
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:id="@+id/menu_user_photo"
        android:layout_width="64dp"
        android:layout_height="64dp"
        android:layout_gravity="center_horizontal"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:src="@drawable/ic_person_white"
        app:border_color="@color/colorTransparent"
        android:layout_marginStart="10dp"
        android:layout_marginLeft="10dp"
        android:layout_marginTop="3dp"
        android:layout_marginBottom="0dp"
        app:border_width="1dp"/>

    <!--<ImageView-->
        <!--android:id="@+id/imageView"-->
        <!--android:layout_width="wrap_content"-->
        <!--android:layout_height="wrap_content"-->
        <!--android:paddingTop="@dimen/nav_header_vertical_spacing"-->
        <!--app:srcCompat="@android:drawable/sym_def_app_icon"/>-->

    <TextView
        android:id="@+id/menu_username"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingTop="@dimen/nav_header_vertical_spacing"
        android:layout_gravity="center_horizontal"
        android:gravity="center_horizontal"
        android:text="Android Studio"
        android:textAppearance="@style/TextAppearance.AppCompat.Body1"/>

    <TextView
        android:id="@+id/textView"
        android:gravity="center_horizontal"
        android:layout_gravity="center_horizontal"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="android.studio@android.com"/>

</LinearLayout>

然后在我的 MainActivity 中,我尝试了多种访问“menu_username”项的方法,但它们都返回空引用。这是我现在的主要课程...

public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {

    public static final String EXTRA_MESSAGE = "text.notreal.justatest.MESSAGE";
    public static final int TAG_KEY = 0;
    public static final int TAG_VALUE = 0;
    public List<Post> posts = new ArrayList<>();

    public FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this,
                drawer,
                toolbar,
                R.string.navigation_drawer_open,
                R.string.navigation_drawer_close
        );
        drawer.setDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);
        //THIS IS WHAT IS FAILING
        //I HAVE ALSO TRIED JUST USING findViewById(R.id.menu_username); NULL STILL
        TextView menuUserName = (TextView) navigationView.findViewById(R.id.menu_username);
        if(menuUserName == null) {
            Log.d("MAIN ACTIVITY", "Somehow the menu_username doesn't exist");
        }
        if(findViewById(R.id.frameLayout) != null) {

            if(savedInstanceState != null) {
                return;
            }
            AllPostsFragment fragment = new AllPostsFragment();
            fragment.setArguments(getIntent().getExtras());
            getSupportFragmentManager().beginTransaction().add(R.id.frameLayout, fragment).commit();
            }
        }

     @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch(item.getItemId()) {
            case android.R.id.home:
                this.finish();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

        @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
        } 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;
    }
}

如您所见,我正在尝试使用 NavigationView 对象来抓取它,但这不起作用,但我也尝试过仅使用

TextView menuUsername = (TextView) findViewById(R.id.menu_username);

它也返回一个空引用。如何在我的主要活动中获取用户名和电子邮件字段,以便我可以动态填写内容?谢谢

【问题讨论】:

    标签: java android android-layout


    【解决方案1】:

    你不会这样发现的。正确的方法是首先找到您的NavigationView,然后使用getHeaderView() 获取它的HeaderView,然后在HeaverView 中搜索您的小部件:

    NavigationView nv = findViewById(R.id.nav_view);
    TextView menuUsername = nv.getHeaderView(0).findViewById(R.id.menu_username);
    

    或更紧凑的方式

    TextView menuUsername = findViewById(R.id.nav_view)
                            .getHeaderView(0).findViewById(R.id.menu_username);
    

    【讨论】:

    • 完美!!非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-24
    • 1970-01-01
    • 1970-01-01
    • 2011-10-04
    • 1970-01-01
    相关资源
    最近更新 更多