Why does this java code work? the compiler does not complain about closing

My DialogFragment contains an invisible OK button and a list of items available for clicks. When any of the items in the ListView is clicked, I set the button visibility to VISIBLE.

This is done through the anonymous OnItemClickListener. The code below works, but I do not understand why. Since Java does not support closure, I expect the compiler to complain that the button is not final.

Isn't this a typical case of closure? Why doesn't the code below generate a compiler error?

thanks

public class AlternativeRoomsDialog extends DialogFragment {

private Button okButton;

static AlternativeRoomsDialog newInstance(String name) {
    AlternativeRoomsDialog f = new AlternativeRoomsDialog();
    return f;
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_alternative_rooms, container);
    getDialog().setTitle("Change Room");

    ListView lv = (ListView) view.findViewById(R.id.alternative_rooms_list);
    final adapter = /*some initialization*/;
    lv.setAdapter(adapter);
    lv.setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> arg0, View linlay, int position, long id) {
            okButton.setVisibility(View.VISIBLE);
            ListView lv = (ListView) linlay.getParent();
            int total = lv.getChildCount();
            for (int i=0; i< total; i++){
                lv.getChildAt(i).setBackgroundColor(Color.BLUE);
            }
            linlay.setBackgroundColor(Color.GREEN);
        }
    }); 

    // setup OK button
    okButton = (Button) view.findViewById(R.id.btn_ok);
    okButton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            Toast.makeText(AlternativeRoomsDialog.this.getActivity(), "ok button clicked", Toast.LENGTH_SHORT).show();
        }
    });
    return view;
}

}

+4
source share
2 answers

, , , , , . -, , : , .

+5

final, . final, , , . , . , , .

, 2 , , . , final.

, . , final.

+2

Source: https://habr.com/ru/post/1525447/


All Articles