android-如何使现有片段实现一个活动的监听器?

时间:2018-03-17 20:46:00

标签: android android-fragments android-activity interface listener

我要从片段中走出来 - >活动。在活动中我创建了一个界面,当用户点击一个按钮时,我将一个字符串传递给我创建的接口对象并调用finish()。在片段中,我实现了该接口,并希望获得该字符串。但是在活动中我得到一个崩溃说听众是空的。

public class SampleActivity  extends AppCompatActivity
{
    private Button button;
    private MatchActivity.OnMatchCompleteListener onMatchCompleteListener;
    public interface OnMatchCompleteListener
    {
        public void matchComplete(String matchID);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        button = (Button) findViewById(R.id.someButton); 
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                onMatchCompleteListener.matchComplete("finished");
                finish();
            }
        });
    }
}

片段

public class SampleFragment extends Fragment implements SampleActivity.OnMatchCompleteListener{

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

    @Override
    public void matchComplete(String matchID) {
        Log.d("TEST",matchID);
    }
}

1 个答案:

答案 0 :(得分:1)

如果您的片段位于R.layout.activity_main且片段ID为R.id.fragment,请使用此字段:

onMatchCompleteListener =
 ((SampleFragment)getFragmentManager().findFragmentById(R.id.fragment))

否则使用此解决方案:

SampleFragment fragment = new SampleFragment();
onMatchCompleteListener = fragment;
getFragmentManager().beginTransaction().add(R.layout.activity_main, fragment, "TAG_SIMPLE").commit();