How can I Reuse Methods for ListViews?

前端 未结 2 1261
南笙
南笙 2021-01-24 12:01

I have several methods in the ListAC ListActivity that I want to reuse and would like to put in separate classes (if possible??). I will be having dozens of ListView Activities

2条回答
  •  无人及你
    2021-01-24 12:38

    It seems like you're doing an extraordinary amount of extra work just to give a bunch of different query options for your Cursor.

    Why not have one ListActivity, with one CursorAdapter, and simply put the query in the Intent when you want to start the Activity?

    I'll work on a small code example and post it here in an edit, but you're really over-thinking this it seems. All you're trying to do is display the results of a query in a ListView. The only thing that is changing is the query. Reuse everything else.

    Code sample:

    public class QueryDisplay extends ListActivity {
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
    
            Bundle extras = getIntent().getExtras();
    
            if (extras != null)
                reloadQuery(extras.getString(QUERY_KEY));
    
        }
    
        private void reloadQuery(query) {
            // Build your Cursor here.
            setAdapter(new QueryAdapter(this, cursor));
        }
    
        private class QueryAdapter extends CursorAdapter {
    
            @Override
            public void bindView(View view, Context context, Cursor cursor) {
                // Set up your view here
            }
    
            @Override
            public View newView(Context context, Cursor cursor, ViewGroup parent) {
                // Create your new view here
                final View view = LayoutInflator.from(context).inflate(R.layout.your_query_list_item_layout, parent, false); 
                return view;
            }
        }
    }
    

    That's literally all the code you should need (plus the fill-ins for your custom Views and building the Cursor). Whenever you need to change the query, you just need to call reloadQuery(String query) and you're set.

提交回复
热议问题