androidkotlinrecreate

How to call recreate from another class in Kotlin?


How do I call recreate() from another class in Kotlin? I am used to Java and did it like in the code shown below for some UI changes.

public class MainActivity extends AppCompatActivity {

    private static MainActivity instance;

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

        instance = this;
    }

    public static MainActivity getInstance() {
        return instance;
    }
}

public class SecondActivity extends AppCompatActivity {

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

    private void onClick(View view) {
        MainActivity.getInstance().recreate();
    }
}

Would be great if somebody knows how to achieve that in Kotlin, I am pretty much stuck with this. Beste regards, Markus


Solution

  • What @broot answered above is right for a 1:1 port but the practice is entirely wrong. What you are doing here is essentially creating a strong reference to an activity that isn't even shown to a user anymore.

    What you should do however is something like the following:-

    Inside Second Activity

     val intent = Intent(BROADCAST_RECREATE_MAIN)
     LocalBroadcastManager.getInstance(this@ SecondActivity).sendBroadcast(intent)
    

    Inside Main Activity

    private val localBroadcastReceiver by lazy {
      object : BroadcastReceiver() {
        override fun onReceive(context: Context?, intent: Intent?) {
          \\Recreate main here
        }
      }
    }
    

    Inside MainActivity's onCreate

    val intentFilter = IntentFilter()
    intentFilter.addAction(BROADCAST_RECREATE_MAIN)
    LocalBroadcastManager.getInstance(context)
            .registerReceiver(localBroadcastReceiver, localBroadcastIntentFilter)
    

    And inside onDestroy

    LocalBroadcastManager.getInstance(requireContext())
            .unregisterReceiver(localBroadcastReceiver)