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

时间:2016-12-31 21:53:36

标签: 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();
}

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

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

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

1 个答案:

答案 0 :(得分: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;
    }