无法在android studio中将文本设置为textview

iyfamqjs  于 2021-08-25  发布在  Java
关注(0)|答案(1)|浏览(361)

我对每个文本视图都有这个问题。我尝试了很多东西,但就是没能成功。如果你有任何建议,请帮忙。我是安卓系统的乞丐,但我认为这是一个简单的问题,但我就是不能解决它。提前谢谢。
片段主页代码

package com.example.mmreviews;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

public class HomeFragment extends Fragment {

@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    LayoutInflater lf = getActivity().getLayoutInflater();
    View view = lf.inflate(R.layout.fragment_home, container, false);
    view.findViewById(R.id.btn_edit).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            getFragmentManager().beginTransaction().replace(R.id.fragment_container, new EditFragment()).commit();
        }
    });

    view.findViewById(R.id.btn_logout).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(getActivity(), LogIn.class);
            startActivity(intent);

        }
    });
    TextView textViewUsernameInfo = view.findViewById(R.id.username);
    textViewUsernameInfo.setText("Some text");

    return view;
}
}

我要设置的文本的xml。也许我应该试试其他的文本视图?

<TextView
                android:id="@+id/username"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_toEndOf="@id/text1"
                android:layout_toRightOf="@id/text1"
                android:textColor="#4B83E5"
                android:textSize="16sp">

            </TextView>

我得到的例外

E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.mmreviews, PID: 6184
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.mmreviews/com.example.mmreviews.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2957)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3032)
    at android.app.ActivityThread.-wrap11(Unknown Source:0)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1696)
    at android.os.Handler.dispatchMessage(Handler.java:105)
    at android.os.Looper.loop(Looper.java:164)
    at android.app.ActivityThread.main(ActivityThread.java:6944)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:327)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1374)
 Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
    at com.example.mmreviews.HomeFragment.onCreateView(HomeFragment.java:38)
    at androidx.fragment.app.Fragment.performCreateView(Fragment.java:2600)
    at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManagerImpl.java:881)
    at androidx.fragment.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManagerImpl.java:1238)
    at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManagerImpl.java:1303)
    at androidx.fragment.app.BackStackRecord.executeOps(BackStackRecord.java:439)
    at androidx.fragment.app.FragmentManagerImpl.executeOps(FragmentManagerImpl.java:2079)
    at androidx.fragment.app.FragmentManagerImpl.executeOpsTogether(FragmentManagerImpl.java:1869)
    at androidx.fragment.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManagerImpl.java:1824)
    at androidx.fragment.app.FragmentManagerImpl.execPendingActions(FragmentManagerImpl.java:1727)
    at androidx.fragment.app.FragmentManagerImpl.dispatchStateChange(FragmentManagerImpl.java:2663)
    at androidx.fragment.app.FragmentManagerImpl.dispatchActivityCreated(FragmentManagerImpl.java:2613)
    at androidx.fragment.app.FragmentController.dispatchActivityCreated(FragmentController.java:246)
    at androidx.fragment.app.FragmentActivity.onStart(FragmentActivity.java:542)
    at androidx.appcompat.app.AppCompatActivity.onStart(AppCompatActivity.java:210)
    at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1340)
    at android.app.Activity.performStart(Activity.java:7200)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2920)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3032) 
    at android.app.ActivityThread.-wrap11(Unknown Source:0) 
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1696) 
    at android.os.Handler.dispatchMessage(Handler.java:105) 
    at android.os.Looper.loop(Looper.java:164) 
    at android.app.ActivityThread.main(ActivityThread.java:6944) 
    at java.lang.reflect.Method.invoke(Native Method) 
    at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:327) 
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1374) 
n53p2ov0

n53p2ov01#

试试这个:

TextView textViewUsernameInfo = (TextView)view.findViewById(R.id.username);
textViewUsernameInfo.setText("Some text");

由于某种原因,你有两个充气机

public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    //LayoutInflater inflater also inflater, but you decalre another inflater
            LayoutInflater lf = getActivity().getLayoutInflater();
 //and i assume you try to get lf  LayoutInflater from Activity not from Fragment
            View view = lf.inflate(R.layout.fragment_home, container, false);
        ...
        }

设法除去

LayoutInflater lf = getActivity().getLayoutInflater();

并将您的观点更改为

assert inflater != null;//not required but try to add
    View view = inflater.inflate(R.layout.fragment_home, container, false);

根据文档:oncreateview(LayoutFlater、viewgroup、bundle)创建并返回与片段关联的视图层次结构,LayoutFlater对象可用于膨胀片段中的任何视图。关于碎片的文档
upd:我无法重现您的错误。
我分别为主活动和片段创建了简单的xml
main_activity.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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="match_parent">

    <androidx.fragment.app.FragmentContainerView
        android:id="@+id/fragmentContainerView"
        android:name="com.example.test.MainFragment"
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

main_fragment.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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/main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainFragment">

    <TextView
        android:id="@+id/username"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="#4B83E5"
        android:textSize="16sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

    </TextView>

    <Button
        android:id="@+id/btn_edit"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toStartOf="parent" />

    <Button
        android:id="@+id/btn_logout"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

创建了fragment类,并将mainactivity保留为默认值

public class MainActivity extends AppCompatActivity {

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

片段类

public class MainFragment extends Fragment {

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.main_fragment, container, false);

        Button button1 =  view.findViewById(R.id.btn_edit);
        button1.setOnClickListener(v -> Toast.makeText (requireContext (),"short1",Toast.LENGTH_SHORT).show ());

        Button button2 =  view.findViewById(R.id.btn_logout);
        button2.setOnClickListener(v -> Toast.makeText (requireContext (),"short2",Toast.LENGTH_SHORT).show ());

        TextView textViewUsernameInfo = view.findViewById(R.id.username);
        textViewUsernameInfo.setText("Some text");

        return view;
}}

它运行良好,不会对我抛出nullpointerexception。您可以尝试android开发人员提供的viewbinding或jakewharton提供的butterknife第三方库(它在2021年被弃用,不会有进一步的更新,因为viewbinding也有同样的功能-您仍然可以使用它。)

相关问题