【问题标题】:How to stop toast & alertDialog losing focus on my EditText filter如何停止 toast 和 alertDialog 失去对我的 EditText 过滤器的关注
【发布时间】:2013-03-17 13:21:21
【问题描述】:

更新:

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

第二次更新 - 我添加了整个 ShoppingList.java 类。

第一次更新 - 在 2 个人喜欢这个问题但没有答案后,我为这个问题开放了一个赏金。

问题:

我遇到过类似的问题,一旦我开始一个新的意图然后返回到原始页面,我就无法重新过滤我的 ListView。这通过使用覆盖 onResume() 方法并从另一个过滤器方法中调用我的过滤器代码来解决。

我遇到的最新问题是是否应该在我的应用页面上使用 dialogBu​​ilder 或 toast 消息,然后过滤器文本再次被空白,即输入到我的过滤器 EditText 的任何文本都被我的过滤器忽略。

以下是一些突出问题的屏幕截图:

加载项的ListView:

在过滤器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);
}

}

来自数据库处理程序类的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() 无济于事。

【问题讨论】:

  • 向我们展示更多代码.....
  • @DhavalSodhaParmar 我已经添加了整个 ShoppingList 类代码。
  • getChanges() 方法长什么样子?
  • @Luksprog 非常感谢您的回答。我添加了 getChanges()。它基本上用作我的数据库处理程序类中的一种方法,用于从我的数据库中返回与过滤器术语匹配的任何结果。

标签: java android filter


【解决方案1】:

更新过滤器后,尝试在适配器上调用 notifyDataSetChanged()。这应该通知ListView 它也需要刷新其数据。

【讨论】:

  • 感谢您的回答。我相信 notifyDataSetChanged();现在已经贬值了。我在发布问题之前尝试了这个,遗憾的是它不起作用。
  • 嗯,这很奇怪。但它并没有被弃用。至少它在文档中没有这样说,也没有在 Eclipse 中显示已弃用的警告。
【解决方案2】:

据我所知,您正在多次运行getCons.open();,但中间没有关闭它。我不知道 open() 方法是忽略多次调用还是多次调用会导致错误,但您可能想尝试是否可以通过将 getCons.open(); 直接移动到 getCons = new DBHandlerShop(this, null, null); 下方来修复它。

【讨论】:

  • 感谢您的回复。我已经尝试将我的数据库 .open() 方法移动到我的 DBHandler 对象下,但遗憾的是它仍然没有在 alertdialog 和 toast 消息之后过滤
【解决方案3】:

我发现解决此问题的一种简单方法是在编辑完成后通过启动一个新的意图对象来简单地调用该类。这仍然使整个过程的操作顺畅快捷,当然也允许我在编辑后进行过滤。所以暂时伙计们,这就是我打算这样做的方式。

【讨论】:

    【解决方案4】:

    我了解您的情况。每次用户成功编辑项目时,您都在为您的列表设置一个新适配器!在您的情况下,在 onCreate 方法中添加到您的 EditText 的 TextWatcher 正在使用第一个适配器(在 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 用于过滤列表的适配器相同。它应该工作,试一试,让我知道会发生什么。

    【讨论】:

      【解决方案5】:

      我认为你应该使用

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

      【讨论】:

        【解决方案6】:

        您可以尝试以下更改..

        在显示您的 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()));
        
                }
        
            });
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-12-08
          • 1970-01-01
          • 2022-01-23
          • 1970-01-01
          • 2019-04-02
          • 1970-01-01
          相关资源
          最近更新 更多