Java / Android Edittext.gettext()。toString不起作用

时间:2014-07-09 13:55:01

标签: java android android-edittext

我有一个edittext和button。第一次我的edittext.settext是1.现在我尝试检查edidtext.gettext()。toString.equels是否有些值做了一些思考

    public class StradaMenuResultReadMore extends Fragment {

public static ImageView buy_btn;

private EditText price_counter;

int av;
private String counterString;

@SuppressLint("UseValueOf")
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {

    View rootView = inflater.inflate(R.layout.strada_menu_result_loadmore,
            container, false);

    buy_btn = (ImageView) rootView.findViewById(R.id.strada_buy_btn);
    price_counter = (EditText) rootView
            .findViewById(R.id.strada_price_counter);

    price_counter.setText("1");
    counterString = price_counter.getText().toString();
    av = Integer.parseInt(counterString);

    buy_btn.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {

            if (counterString.equals("1")) {

                Toast.makeText(getActivity(), "one", Toast.LENGTH_SHORT)
                        .show();

            } else

            {

                Toast.makeText(getActivity(), "two", Toast.LENGTH_SHORT)
                        .show();

            }

        }
    });

    return rootView;

}

目前我的代码工作正常,但如果我更改edittext输入值然后单击按钮,那么我的代码无法正常工作 我怎么能解决我的问题?

3 个答案:

答案 0 :(得分:2)

onClick中,您需要从EditText中获取值,因为counterString仍包含旧值" 1":

buy_btn.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View v) {
        counterString = price_counter.getText().toString();
        ....

答案 1 :(得分:2)

counterString = price_counter.getText().toString();

将此行放在onClick

答案 2 :(得分:0)

由于在oncreateView()onCreate(Bundle)之间调用onActivityCreated(Bundle),因此只调用一次,而您用来比较的字符串始终保持为1.因此问题。 改变这个:

buy_btn.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View v) {

        counterString = price_counter.getText().toString();

        if (counterString.equals("1")) {
            Toast.makeText(getActivity(), "one", Toast.LENGTH_SHORT)
                    .show();
        } else{
            Toast.makeText(getActivity(), "two", Toast.LENGTH_SHORT)
                    .show();
        }
    }
});