尝试不重复自己(android/java) [英] trying not to repeat myself (android/java)
问题描述
怎么了? 我是开发的初学者,在任何地方我读到不要重复自己",所以我真的很想重复自己. 我在应用程序的每个活动中复制并粘贴了一段代码,我怀疑可能有一种不重复的代码-可能创建一个类并调用其方法-但我不知道如何实现它. 下面的代码就是我在说的:我在导航抽屉中使用的东西,它在我的应用程序的每个活动的主类中:
whats up? i'm a beginner to development and everywhere i read 'do not repeat yourself', so i really mind about repeating myself. there is a piece of code that i copied and pasted in every single activity of my app, and i suspect there might be a way of not repeating it - maybe creating a class and calling its methods - but i don't know how to implement it. the code below is what i'm talking about: something i use in my navigation drawer and it's inside the main class of each activity of my app:
@Override
public void onItemClick(AdapterView<?> parent, View arg1, int position,
long arg3) {
if (position == 0) {
Toast.makeText(this, "categories baby", Toast.LENGTH_SHORT).show();
} else if (position == 1){
final Context context = this;
Intent getUserData = getIntent();
String userEmail = getUserData.getStringExtra("user_email");
Intent intent = new Intent(context, NewAdActivity.class);
intent.putExtra("userEmail", userEmail);
startActivity(intent);
} else if (position == 2){
final Context context = this;
Intent getUserData = getIntent();
String userEmail = getUserData.getStringExtra("user_email");
Intent intent = new Intent(context, AdListActivity.class);
intent.putExtra("userEmail", userEmail);
startActivity(intent);
} else {
Session session = Session.getActiveSession();
session.closeAndClearTokenInformation();
Intent intent = new Intent(context, MainActivity.class);
startActivity(intent);
}
}
您能给我一些关于如何重用它而不是复制/粘贴的提示吗? 谢谢!
can you give me some hints on how to reuse this rather than copy/paste? thanks!
推荐答案
您可以创建一个扩展Activity
并实现您的代码的新类,然后使您的所有活动扩展该类.
You can create an new class that extends Activity
and implements your code and then make all your activities extend that class.
该代码似乎是AdapterView.OnItemClickListener
的实现,因此您可以创建以下内容:
That code seems to be the implementation of the AdapterView.OnItemClickListener
, so you can create something like:
public abstract class MyActivityWithListener extends Activity
implements AdapterView.OnItemClickListener {
@Override
public void onItemClick(AdapterView<?> parent, View arg1, int position, long arg3) {
....
}
}
然后您的主要活动可能是这样的:
And then your main activity could be something like:
public class MainActivity extends MyActivityWithListener {
...
}
这篇关于尝试不重复自己(android/java)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!