GridView 与 ListActivity 而不是 ListView

Posted

技术标签:

【中文标题】GridView 与 ListActivity 而不是 ListView【英文标题】:GridView with ListActivity instead of ListView 【发布时间】:2013-09-19 22:11:36 【问题描述】:

我有一个应用程序,它从数据库中提取数据并通过 ListActivity 和 Cursor Loader 将其放入列表视图中。

代码如下:

public class PersonRecord extends ListActivity implements
    LoaderManager.LoaderCallbacks<Cursor> 

private Uri addUri;
private TextView nameOfPerson, creditOfPerson;
private SimpleCursorAdapter adapter;
private String nameOfThePersonString;

// Used for menu deleting of a record
private static final int DELETE_ID = Menu.FIRST + 1;

// List  for Listview
private ListView lv;

private static final String AUTHORITY = "com.fthatnoise.borrow.me.contentprovider";

// ---------------------------------------------------

@Override
protected void onCreate(Bundle savedInstanceState) 
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.person_record);
    this.getListView().setDividerHeight(2);

    init(); // Initialize parameters and GUI

    // Gets the name of the person that was sent from the Borrower List
    // class
    Bundle extras = getIntent().getExtras();

    // Toast.makeText(this, nameOfThePersonString, Toast.LENGTH_SHORT)
    // .show();

    if (extras != null) 
        addUri = extras
                .getParcelable(BorrowMeContentProvider.CONTENT_ITEM_TYPE);

        // Try-catch when the records are finished, this prevents the program
        // from crashing (Pulling 0 from database)
        try
            fillData(addUri);
         catch (Exception e)
        
            Toast.makeText(this, "There are no more records for this person", Toast.LENGTH_SHORT)
            .show();
        
    

    // Registers a content menu to the ListView 
    registerForContextMenu(getListView());




// ---------------------------------------------------
// Adding content menu to allow for the deletion of stored entries under peoples names

@Override public boolean onContextItemSelected(MenuItem item) 

    switch (item.getItemId()) 
    case (DELETE_ID):

    // Gets the content for the assigned content menu - in this case the listview
            AdapterContextMenuInfo info = (AdapterContextMenuInfo) item
                     .getMenuInfo();

            // Find the entry for the item currently clicked on
            Uri uri = Uri.parse(BorrowMeContentProvider.CONTENT_URI +
                     "/" + info.id);
            getContentResolver().delete(uri, null, null);

            // Reload the list with new data based on the name sent over 
            // from the person credit screen

            /*
             * Removed filldata for now, seems to work without it even though it crashes
             * When removed it works fine but fails to refresh person record
             * causes an error if all records are removed and person still shows up in
             * the record screen.
             */
            try 


             catch (Exception e)

                Toast.makeText(this, "There are no more records for this person", Toast.LENGTH_SHORT)
                .show();
            


            return true;
    

    return super.onContextItemSelected(item);



// ---------------------------------------------------
// Create Content Menu

@Override
public void onCreateContextMenu(ContextMenu menu, View v,
        ContextMenuInfo menuInfo) 
    // TODO Auto-generated method stub
    super.onCreateContextMenu(menu, v, menuInfo);

    //showDialog(DIALOG_SAB_PRIORITY_ID); 
    menu.add(0, DELETE_ID, 0, "Delete Record"); 




// ---------------------------------------------------

private void init() 

    nameOfPerson = (TextView) findViewById(R.id.person_name);
    creditOfPerson = (TextView) findViewById(R.id.person_credit);


// ---------------------------------------------------
// Loads record that was sent based on the ID
private void fillData(Uri uri) 

    // Loads up the name of the person
    String[] projection =  BorrowMeTable.COLUMN_NAME ; // Pulls only the
                                                            // name so far

    Cursor databaseCursor = getContentResolver().query(uri, projection,
            null, null, null);

    if (databaseCursor != null) 

        databaseCursor.moveToFirst();

        nameOfThePersonString = databaseCursor.getString(databaseCursor
                .getColumnIndexOrThrow(BorrowMeTable.COLUMN_NAME));

        nameOfPerson.setText(nameOfThePersonString);

    

    // Makes a raw query to the database in order to pull credit score for
    // person being looked at.

    ContentProviderClient client = getContentResolver()
            .acquireContentProviderClient(AUTHORITY);
    SQLiteDatabase dbHandle = ((BorrowMeContentProvider) client
            .getLocalContentProvider()).getDbHandle();
    Cursor cursor = dbHandle.rawQuery("SELECT sum("
            + BorrowMeTable.COLUMN_CREDIT_SCORE
            + ") AS creditcardtotal FROM " + BorrowMeTable.DATABASE_TABLE
            + " WHERE " + BorrowMeTable.COLUMN_NAME + "= \""
            + nameOfThePersonString + "\"", null);
    cursor.moveToFirst();
    int total = cursor.getInt(0);
    cursor.close();
    cursor.deactivate();
    client.release(); // End of Credit Pull

    // This is the formula to calc credit score.
    // Everyone starts with 7, then it adds based on borrowed and returned items.
    int defaultScore = 7;
    int cnt = 0;

    cnt = defaultScore + total;


    // This is the start of the credit evaluation system. 
    // Based on what the final numbers are, this will assign them a credit score.

    if (cnt >= 5 && cnt <= 6)
        creditOfPerson.setText(cnt + " - Average");
        creditOfPerson.setTypeface(null, Typeface.NORMAL);

    else if (cnt >= 7 && cnt <= 8)
        creditOfPerson.setText(cnt + " - Good");
        creditOfPerson.setTextColor(Color.MAGENTA);
        creditOfPerson.setTypeface(null, Typeface.NORMAL);
    else if (cnt >= 2 && cnt <= 4)
        creditOfPerson.setText(cnt + " - Bad");
        creditOfPerson.setTextColor(Color.RED);
        creditOfPerson.setTypeface(null, Typeface.NORMAL);
    else if (cnt >= 9)
        creditOfPerson.setText(cnt + " - Fantastic");
        creditOfPerson.setTextColor(Color.GREEN);
        creditOfPerson.setTypeface(null, Typeface.NORMAL);
    else if (cnt <1)
        // Stops showing the score if it drops below 1
        creditOfPerson.setText("1 - Terrible");
        creditOfPerson.setTextColor(Color.RED);
        creditOfPerson.setTypeface(null, Typeface.BOLD);

    else if (cnt >= 10)
        // Stops showing the score if it raises above 10
        creditOfPerson.setText("10 - Wicked Awesome");
        creditOfPerson.setTextColor(Color.GREEN);
        creditOfPerson.setTypeface(null, Typeface.BOLD);

    

    // End of credit score pull

    // Loads the data for the rows of all items this person has borrowed
    String[] from = new String[]  BorrowMeTable.COLUMN_ITEM,
            BorrowMeTable.COLUMN_DATE, BorrowMeTable.COLUMN_BORROW_FLAG, BorrowMeTable.COLUMN_RETURN_DATE, BorrowMeTable.COLUMN_RETURN_FLAG, BorrowMeTable.COLUMN_IMAGE;

    int[] to = new int[]  R.id.items_for_the_person_record,
            R.id.borrowed_on_the_date, R.id.returned_on_the_date, R.id.returned_on_the_day, R.id.returned_cond, R.id.pic_of_item;

    //getLoaderManager().initLoader(0, null, this); // This is where it was originally
    adapter = new SimpleCursorAdapter(this, R.layout.rows_people_records,
            null, from, to, 0);

    // The viewbinder that allows the adapter to display BLOB images
    adapter.setViewBinder(new MyViewBinder());

    setListAdapter(adapter);


    // Here is where I attempt to load the custom view binder to load the blob data

    getLoaderManager().initLoader(0, null, this); // I have commented out above and placed it here


// ---------------------------------------------------

@Override
public Loader<Cursor> onCreateLoader(int arg0, Bundle arg1) 

    String mSelection = BorrowMeTable.COLUMN_NAME + "=?"; // SQL request
    String[] selectionArgs =  nameOfThePersonString ; // The actual
                                                        // argument

    String[] projection =  BorrowMeTable.COLUMN_ID,
            BorrowMeTable.COLUMN_ITEM, BorrowMeTable.COLUMN_DATE,
            BorrowMeTable.COLUMN_BORROW_FLAG, BorrowMeTable.COLUMN_RETURN_DATE, BorrowMeTable.COLUMN_RETURN_FLAG, BorrowMeTable.COLUMN_IMAGE;


    CursorLoader cursorLoader = new CursorLoader(this,
            BorrowMeContentProvider.CONTENT_URI, projection, mSelection,
            selectionArgs, null);

    return cursorLoader;


// ---------------------------------------------------

@Override
public void onLoadFinished(Loader<Cursor> arg0, Cursor arg1) 
    adapter.swapCursor(arg1);



// ---------------------------------------------------

@Override
public void onLoaderReset(Loader<Cursor> arg0) 
    adapter.swapCursor(null);




我想知道这是否可以很容易地重复使用相同的代码,如果我必须重做一堆。我看过教程,但我没有看到任何东西可以完全回答我的问题。

【问题讨论】:

用gridview替换listview就可以了 【参考方案1】:

我建议你用Activity来替换然后稍微改变一下

【讨论】:

以上是关于GridView 与 ListActivity 而不是 ListView的主要内容,如果未能解决你的问题,请参考以下文章

ListActivity与Adapter以及SQLite的使用

onListItemClick 不会(总是)被 ListActivity 调用

GridView 与嵌套类的属性绑定

ListFragment vs ListActivity - 使用哪一个?

Scrollerview与listview或者gridview发生冲突

高级控件安卓5——ListActivity