侦听器活动片段

时间:2019-05-30 09:36:07

标签: java android

我有BlankFragment,并在MainAcitivity中添加到了FrameLayout。 我的问题是: 我在MainActivity中单击一个按钮,然后我想在BlackFragment中进行更改,但是它不起作用。 我已经尝试过了:

MainActivity

private Button button;
private BlankFragment blankFragment;
private IListener listener;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    button = findViewById(R.id.button);
    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            setListenter(listener);
        }
    });

    BlankFragment fragment = new BlankFragment();
    changeFragment(fragment);
}

private void changeFragment(Fragment fragment) {
    FragmentManager fragmentManager = getSupportFragmentManager();
    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
    fragmentTransaction.replace(R.id.frame, fragment).commit();
}

private void setListenter(IListener listener) {
    this.listener = listener;
    listener.onClickListener("Android is handsome");
}

空白军团

public class BlankFragment extends Fragment implements IListener {

public BlankFragment() {
    // Required empty public constructor
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View view = inflater.inflate(R.layout.fragment_blank, container, false);

    return view;
}

@Override
public void onClickListener(String value) {
    Toast.makeText(getContext(), value, Toast.LENGTH_SHORT).show();
}

}

0 个答案:

没有答案