Android在活动中覆盖多个类
即时答案是否,这在Java中是不可能的。我明白,这是一个noob问题,但我一直在编写这种方式一段时间,我总是觉得这是一个肮脏的方法,所以我想澄清我在做什么。说例如我有一个Activity扩展了Activity类,以便我可以使用onCreate等等......在该Activity中,我有一个SimpleCursorAdapter来填充ListView。Android在活动中覆盖多个类
String sql = "SELECT * FROM myTable";
Cursor data = database.rawQuery(sql, null);
String fields[] = {"field1", "field2", "field3"};
adapter = new CustomCursorAdapter(this, R.layout.custom_row, data, fields, new int[] { R.id.Field1, R.id.Field2, R.id.Field2 });
list.setAdapter(adapter);
,因为我创建一个名为CustomCursorAdapter全新的类,它扩展SimpleCursorAdapter这样我就可以使用诸如bindView,NewView的等上使用我的ListView控件对象按钮我命名这个CustomCursorAdapter。
public class CustomCursorAdapter extends SimpleCursorAdapter {
private Context myContext;
private myActivity parentActivity;
private Button delButton;
public CustomCursorAdapter(Context context, int layout, Cursor c, String[] from, int[] to) {
super(context, layout, c, from, to);
myContext = context;
parentActivity = (myActivity) myContext;
@Override
public void bindView(View view, Context context, Cursor cursor) {
int idColumn = cursor.getColumnIndex("_id");
final int getId = cursor.getInt(idColumn);
final double increment = 0.25;
UnitsConversions convert = new UnitsConversions();
int nameColumn = cursor.getColumnIndex("name");
String getName = cursor.getString(nameColumn);
TextView name = (TextView)view.findViewById(R.id.GrainName);
name.setText(getName);
delButton = (Button)view.findViewById(R.id.DeleteButton);
delButton.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View arg0) {
parentActivity.deleteItem(getId);
}
});
@Override
public View newView(Context context, Cursor cursor, final ViewGroup parent) {
View view = View.inflate(context, R.layout.list_item, null);
return view;
}
我攀登我的代码了很多在这里,所以如果我删除任何让这种非工作的代码我appologize只是作为一个例子使用,但非工作代码是不是我的问题的目的。我的问题是,除非使用SimpleCursorAdapter扩展活动本身,否则这是覆盖方法的唯一方法吗?它看起来不是什么大问题,但是当我有10个不同的活动时,所有的基本上都做同样的事情,但有不同的ListView和项目,我必须创建10个不同的CustomCursorAdapter,看起来很脏和多余。也许有一种方法只创建1个其他活动,然后传递我需要的项目?看起来只要使用SimpleCursorAdapter而不是创建一个自定义的并且覆盖Activity中我需要的方法就会更清晰。如果我没有正确地提出这个问题,请随时编辑。
是的,有一个更好的方法。你可以创建一个Activity的子类(并且如果你愿意,可以声明它是抽象的),它实现了你在10个类中共享代码的每个方法的重写版本。然后,对于您需要的每个实际活动,请扩展该活动的子类,并仅对每种方法进行所需的更改。如果一个方法在每个类中都不相同,但是将其大部分代码与其他活动共享,则可以调用general.method()方法,然后应用特定的更改。
好吧,你要说创建一个名为SubActivity(或其他)的新类并扩展Activity,然后在同一个SubActivity中声明另一个类并扩展SimpleCursorAdapter以及其他任何我可能需要的东西。然后扩展该SubActivity,我将从多个类中提供所有我的方法,我可以根据自己的判断来覆盖它们?我可以举个例子吗? – ryandlf
是的。对于一个非常简单的例子,设想SubActivity声明一个公共实例变量TextView,称为tv,并写入onCreate方法来在该TextView上调用setContentView。然后在每个真正的Activity中,在onCreate中,你只需调用super.onCreate()然后说tv.setText(“Some String”);您不必在每个子类中声明TextView并重复setContentView行,只需要更改Activity特定文本的行。 – Jems
有道理,但是没有办法基本调用该子类中的多个类,然后在实际活动中扩展子类,以便我可以覆盖所有在子类中声明的类?对于每个不同的活动,我都有不同的变量,所以对我来说尝试重用这部分代码没有多大意义。我宁愿只能重写我的活动中的方法,这样我就可以保留所有需要和整齐的东西,而不必拥有Activity1,CustomAdapter1,Activity2,CustomAdapter2等。 – ryandlf