android - 从activity调用片段方法返回null对象引用

时间:2015-12-08 09:24:24

标签: android fragment

从activity调用fragment方法返回null对象引用,为什么?

片段:

private RelativeLayout waitingForTerminal;
private RelativeLayout blackContent;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.waiting_for_terminal, container, false);
    setViews(rootView);
    return rootView;
}
private void setViews(View view){
    waitingForTerminal = (RelativeLayout) view.findViewById(R.id.waiting_for_terminal);
    blackContent = (RelativeLayout) view.findViewById(R.id.blank_content);
}

public void hideWaitingForTerminal(){
    waitingForTerminal.setVisibility(View.INVISIBLE);
    blackContent.setVisibility(View.VISIBLE);
}

MainActivity:

public void run() {
    WaitingForTerminalFragment fragment = new WaitingForTerminalFragment();
    fragment.hideWaitingForTerminal();

    showToast(terminalConnectionEvent.getTerminalInformation().getSerialNumber());
}

3 个答案:

答案 0 :(得分:1)

以下是我如何解决它。

片段:

public void hideWaitingForTerminal(View view) {
    RelativeLayout relativeLayout = (RelativeLayout) view.findViewById(R.id.waiting_for_terminal);
    relativeLayout.setVisibility(RelativeLayout.GONE);
}

MainActivity:

private void changeWaitingForTerminalLayout(WaitingForTerminalFragment waitingForTerminalFragment){
    waitingForTerminalFragment.hideWaitingForTerminal(this.findViewById(R.id.terminal).getRootView());
}

答案 1 :(得分:0)

尝试给予参考:

WaitingForTerminalFragment fragment = (WaitingForTerminalFragment)getFragmentManager().findFragmentById(R.id.youfragmentid);
fragment.<specific_function_name>();   

答案 2 :(得分:0)

仅通过创建该片段的对象,不会调用初始化您的视图的该片段类的oncreateview。这就是片段方法内的视图返回null的原因。

以这种方式从Activity调用片段方法,对我有用

YourFragment yourFragment = (YourFragment)getSupportFragmentManager().getFragments().get(0);
yourFragment .yourmethod();  

这里0是您的片段位置。