简体   繁体   English

在setOnCheckedChangeListener方法内执行Toast消息

[英]Execute a Toast message inside a setOnCheckedChangeListener method

I have an array of togglebuttons. 我有一组切换按钮。 There is a 1-to-1 ratio of toggleButtons with number of rows in a cursor. 游标中的行数与切换按钮的比例为1:1。 I assign an setId() to each toggleButton in the array with returned data from the cursor. 我使用从游标返回的数据为数组中的每个toggleButton分配一个setId()。

My update is always updating 1 row up in the cursor and I'm trying to troubleshoot this issue using some toast messages. 我的更新总是在光标中向上更新1行,我正尝试使用一些吐司消息来解决此问题。 The problem is that I can't get the toast message to display. 问题是我无法显示吐司消息。 I know the method is listener is firing because my sql update is running, it's just that it's the wrong row. 我知道该方法正在触发监听器,因为我的sql更新正在运行,只是错误的行。 Here is my code. 这是我的代码。

toggleButton[i].setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener()
        {
            ContentValues values = new ContentValues(); //Create the new content values object for data input
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
            {
                if(isChecked)
                {
                    Toast.makeText(Cart.this.getBaseContext(), "hello", Toast.LENGTH_SHORT).show();
                    toggleButton[buttonView.getId()].setTextOn("Yes"); //Set the text when the button changes state to on
                    values.put(Contract.ItemsTable.COLUMN_ONE, 1); //Update the record on the 'status' column to true
                    String[] itemId = {String.valueOf(buttonView.getId())}; //
                    db.update(Contract.ItemsTable.TABLE_NAME, values, SmartCartContract.ItemsTable.COLUMN_ITEM_ID + " LIKE ?", itemId); //Update the DB record
                } else
                {
                    Toast.makeText(Cart.this.getBaseContext(), "hello", Toast.LENGTH_SHORT).show();
                    toggleButton[buttonView.getId()].setTextOff("No"); //Set the text when the button changes state to off
                    values.put(SmartCartContract.ItemsTable.COLUMN_TWO, 0); //Update the record on the 'status' column to false
                    String[] itemId = {String.valueOf(buttonView.getId())}; //
                    db.update(Contract.ItemsTable.TABLE_NAME, values, Contract.ItemsTable.COLUMN_ITEM_ID + " LIKE ?", itemId); //Update the DB record
                }
            }
        });

Cart.this.getBaseContext() is my last attempt of the options I've seen to use. Cart.this.getBaseContext()是我最后一次尝试使用的选项。 Is this what I'm doing wrong? 这是我做错了吗?

I'm building those buttons dynamically with: 我正在使用以下方法动态构建这些按钮:

toggleButton[i] = new ToggleButton(this); //Create new ToggleButton control for this row    
toggleButton[i].setGravity(Gravity.CENTER); //Align the text in the middle 
toggleButton[i].setId(cursor.getInt(cursor.getColumnIndex("itemId"))); 
if (cursor.getInt(cursor.getColumnIndex("itemInCart")) == 1) //Check if marked 'in Cart'

Not sure what the problem with the database is, but here is a minimal example of some ToggleButtons with a working Toast. 不确定数据库的问题是什么,但这是一些Toast正常工作的ToggleButtons的最小示例。

public class CartActivity extends AppCompatActivity {

    private CompoundButton.OnCheckedChangeListener listener = new CompoundButton.OnCheckedChangeListener() {

        ContentValues cv;

        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            cv = new ContentValues();
            String key;
            int val;

            if (isChecked) {
                key = "col1";
                val = 1;
            } else {
                key = "col2";
                val = 0;
            }

            cv.put(key, val);
            String[] itemId = {String.valueOf(buttonView.getId())};
            Toast.makeText(CartActivity.this,
                    String.format("[%d] %s {%s}", buttonView.getId(), isChecked, cv),
                    Toast.LENGTH_SHORT).show();
        }
    };

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

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

        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);

        ToggleButton[] buttons = new ToggleButton[3];
        for (int i = 0; i < buttons.length; i++) {
            ToggleButton toggle = new ToggleButton(this);

            toggle.setLayoutParams(lp);
            toggle.setId(i);
            toggle.setGravity(Gravity.CENTER);            
            toggle.setTextOn(String.format("On [%d]", i));
            toggle.setTextOff(String.format("Off [%d]", i));
            toggle.setChecked(false);
            toggle.setOnCheckedChangeListener(listener);

            buttons[i] = toggle;
            view.addView(toggle);
        }

        setContentView(view);
    }
}

Not sure what kind of object Cart is. 不确定购物车是哪种物品。 But you could extend the Application class and save off the application context, which you could then use in your toasts. 但是,您可以扩展Application类并保存应用程序上下文,然后在吐司中使用它们。

import android.app.Application;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;

public class BaseApplication extends Application
{
    protected static Context context;
    protected static PackageInfo packageInfo;
    protected static BaseApplication baseApplication;

    @Override
    public void onCreate()
    {
        try
            {

                baseApplication = this;

                context = getApplicationContext();

                PackageManager manager = context.getPackageManager();
                String packageName = context.getPackageName();

                packageInfo = manager.getPackageInfo(packageName, 0);
            }
        catch (Exception e)
            {
                // ignore
            }
    }

    public static Context getContext()
    {
        return context;
    }

    public static PackageInfo getPackageInfo()
    {
        return packageInfo;
    }

    public static BaseApplication getApplication(){
        return baseApplication;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM