Javaインタフェースコールバック値

3984 ワード

--------------------------MainActivity------------------------
public class MainActivity extends AppCompatActivity {

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

        Button btn = findViewById(R.id.btn1);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(MainActivity.this,Main2Activity.class));
            }
        });
        Main2Activity.setOnDisplayRefreshListener(new Main2Activity.refreshOnDisplayListener() {
            @Override
            public void returnRefresh(String s) {
                Toast.makeText(MainActivity.this, s+"", Toast.LENGTH_SHORT).show();
            }
        });

    }

}

-------------------Main2Activity-------------------
public class Main2Activity extends AppCompatActivity {

    private static refreshOnDisplayListener listener;

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

        Button btn = findViewById(R.id.btn2);

        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
                listener.returnRefresh("   ");
            }
        });
    }

    public interface refreshOnDisplayListener {
        public void returnRefresh(String s);
    }

    public static void setOnDisplayRefreshListener(refreshOnDisplayListener myListener) {
        listener = myListener;
    }

}