簡體   English   中英

如何停止toast&alertDialog失去對我的EditText過濾器的關注

[英]How to stop toast & alertDialog losing focus on my EditText filter

更新:

最新更新 - 添加了getChanges()方法。

第二次更新 - 我添加了整個ShoppingList.java類。

第一次更新 - 在2個人喜歡這個問題但沒有答案之后,我已經為這個問題開了一筆賞金。

題:

我有類似的問題,一旦我開始一個新的意圖,然后返回到原始頁面,我無法重新過濾我的ListView。 這是通過使用overResume()方法並從另一個過濾器方法中調用我的過濾器代碼來解決的。

我有的最新問題是應該在我的應用頁面上使用dialogBu​​ilder或toast消息,然后再次將過濾器文本消隱,即我的過濾器忽略輸入到我的過濾器EditText中的任何文本。

以下是一些突出顯示問題的屏幕截圖:

加載列表的項目:

在此輸入圖像描述

搜索詞輸入到過濾器EditText中並正確過濾:

在此輸入圖像描述

第一個項目“A”被編輯為“AB”。 Toast消息確認了該動作:

在此輸入圖像描述

這就是問題,對話框構建器(編輯項目的方式)和Toast消息是完整的,在EditText中輸入一個新的過濾器術語,過濾器不再過濾:

在此輸入圖像描述

這是我的過濾器代碼:

package com.example.flybaseapp;



    public class ShoppingList extends ListActivity implements OnClickListener {

Button AddItem;
Button showShop;
ListView showItems;
SimpleCursorAdapter cursorAdapter;
Long itemId;
TextView totalPrice;
String itemDescription;
int itemAmount;
int itemPrice;
EditText itemNameEdit;
DBHandlerShop getCons;
Dialog e1;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.shoppinglistlayout);

    AddItem = (Button) findViewById(R.id.btnAddItem);
    showShop = (Button) findViewById(R.id.btnSearchShops);

    showItems = (ListView) findViewById(android.R.id.list);

    totalPrice = (TextView) findViewById(R.id.totalListPrice);

    AddItem.setOnClickListener(this);
    showShop.setOnClickListener(this);

    setList();

    int setPrice = updateTotal();
    totalPrice.setText(Integer.toString(setPrice));

    itemNameEdit = (EditText) findViewById(R.id.inputItemName);

    showItems.setTextFilterEnabled(true);

    itemNameEdit.addTextChangedListener(new TextWatcher() {

        @Override
        public void afterTextChanged(Editable s) {

        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before,
                int count) {

            cursorAdapter.getFilter().filter(s.toString());
            showItems.refreshDrawableState();

        }

    });

    getCons = new DBHandlerShop(this, null, null);
    getCons.open();
    cursorAdapter.setFilterQueryProvider(new FilterQueryProvider() {

        public Cursor runQuery(CharSequence constraint) {

            return getCons.getChanges((constraint.toString()));

        }

    });

    showItems.setAdapter(cursorAdapter);

}

@Override
public void onClick(View clickedAdd) {

    switch (clickedAdd.getId()) {

    case (R.id.btnAddItem):

        show();

        break;

    case (R.id.btnSearchShops):

        Intent checkGPS = new Intent("com.example.flybaseapp.CheckGPS");
        startActivity(checkGPS);

        break;

    }

}

@Override
protected void onListItemClick(ListView l, View v, int position, long idd) {
    super.onListItemClick(l, v, position, idd);

    itemId = idd;

    final CharSequence[] items = { "Edit Item", "Delete Item" };

    Builder alertDialogBuilder = new AlertDialog.Builder(ShoppingList.this);

    alertDialogBuilder.setTitle("Item Options:");

    alertDialogBuilder.setItems(items,
            new DialogInterface.OnClickListener() {

                public void onClick(DialogInterface dialog, int item) {

                    if (items[item].equals("Edit Item")) {

                        AlertDialog.Builder builder = new AlertDialog.Builder(
                                ShoppingList.this);

                        builder.setTitle("Edit Item");

                        DBHandlerShop setEdit = new DBHandlerShop(
                                ShoppingList.this, null, null);

                        setEdit.open();
                        String itemName = setEdit.getItem(itemId);
                        int itemAmount = setEdit.getItemQuan(itemId);
                        int itemPrice = setEdit.getItemCost(itemId);
                        setEdit.close();

                        LinearLayout layout = new LinearLayout(
                                ShoppingList.this);
                        layout.setOrientation(LinearLayout.VERTICAL);

                        final EditText titleBox = new EditText(
                                ShoppingList.this);
                        titleBox.setText(itemName);
                        titleBox.setHint("Item Name:");
                        layout.addView(titleBox);

                        final EditText quantityBox = new EditText(
                                ShoppingList.this);
                        quantityBox.setText(Integer.toString(itemAmount));
                        quantityBox.setHint("Item Quantity");
                        layout.addView(quantityBox);

                        final EditText priceBox = new EditText(
                                ShoppingList.this);
                        priceBox.setText(Integer.toString(itemPrice));
                        priceBox.setHint("Item Price.");
                        layout.addView(priceBox);

                        builder.setView(layout);

                        builder.setPositiveButton("Ok",
                                new DialogInterface.OnClickListener() {
                                    public void onClick(
                                            DialogInterface dialog,
                                            int whichButton) {

                                        Editable valueItem = titleBox
                                                .getText();
                                        Editable valueAmount = quantityBox
                                                .getText();
                                        Editable valuePrice = priceBox
                                                .getText();

                                        String itemDescription = valueItem
                                                .toString();
                                        String s = valueAmount.toString();
                                        int itemAmount = Integer
                                                .parseInt(s);
                                        String a = valuePrice.toString();
                                        int itemPrice = Integer.parseInt(a);

                                        try {
                                            DBHandlerShop update = new DBHandlerShop(
                                                    ShoppingList.this,
                                                    null, null);

                                            int totalCombined = itemAmount
                                                    * itemPrice;

                                            update.open();
                                            update.updateItem(itemId,
                                                    itemDescription,
                                                    itemAmount, itemPrice);
                                            update.close();

                                            int setPrice = updateTotal();
                                            totalPrice.setText(Integer
                                                    .toString(setPrice));

                                        } catch (Exception e) {

                                            Toast.makeText(
                                                    getApplicationContext(),
                                                    "Items not updated.",
                                                    Toast.LENGTH_SHORT)
                                                    .show();

                                        } finally {

                                            Toast.makeText(
                                                    getApplicationContext(),
                                                    "Items updated.",
                                                    Toast.LENGTH_SHORT)
                                                    .show();

                                            setList();

                                        }

                                    }

                                });

                        builder.setNegativeButton("Cancel",
                                new DialogInterface.OnClickListener() {
                                    public void onClick(
                                            DialogInterface dialog,
                                            int whichButton) {

                                    }
                                });

                        builder.show();

                    }

                    else if (items[item].equals("Delete Item")) {
                        try {

                            DBHandlerShop delete = new DBHandlerShop(
                                    ShoppingList.this, null, null);

                            delete.open();
                            delete.deleteItem(itemId);
                            delete.close();

                            DBHandlerShop findPrice = new DBHandlerShop(
                                    ShoppingList.this, null, null);

                            findPrice.open();
                            int returnedCost = findPrice
                                    .getItemCost(itemId);
                            findPrice.close();

                            int cost = updateTotal();

                            int newTotal = cost - returnedCost;
                            totalPrice.setText(Integer.toString(newTotal));
                        }

                        catch (Exception e) {

                            Toast.makeText(getApplicationContext(),
                                    "Item failed to be deleted.",
                                    Toast.LENGTH_SHORT).show();
                        }

                        finally {

                            Toast.makeText(getApplicationContext(),
                                    "Item deleted from the list.",
                                    Toast.LENGTH_SHORT).show();

                            setList();
                        }

                    }

                }

            });

    alertDialogBuilder.show();

}

@SuppressWarnings("deprecation")
private void setList() {

    DBHandlerShop DBShop = new DBHandlerShop(this, null, null);

    DBHandlerShop searchItems = new DBHandlerShop(this, null, null);

    searchItems.open();

    Cursor cursor = searchItems.getItems();

    startManagingCursor(cursor);

    searchItems.close();

    String[] from = new String[] { DBShop.KEY_ITEMSHOP, DBShop.KEY_ITEMNUM,
            DBShop.KEY_ITEMPRICE };
    int[] to = new int[] { R.id.txtSetItem, R.id.txtSetAmount,
            R.id.txtSetPrice };

    cursorAdapter = new SimpleCursorAdapter(this, R.layout.setshoppinglist,
            cursor, from, to);
    showItems.setAdapter(cursorAdapter);

}

private int updateTotal() {

    DBHandlerShop total = new DBHandlerShop(this, null, null);

    int totalPrice = 0;
    total.open();
    Cursor totalPrices = total.getTotals();
    total.close();

    if (totalPrices != null) {

        startManagingCursor(totalPrices);
        if (totalPrices.moveToFirst()) {

            do {
                int cost = totalPrices.getInt(3);
                int amount = totalPrices.getInt(2);

                int totalCost = cost * amount;
                totalPrice += totalCost;

            } while (totalPrices.moveToNext());

            return totalPrice;
        }

    }

    else {

        return totalPrice;

    }

    return 0;

}

private void show() {

    AlertDialog.Builder builder = new AlertDialog.Builder(ShoppingList.this);

    builder.setTitle("Enter Item Details:");

    LinearLayout layout = new LinearLayout(this);
    layout.setOrientation(LinearLayout.VERTICAL);

    final EditText titleBox = new EditText(this);

    titleBox.setHint("Item Name:");
    layout.addView(titleBox);

    final EditText quantityBox = new EditText(this);

    quantityBox.setHint("Item Quantity");
    layout.addView(quantityBox);

    final EditText priceBox = new EditText(this);

    priceBox.setHint("Item Price.");
    layout.addView(priceBox);

    builder.setView(layout);

    builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int whichButton) {
            try {

                Editable valueItem = titleBox.getText();
                Editable valueAmount = quantityBox.getText();
                Editable valuePrice = priceBox.getText();

                itemDescription = valueItem.toString();
                String s = valueAmount.toString();
                itemAmount = Integer.parseInt(s);
                String a = valuePrice.toString();
                itemPrice = Integer.parseInt(a);

                DBHandlerShop addItem = new DBHandlerShop(
                        ShoppingList.this, null, null);
                addItem.open();
                addItem.insertItems(itemDescription, itemAmount, itemPrice);
                addItem.close();

            } catch (Exception e) {

                Toast.makeText(getApplicationContext(),
                        "Item failed to be added", Toast.LENGTH_SHORT)
                        .show();

            } finally {

                Toast.makeText(getApplicationContext(),
                        "Item added to your list", Toast.LENGTH_SHORT)
                        .show();

                int cost = updateTotal();
                totalPrice.setText(Integer.toString(cost));

                setList();

            }

        }

    });

    builder.setNegativeButton("Cancel",
            new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {

                }
            });

    builder.show();

}

@Override
protected void onResume() {
    super.onResume();

    setList();

    showItems.setTextFilterEnabled(true);

    itemNameEdit.addTextChangedListener(new TextWatcher() {

        @Override
        public void afterTextChanged(Editable s) {

        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before,
                int count) {

            cursorAdapter.getFilter().filter(s.toString());
            showItems.refreshDrawableState();

        }

    });

    getCons = new DBHandlerShop(this, null, null);
    getCons.open();
    cursorAdapter.setFilterQueryProvider(new FilterQueryProvider() {

        public Cursor runQuery(CharSequence constraint) {

            return getCons.getChanges((constraint.toString()));

        }

    });

    showItems.setAdapter(cursorAdapter);
}

}

來自Database Handler類的getChanges():

public Cursor getChanges(String constraintPassed) {

        String [] columns = new String[]{KEY_ROWSHOPID, KEY_ITEMSHOP, KEY_ITEMNUM, KEY_ITEMPRICE};
        Cursor c = null;
         if(constraintPassed.equals(""))
         {
             c = ourDatabase.query(DATABASE_TABLESHOP, columns, null, null, null, null, null);

         }

         else
         {
            c = ourDatabase.query(DATABASE_TABLESHOP, columns, KEY_ITEMSHOP + " LIKE'" + constraintPassed + "%'", null, null, null, KEY_ITEMSHOP + " ASC", null);
         }

        if( c != null)
            {
                c.moveToFirst();

            }
        return c;
    }

編輯完成后,是否需要實施生命周期方法? 如果是這樣,有人可能會向我推進正確的方向,因為我嘗試過onResume()和onRestart()無濟於事。

更新過濾器后,嘗試在適配器上調用notifyDataSetChanged() 這應該通知ListView它還需要刷新其數據。

據我所見,你正在運行getCons.open(); 多次沒有關閉它們之間。 我不知道open()方法是否忽略多個調用或多次調用會導致錯誤,但您可能想嘗試是否可以通過移動getCons.open();來修復它getCons.open(); 直接在getCons = new DBHandlerShop(this, null, null);下面getCons = new DBHandlerShop(this, null, null);

我發現,解決這個問題的一個簡單方法是通過在編輯完成后啟動一個新的intent對象來簡單地調用該類。 這仍然使流程的整體操作流暢而快速,當然也允許我在編輯后進行過濾。 因此,對於暫時​​的人來說,這就是我將如何使用它。

我想你應該用

android:hapticFeedbackEnabled="true"
android:imeOptions="actionNext"
android:nextFocusUp="@id/editeText1" 
android:nextFocusLeft="@id/edittextText"
android:includeFontPadding="true"

我看到你的情況正在發生什么。 每次用戶成功編輯項目時,您都要為列表設置新的適配器! 而在你的情況下,也TextWatcher加入到onCreate方法您的EditText是使用第一個適配器(在onTextChanged法)在onCreate方法也創造中,第一次創建活動!

有幾種方法可以解決這個問題。 一種方法是改變你實施活動的整個方式(我個人不會這樣做)。

另一種方法是簡單地改變setList方法,該方法在onCreate方法中第一次被調用,並且每次用戶成功編輯項目時。 這是我將要詳細解釋的解決方案,因為它既快速又簡單,而且不耗費時間:

  • 如果列表沒有適配器,則創建一個。
  • 如果列表已有適配器,則只需更改適配器的光標並刷新列表即可。

所以你的setList方法應如下所示:

@SuppressWarnings("deprecation")
private void setList() {

    DBHandlerShop DBShop = new DBHandlerShop(this, null, null);

    DBHandlerShop searchItems = new DBHandlerShop(this, null, null);

    searchItems.open();

    Cursor cursor = searchItems.getItems();

    startManagingCursor(cursor);

    searchItems.close();

    String[] from = new String [] { DBShop.KEY_ITEMSHOP , DBShop.KEY_ITEMNUM, DBShop.KEY_ITEMPRICE };
    int[] to = new int[] { R.id.txtSetItem, R.id.txtSetAmount, R.id.txtSetPrice };

    // Check the cursor adapter is previously created
    if ( cursorAdapter == null ) {
        // There is no previous cursors, create a new one
        cursorAdapter = new SimpleCursorAdapter(this, R.layout.setshoppinglist, cursor, from, to);
        showItems.setAdapter(cursorAdapter);
    }
    else {
        // There is a previous adapter
        // Stop managing its cursor
        stopManagingCursor ( cursorAdapter.getCursor() );
        // Assign the new cursor to the current adapter
        // The old cursor will be closed
        cursorAdapter.changeCursor ( cursor );
        // No need to refresh the list, it will be automatically refreshed after the adapter's cursor is changed
    }

}

以這種方式,列表的適配器與TextWatcher用於過濾列表的適配器相同。 它應該工作,嘗試一下,讓我知道會發生什么。

您可以嘗試以下更改..

顯示您的Toast項目更新/刪除消息后調用此方法

cursorAdapter.notifyDataSetChanged();

在你的setList()方法中添加以下內容..

cursorAdapter.registerDataSetObserver(new DataSetObserver() {
@Override
public void onChanged() {
    super.onChanged();
    setList();
}});

並在代碼下移動到setList()

itemNameEdit.addTextChangedListener(new TextWatcher() {

        @Override
        public void afterTextChanged(Editable s) {

        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                                      int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before,
                                  int count) {

            cursorAdapter.getFilter().filter(s.toString());
            showItems.refreshDrawableState();

        }

    });

    getCons = new DBHandlerShop(this, null, null);
    getCons.open();
    cursorAdapter.setFilterQueryProvider(new FilterQueryProvider() {

        public Cursor runQuery(CharSequence constraint) {

            return getCons.getChanges((constraint.toString()));

        }

    });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM