使用RadioButtons实现TextWatcher

时间:2016-09-09 18:55:00

标签: java android android-fragments textwatcher android-textwatcher

请参阅随附的图片和代码段以帮助解释。 从附图中我希望用户输入费用数量并选择包含税排除税并且在没有按Button的情况下自动生成新成本,但无效,我无法执行此操作。有人请帮忙。感谢

见图像 enter image description here

在实施建议的更改并尝试在费用字段中输入输入后,我遇到了下面看到的错误。请提供其他反馈。感谢

错误图片 enter image description here

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;
}


}

1 个答案:

答案 0 :(得分:0)

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

如果输入了有效值并且选中了复选框,则在文本输入后调用的更新方法可能只是更新税值。

使用其他建议进行更新

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

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

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

if (checkedId == R.id.radio1 )

另一个建议:

考虑使用小写字符将变量名称更改为lead。带大写字母的前导使其看起来像是类名或常量,使代码更难以阅读。

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

您还可以删除 all (某些)焦点更改侦听器,并在android drawable资源中设置这些属性。看看here

更新9/9/2016 22:22

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

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