一级目录
Main页面代码
package com.example.day12;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
public class MainActivity extends AppCompatActivity {
private Button btn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
EventBus.getDefault().register(this);
}
@Subscribe
public void getString(String s){
Toast.makeText(this, s, Toast.LENGTH_SHORT).show();
}
private void initView() {
btn = (Button) findViewById(R.id.btn);
}
@Override
public void onDestroy() {
super.onDestroy();
EventBus.getDefault().unregister(this);
}
}
Main布局
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:orientation="vertical"
android:layout_height="match_parent"
tools:context=".MainActivity">
<fragment
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/frg"
android:name="com.example.day12.BlankFragment"></fragment>
</LinearLayout>
fragment代码
package com.example.day12;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import androidx.fragment.app.Fragment;
import org.greenrobot.eventbus.EventBus;
public class BlankFragment extends Fragment {
private Button btn;
private View inflate;
public BlankFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
inflate = inflater.inflate(R.layout.fragment_blank, container, false);
initView();
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String s = "这不错";
EventBus.getDefault().post(s);
}
});
return inflate;
}
private void initView() {
btn = (Button) inflate.findViewById(R.id.btn);
}
}
fragment布局
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".BlankFragment">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/btn"
android:text="发送"/>
</LinearLayout>