片段文本字段上的NPE - 为什么?

Joc*_*hen -2 android android-layout android-fragments

我想更改我的TextView元素的文本,该文本在相应的QuoteFragment.class文件和相关layout.xml文件中定义.您可以在我的主要活动中看到该方法的代码:

private void forwardToQuoteFragment(Quote quote){
    quoteFragment = QuoteFragment.newInstance(quote);
    View view = quoteFragment.getView();
    TextView tv = (TextView) view.findViewById(R.id.quoteFragmentHeader);
    tv.setText("Quote (" + quote.getId() + "): " + quote.getQuote());
    android.support.v4.app.FragmentManager fm = getSupportFragmentManager();
    android.support.v4.app.FragmentTransaction ft = fm.beginTransaction();
    ft.replace(R.id.container, quoteFragment);
    ft.commit();
}
Run Code Online (Sandbox Code Playgroud)

我的调试器告诉我,视图变量为null,因此我得到了一个N​​PE.如果我在my中创建了view-property,它将没有区别,QuoteFragment.class你可以在下面看到:

public class QuoteFragment extends android.support.v4.app.Fragment {
    public static final String QUOTE_FRAGMENT_TAG = "QuoteFragment";
    public static final String QUOTE_ID = "quoteId";
    private View view;
    private long quoteId;

    public QuoteFragment(){
        // required
    }

    // factory to set arguments
    public static QuoteFragment newInstance(Quote quote) {
        QuoteFragment fragment = new QuoteFragment();
        Bundle args = new Bundle();
        args.putLong(QUOTE_ID, quote.getId()); 
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onAttach(Context context){
        super.onAttach(context);
        Log.i(QUOTE_FRAGMENT_TAG, "onAttach()");
    }

    @Override
    public void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        Log.i(QUOTE_FRAGMENT_TAG, "onCreate()");
        setHasOptionsMenu(true);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
        view = inflater.inflate(R.layout.fragment_quote, container, false);
        return view;
    }

    public void setQuoteId(long id){
        this.quoteId = id;
    }

    public long getQuoteId() {
        return quoteId;
    }

    public View getView(){
       return this.view;
    }
}
Run Code Online (Sandbox Code Playgroud)

解决这个问题的最佳方法是什么?我忽略了什么?

Ste*_*955 5

你无法得到View,因为View还没有被吸引到屏幕上: onCreateView()你的内部Fragment尚未被调用,但是你已经尝试访问TextView仅在onCreateView()被调用时才会被创建的内容.

您需要在OnCreateView()方法内设置文本,如此

@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
        View view = inflater.inflate(R.layout.fragment_quote, container, false);
        TextView tv = (TextView) view.findViewById(R.id.quoteFragmentHeader);
        tv.setText("Quote (" + quote.getId() + "): " + quote.getQuote());
        return view;
    }
Run Code Online (Sandbox Code Playgroud)