how to make a button visible / invisible in an if else loop

Viewed 130

I'm building an android app (similar to Discord for those who know it). All channels are displayed on the homepage, each channel has attributes (name, author, mine; what I have to do is display a DETAILS button only next to my channels (and therefore if the mine attribute is equal to "t"). The problem is that if I write b.setVisibility (View.VISIBLE) or b.setVisibility (View.GONE) the whole line disappears and therefore also the channel name.

Main Activity:

 for(int i = 0; i < canaliJSON.length(); i ++){ 
                JSONObject obj = (JSONObject) canaliJSON.get(i); 
                String title = obj.getString("ctitle");
                String property = obj.getString("mine");

                final Button buttonHv = (Button) findViewById(R.id.hv);
                View b = findViewById(R.id.hv);
                        if (property.equals("t")) {
                            Log.d(TAG,"myChannel");
                            b.setVisibility(View.VISIBLE);
                        }
                        else {
                            Log.d(TAG,"not myChannel");
                            buttonHv.setVisibility(View.GONE);
                        }

                canali.add(new Canale(title, property + " "+ buttonHv));
            }

MainActivity.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:gravity="center_vertical"
    android:orientation="horizontal"
    android:minHeight="?android:attr/listPreferredItemHeight"
    android:padding="16dp">

    <!--Nome canale nella homepage-->

    <TextView
        android:id="@+id/canale_name"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginLeft="30dp"
        android:layout_weight="1"
        android:textColor="@color/black" />


    <Button
        android:id="@+id/hv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="right"
        android:visibility="invisible"/>
        android:text="HV" />


</LinearLayout>
1 Answers

Why you have declared the button 2 times with 'View' and 'Button'?
Just use 'Button'

Remove this line from your code:
View b = findViewById(R.id.hv);

And use:
buttonHv.setVisibility(View.VISIBLE)

'View' will get all the elements including 'Button' or any other tags you have used. Just use 'Button'

Related