OnClick in Fragment does not change my TextView [duplicated]

1
public class MainMenu extends Fragment implements OnClickListener{

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

        View v = inflater.inflate(R.layout.fragment_main_menu, container, false);

        Button b = (Button) v.findViewById(R.id.btnme1);
        b.setOnClickListener(this);
        return v;
    }

    @Override
    public void onClick(View vi) {
        int id = vi.getId();
        switch (id) {
            case R.id.btnme1:
                TextView ncant1 = (TextView) vi.findViewById(R.id.txtcant1);
                ncant1.setText("85");
                break;
        }
    }
}

I want to place the number 85 in a textview [R.id.txtcant1] by pressing the button

    
asked by Edwin S Toala P 21.04.2017 в 10:42
source

1 answer

0

Your code is wrong in the OnClick method, since you are looking for the reference of the TextView with a wrong view ( vi ) which is the reference of Button .

If you are going to use a widget outside of the local context, I recommend declaring it global as in this case:

public class MainMenu extends Fragment implements OnClickListener{

        private TextView ncant1;

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

            View v = inflater.inflate(R.layout.fragment_main_menu, container, false);
            ncant1 = (TextView) v.findViewById(R.id.txtcant1);
            Button b = (Button) v.findViewById(R.id.btnme1);
            b.setOnClickListener(this);
            return v;
        }

        @Override
        public void onClick(View vi) {
            int id = vi.getId();
            switch (id) {
                case R.id.btnme1:
                    ncant1.setText("85");
                    break;
            }
        }
    }
    
answered by 21.04.2017 в 10:47