Jan Soldát Jan Soldát - 5 months ago 9
Java Question

Android: On Click gradual visibility change

I have got a little problem which is for me impossible to solve. I've got lots of TableRows called Radek_X and they are set to be

android:visibility="gone".
And I need that if you for the first time, click on button(there is only one button for that process) it will change Radek_1 to
android:visibility="visible"
if you click on the button for the second time it will change Radek_2 from gone to visible, while Radek_1 is still visible. And so on for all others TableRows. I'm really desperate. I will be very grateful for any help! Have a nice day!

Here is my java file

package jansoldat.formular100;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.TableRow;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

Button buttonPridejStaniceni;
TableRow Radek_2, Radek_3, Radek_4,Radek_5,Radek_6;

@Override
private ArrayList<String> arrayList;
private ArrayAdapter<String> adapter;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

buttonPridejStaniceni = (Button) findViewById(R.id.buttonPridejStaniceni);
Radek_2 = (TableRow) findViewById(R.id.Radek_2);
Radek_3 = (TableRow) findViewById(R.id.Radek_3);
Radek_4 = (TableRow) findViewById(R.id.Radek_4);
Radek_5 = (TableRow) findViewById(R.id.Radek_5);
Radek_6 = (TableRow) findViewById(R.id.Radek_6);

}

public void PridejDalsiStaniceniClicked(View v)
{
Radek_2.setVisibility(View.VISIBLE);
Radek_3.setVisibility(View.VISIBLE);
Radek_3.setVisibility(View.VISIBLE);
Radek_4.setVisibility(View.VISIBLE);
Radek_5.setVisibility(View.VISIBLE);
Radek_6.setVisibility(View.VISIBLE);
}
}


`

Answer

It's actually easier than you think, change your onClick method, which I assume you're setting by xml to PridejDalsiStaniceniClicked to this:

int[] views = new int[]{R.id.Radek_2,R.id.Radek_3,R.id.Radek_4};//...
int counter = 0;
public void PridejDalsiStaniceniClicked(View v)
{
    findViewById(views[counter]).setVisibility(View.VISIBLE);
    if(counter<views.length){
        counter++;
    }
}

What happens inside is that we will fetch the view that matches the counter of times pressed while there are still views in the array. Some people don't realize that view ids are integers and can be stored in an array like in the example.

Comments