当前位置: 首页 > 知识库问答 >
问题:

尝试调用虚拟方法“void android”。小装置。文本视图。空对象引用2上的setText(java.lang.CharSequence)'

强化
2023-03-14

我是android新手。最近,我尝试通过活动在两个片段之间进行通信。基本上在这里,我将按钮的位置从一个片段发送到另一个由textview组成的片段。但我得到了一个错误:尝试调用虚拟方法void-android。小装置。文本视图。setText(java.lang.CharSequence)'

我尝试了值id是否被传递。我在Log上打印了该值并成功打印。我已经搜索了很多这个错误并尝试了替代方案;使用方法,rootView而不是getView(),但似乎没有什么效果。我可能犯了一个愚蠢的错误,但我真的要完成这个。

主要活动。Java语言

      package com.example.benchtobasecamp.doublelistfragment;
      import android.support.v4.app.FragmentActivity;
      import android.os.Bundle;
      import android.support.v4.app.FragmentTransaction;
      import android.view.Menu;
      import android.view.MenuItem;

      public class MainActivity extends FragmentActivity implements BlankFragment.OnItemClickListener{

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

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

 @Override
public void method1(int position)
 {
 ResultFragment rf=new ResultFragment();
 Bundle bundle = new Bundle();
 bundle.putString("value", String.valueOf(position));

 rf.setArguments(bundle);


FragmentTransaction fragmentManager=getSupportFragmentManager().beginTransaction();
fragmentManager.replace(R.id.frame_container,rf);
fragmentManager.addToBackStack(null);
fragmentManager.commit();

 }
}

空白片段。jav公司

    package com.example.benchtobasecamp.doublelistfragment;
    import android.content.Context;
    import android.support.v4.app.ListFragment;
    import android.os.Bundle;
    import android.support.v4.app.Fragment;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.AdapterView;
    import android.widget.ArrayAdapter;



    public class BlankFragment extends ListFragment {
OnItemClickListener listener;

public interface OnItemClickListener
{
    public void method1(int position);
}
@Override
public void onActivityCreated(Bundle savedInstanceState)
{
    super.onActivityCreated(savedInstanceState);
    ArrayAdapter<CharSequence> adapter=ArrayAdapter.createFromResource(getActivity(), R.array.Buttons, android.R.layout.simple_list_item_1);
    setListAdapter(adapter);
    getListView().setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            switch (position)
            {
                case 0:listener.method1(0);
                    break;
                case 1:listener.method1(1);
                    break;
                case 2:listener.method1(2);
                    break;
            }

        }
    });

}


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View view= inflater.inflate(R.layout.fragment_blank, container, false);
    return view;
}


@Override
public void onAttach(Context context) {
    super.onAttach(context);
    try{

        listener = (OnItemClickListener) context;
    }
    catch(ClassCastException e) {
        throw new ClassCastException(context.toString() + " must implement MyListFragment.OnItemSelectedListener");
    }
}
}

结果片段

    package com.example.benchtobasecamp.doublelistfragment;
    import android.os.Bundle;
    import android.support.v4.app.Fragment;
    import android.util.Log;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.TextView;


    public class ResultFragment extends Fragment {

    TextView textView;

public ResultFragment() {
    // Required empty public constructor
}



@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    Bundle bundle = this.getArguments();
    String Value = bundle.getString("value");

    //Log.d("You pressed Button",String.valueOf(position+1));

    textView= (TextView) getActivity().findViewById(R.id.textView);
    textView.setText(Value);




}

  }

logcat显示此错误:

     01-20 11:33:24.084    1923-1923/com.example.benchtobasecamp.doublelistfragment E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.benchtobasecamp.doublelistfragment, PID: 1923
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
        at com.example.benchtobasecamp.doublelistfragment.ResultFragment.onCreate(ResultFragment.java:34)
        at android.support.v4.app.Fragment.performCreate(Fragment.java:1942)
        at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1040)
        at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1259)
        at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:738)
        at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1624)
        at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:517)
        at android.os.Handler.handleCallback(Handler.java:739)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:148)
        at android.app.ActivityThread.main(ActivityThread.java:5417)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

共有3个答案

江阳羽
2023-03-14

之后再叫你的逻辑

setContentView(id);
何骞尧
2023-03-14

在这里:

textView= (TextView) getActivity().findViewById(R.id.textView);

getActivity()返回容器Activity上下文,如果我们使用getActivity()调用findViewById方法,意味着从Activity布局访问视图,而不是从Fragment访问视图。

要从布局中访问视图,请使用与空白片段中的丁相同的方式创建视图。

覆盖BlankFraank片段中的onCreateView方法:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View view= inflater.inflate(
         R.layout.<pass layout id which contains TextView with textView  id>, 
        container, false);
    TextView textView= (TextView) view.findViewById(R.id.textView);
     Bundle bundle = this.getArguments();
     String Value = bundle.getString("value");
     textView.setText(Value);
    return view;
}
刘海
2023-03-14

它给你带来了NullPointerException,因为

textView= (TextView) getActivity().findViewById(R.id.textView);

您试图在活动上下文中找到视图,但没有Id的视图。text视图与其关联。

因此,您必须通过重写来膨胀视图,从而在片段范围内找到视图

以下是获取视图的代码

public class ResultFragment extends Fragment{
     @Override
     public View onCreateView ( LayoutInflater inflater , ViewGroup container, Bundle savedInstanceState){
        super.onCreateView(inflater,container,savedInstanceState);

        View view=inflater.inflate(R.layout.yourlayout,container,false);
        TextView textView=view.findViewById(R.id.textView);
        textView.setText(content);
        return view;
   }
 类似资料: