Csáki Csáki - 1 month ago 5
Java Question

Declare multiple views with a similar name (Android Studio)

I want to declare and hide some views on the activity, but it's too complicated and consumes a lot of time. Can i do this with a loop or something?

//Startup
//Hide msgs
CardView msgUser1v = (CardView) findViewById(R.id.msgUser1v);
msgUser1v.setVisibility(View.GONE);
CardView msgBot1v = (CardView) findViewById(R.id.msgBot1v);
msgBot1v.setVisibility(View.GONE);
CardView msgUser2v = (CardView) findViewById(R.id.msgUser2v);
msgUser2v.setVisibility(View.GONE);
CardView msgBot2v = (CardView) findViewById(R.id.msgBot2v);
msgBot2v.setVisibility(View.GONE);
CardView msgUser3v = (CardView) findViewById(R.id.msgUser3v);
msgUser3v.setVisibility(View.GONE);
CardView msgBot3v = (CardView) findViewById(R.id.msgBot3v);
msgBot3v.setVisibility(View.GONE);
CardView msgUser4v = (CardView) findViewById(R.id.msgUser4v);
msgUser4v.setVisibility(View.GONE);
CardView msgBot4v = (CardView) findViewById(R.id.msgBot4v);
msgBot4v.setVisibility(View.GONE);
CardView msgUser5v = (CardView) findViewById(R.id.msgUser5v);
msgUser5v.setVisibility(View.GONE);
CardView msgBot5v = (CardView) findViewById(R.id.msgBot5v);
msgBot5v.setVisibility(View.GONE);

Answer

I think this will be a good way to do it:

List<CardView> cards = new ArrayList<CardView>();
for (int i = 1 ; i <= cardsCount ; i++)
{
    int id = getResources().getIdentifier("msgBot"+i+"v", "id", context.getPackageName());
    cards.add((CardView) findViewById(id));
}

Now you have all your card views in cards array. If you want to make them invisible, you can do it easily like this:

for(CardView c : cards){
    cards.setVisibility(View.INVISIBLE);
}