放置片段后无法直接找到片段的元素

问题描述:

G'Day, 问题很简单,在AppCompatActivity的onResume()方法中,我替换了片段,并且希望在此之后直接更改其子元素的某些值。放置片段后无法直接找到片段的元素

例如:

public void onResume(){ 
    Fragment FR = new Fragment(); 
    FragmentTransaction FT = getSupportFragmentManager().beginTransaction(); 
    FT.replace(containerID, FR); //The Container is a FrameLayout 
    FT.commit(); 

    findViewById(R.id.someTextView).setId(SomeID); //This throws a NullPointerException 

} 

确切的说:java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.View.setId(int)' on a null object reference

任何想法如何找到我查看?

您应该使用commitNow来代替提交。 在提交指令后,片段实际上并没有就位。 commitNow将同步执行提交,你应该能够在后面找到视图。

由于getView()只能在onCreateView()之后工作,所以不能像上面那样使用它..