以下是我的活动。我的应用程序中有超过50个食谱,其中活动文件具有相同的内容,但xml布局文件名除外。如何将所有这些文件合并为一个?
我有listview和listitems。每当按下一个listitem时,它将通过intent重定向到相应的活动。那么,如果我将所有这些活动合并为一个,会受到影响吗?
public class recipe1 extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.recipe1);
// To make text scrollable
TextView txt = (TextView) findViewById(R.id.ImageViewText);
txt.setVerticalScrollBarEnabled(true);
txt.setMovementMethod(ScrollingMovementMethod.getInstance());
TextView title = (TextView) findViewById(R.id.Heading);
title.setTextColor(Color.BLUE);
}
}
答案 0 :(得分:1)
在努力/价值比方面,你能做的最好的事情就是只保留一个活动(我们称之为RecipeActivity
)来显示配方,但继续复制xml布局。您可以在启动配方活动时将配方ID传递给意图,在配方活动中,您可以从意图中提取配方ID并根据该设置内容。大概是这样的:
// in MainActivity
public final String RECIPE_ID = "RECIPE_ID";
...
Intent recipeIntent = new Intent(this, RecipeActivity.class);
recipeIntent.putExtra(RECIPE_ID, recipeId);//where recipeId is an index of recipe user has clicked on
startActivity(recipeIntent);
// in RecipeActivity
protected void onCreate(Bundle savedInstanceState) {
...
int recipeId = getIntent().getIntExtra(MainActivity.RECIPE_ID, 0);
switch (recipeId) {
case 1: setContentView(R.layout.recipe1); break;
case 2: setContentView(R.layout.recipe2); break;
...
default: throw new IllegalStateException("Wrong recipe id");
}
...
}
如果您还想避免xml布局重复,可以将公共部分提取到一个xml布局中,并根据配方ID以编程方式设置其余内容。我的意思是这样的:
// in RecipeActivity
protected void onCreate(Bundle savedInstanceState) {
...
ImageView recipeImage = (ImageView) findViewById(R.id.recipe_image);
TextView recipeDescription = (TextView) findViewById(R.id.recipe_description);
switch (recipeId) {
case 1: {
recipeImage.setBackgroundResource(R.drawable.recipe_1_image);
recipeDescription.setText(R.string.recipe_1_description);
break;
}
...
}
}