带有 RadioButtons 的 TextWatcher 实现

TextWatcher implementation with RadioButtons

请参阅附件图片和代码片段以帮助解释。 从所附的图片中,我希望用户输入 costquantity 和 select Include Tax 排除税费 并且在没有按 Button 的情况下会自动生成新的费用,但我无法执行此操作。有人请帮忙。谢谢

在此处查看图片

在实施建议的更改并尝试在成本字段中输入内容后,我遇到了如下所示的错误。请提供更多反馈。谢谢

错误图片

import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;

import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.util.Locale;


public class Calculator extends Fragment {

private static EditText itemText, editCost, editQuantity, calCost, rTax;
private static RadioGroup rGroup;
private static RadioButton rb;
View gView;

private double bTotal = 0, aTotal = 0, trueCost = 0, taxValue = 16.5, cost = 0, newCost = 0;
private int quantity = 1;

DecimalFormatSymbols symbols = DecimalFormatSymbols.getInstance(Locale.US);
DecimalFormat decimalFormat = new DecimalFormat("###,###.##", symbols);

CalculatorListener activityCommander;


public interface CalculatorListener {
    void addtoCart(String itemName, int qty, double beforeTax, double afterTax, double bTotal, double aTotal);
}

@Override
public void onAttach(Context context) {
    super.onAttach(context);
    try {
        activityCommander = (CalculatorListener) context;
    } catch (ClassCastException e) {
        throw new ClassCastException(context.toString());
    }
}


public Calculator() {
    // Required empty public constructor
}


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    gView = inflater.inflate(R.layout.fragment_calculator, container, false);


    editCost = (EditText) gView.findViewById(R.id.editcost);
    itemText = (EditText) gView.findViewById(R.id.itemText);
    editQuantity = (EditText) gView.findViewById(R.id.editquantity);
    calCost = (EditText) gView.findViewById(R.id.calcost);
    rTax = (EditText) gView.findViewById(R.id.rtax);
    rGroup = (RadioGroup) gView.findViewById(R.id.rgroup);

    final ImageButton FieldButton = (ImageButton) gView.findViewById(R.id.FieldButton);
    final ImageButton TaxButton = (ImageButton) gView.findViewById(R.id.TaxButton);
    final ImageButton CalButton = (ImageButton) gView.findViewById(R.id.CalButton);

    rTax.setEnabled(false);
    calCost.setEnabled(false);

    rGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {

            rb = (RadioButton)gView.findViewById(checkedId);
        }
    });

    editCost.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

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

        }

        @Override
        public void afterTextChanged(Editable s) {

            try{
                update();
            }catch (NumberFormatException e)
            {
                e.printStackTrace();
            }
        }
    });

    editQuantity.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

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

        }

        @Override
        public void afterTextChanged(Editable s) {

            try{
                update();
            }catch (NumberFormatException e)
            {
                e.printStackTrace();
            }
        }
    });


    FieldButton.setOnClickListener(
            new View.OnClickListener() {
                public void onClick(View v) {
                    clearfield();
                }

            }
    );
    TaxButton.setOnClickListener(
            new View.OnClickListener() {
                public void onClick(View v) {
                    adjtax();
                }

            }
    );
    CalButton.setOnClickListener(
            new View.OnClickListener() {
                public void onClick(View v) {
                    //toCart();
                }

            }
    );


    return gView;

}

public void clearfield() {
    editCost.setText("");
    editCost.setBackgroundResource(R.drawable.edittxt);
    editQuantity.setText("");
    editQuantity.setBackgroundResource(R.drawable.edittxt);
    calCost.setText("");
    calCost.setBackgroundResource(R.drawable.edittxt);
    itemText.setText("");
    itemText.setBackgroundResource(R.drawable.edittxt);
    rGroup.clearCheck();
}

public void adjtax() {
    editCost.setBackgroundResource(R.drawable.edittxt);
    editQuantity.setBackgroundResource(R.drawable.edittxt);
    calCost.setBackgroundResource(R.drawable.edittxt);
    itemText.setBackgroundResource(R.drawable.edittxt);
    rTax.setEnabled(true);
    rTax.setText("");
    rTax.setBackgroundResource(R.drawable.edittxtfocus);
    rTax.setOnFocusChangeListener(new View.OnFocusChangeListener() {
        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            if (hasFocus) {
                rTax.setEnabled(true);

            } else {
                rTax.setEnabled(false);
                v.setBackgroundResource(R.drawable.edittxt);
            }
        }
    });

}


public void update(){


            if (rTax.getText().toString().isEmpty()) {
               taxValue = 16.5;
            } else if (!rTax.getText().toString().isEmpty()) {
                taxValue = Double.parseDouble(rTax.getText().toString());
            }


            //CHECKS THE TAX VALUE IF IT NEEDS TO BE CONVERTED
            if (taxValue > 1) {
                taxValue = taxValue / 100;
            } else {
                taxValue = taxValue * 1;
            }

            //CUSTOM VALIDATOR FOR QUANTITY FIELD
            if (editQuantity.getText().toString().isEmpty()) {
                quantity = 1;
            } else if (!editQuantity.getText().toString().isEmpty()) {
                quantity = Integer.parseInt(editQuantity.getText().toString());
            }


            if(rb.getText() == "Include Tax"){
                newCost = (((cost = Double.parseDouble(editCost.getText().toString())) * taxValue) + cost) * quantity;
                calCost.setText(decimalFormat.format(newCost).toString());
            }
            else if(rb.getText() == "Exclude Tax"){
                newCost = ((cost = Double.parseDouble(editCost.getText().toString())) * quantity);
                calCost.setText(decimalFormat.format(newCost).toString());
            }

            trueCost = cost * quantity;
            bTotal = trueCost;
            aTotal = newCost;
}


}

rgroup.setOnCheckedChangeListener 移出 update() 方法并移入 onCreateView()。您不必在每次更新文本时都设置监听器。

如果输入了有效值并且复选框已被select编辑,则文本输入后调用的更新方法可能只更新税值。

更新另一个建议

我会像您一样通过比较文本来查找单选按钮,将来您可能想要更改资源文件中的文本或应用其他语言环境,此代码将停止工作。

if(rb.getText() == "Include Tax")

我建议与 id 本身进行比较:

if (checkedId == R.id.radio1 )

另一个建议:

考虑更改您的变量名,使其以小写字符开头。以大写字母开头使它看起来像 class 名称或常量,并使代码更难阅读。

private EditText itemText;
private EditText editCost;
private EditText editQuantity;
private EditText calcost;
private EdtiText rTax;

您还可以移除所有(部分)您拥有的焦点更改侦听器,并在android 可绘制资源中设置这些属性。看看here

2016 年 9 月 9 日更新 22:22

稍微好一点,但是正如您发现的那样,如果 rb 从未被初始化,则对更新的调用可能会抛出一个空指针。您应该在更新方法中检查空 rb 并通知用户 select 一个选项。您还可以将 rb 分配给 onCreateView 中开始的两个值中的任何一个,因此它永远不会为 null。

在无线电组回调中设置 rb 后,您可能还应该添加对 update() 的调用。这将使屏幕在他们选择一个选项后立即更新。