Search code examples
androidandroid-studioif-statementvisibilityonitemclicklistener

Changing textview visibility in android studio


I want to click to hide or unhide a textview using android studio. If it is visible, one click will make it invisible. If it is invisible, one click will make it visible.

Currently, only half of the function is working. While I can click to make a textview invisible, clicking it again does not make it visible again.

Here is my code

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        toDoList = new ArrayList<>();
        arrayAdapter = new ArrayAdapter<>(this, R.layout.list_view_layout, toDoList);
        listView = findViewById(R.id.id_list_view);

        listView.setAdapter(arrayAdapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener(){
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long id){
                TextView textView = (TextView) view;

                if (textView.getVisibility() == View.VISIBLE) {
                    textView.setVisibility(View.INVISIBLE);
                }
                else {
                    textView.setVisibility(View.VISIBLE);
                }

            }
        });

When trying to debug it, I find that the else statement is never ran, even when the if condition returns false. Am I missing something?


Solution

  • get extViw from your onItemClick is wrong.

     TextView textView = (TextView) view;
    

    it should be

    TextView textView = (TextView) view.findViewById(R.id.yourTextView);
    

    and if you want to invisible view and clickable, use setAlpha(0); and setAlpha(1);