0

How would I refactor only certain areas of code in Android Studios that are commonly called? For instance:

Dog dog = new Dog();
dog.bark()

Dog dog = new Dog();
dog.bark()

Dog dog = new Dog();
dog.bark()

Dog dog = new Dog();
dog.bark()

I want to be able to change the 2nd copy of the dog object into dog1 and use dog1.bark instead of dog.bark(). I also want to rename the 3rd dog object to dog3 and call dog3.bark instead. Is there any shortcut that allows me to rename only certain portions of code in android studios?

Shashanth
  • 4,995
  • 7
  • 41
  • 51
questions
  • 473
  • 6
  • 19
  • 2
    I wonder why don't you create and make the dogs barking in a loop. Anyway, I would consider just to use replace within selection with "Preserve Case" accessible via Ctrl-R - instead real refactoring. – no id Feb 20 '19 at 04:30
  • https://jeroenmols.com/blog/2018/04/26/androidstudioshortcuts2/ might help – Akash Pal Feb 20 '19 at 05:12
  • You can use Multiple cursors at every text that matches using `Alt + J` Refer https://stackoverflow.com/questions/53796045/multiple-cursors-in-android-studio-automatically-at-every-text-that-matches#answer-53806874 – Firoz Memon Feb 20 '19 at 05:13
  • @FirozMemon he dont want to replace all the instances. – Pratik Butani Feb 20 '19 at 05:17
  • @Ilia Nedoluzhko, good idea! Wasn't really thinking about that at the time... However, this is still a good question because I actually want to know a shortcut for my case. – questions Feb 20 '19 at 20:38

2 Answers2

1

Just select area that you want and then with command ctrl+R open window replace and checked In Selection then type what you want to replace and enjoy from that.

Like this image

Masoud Mokhtari
  • 2,390
  • 1
  • 17
  • 45
0

The easiest way is:

Dog dog = new Dog();
dog.bark();

Dog dog1 = new Dog();
dog1.bark();

Dog dog2 = new Dog();
dog2.bark();

Dog dog3 = new Dog();
dog3.bark();

Manually as I have done, you can also do same, because there is no way to create variables as you want in sequence.

Right now you can copy/paste my code but if you want to do for more objects you can do manually because it will be better.

Pratik Butani
  • 60,504
  • 58
  • 273
  • 437
  • I was looking for a way to do that with a shortcut on android studios by renaming all of my duplicate variables. – questions Feb 20 '19 at 20:38