0

I have GridLayout with a CardView inside. I want to create an Intent to 4 different activities. I only can execute one Intent. I do not know if I should use Else If or case. Thanks for your help. Here is my code.

GridLayout mainGrid;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.dashboard);
    mainGrid = (GridLayout)findViewById(R.id.grid);
    setSingleEvent(mainGrid);
}

private void setSingleEvent(GridLayout mainGrid) {

    for (int i=0;i<mainGrid.getChildCount();1++)
    {
        CardView cardView = (CardView)mainGrid.getChildAt(i);
        final int final1= i;
        cardView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent i=new      Intent(DashboardActivity.this,MapsActivity.class);
                startActivity(i);
            }
        });
    }
}
trocchietto
  • 2,607
  • 2
  • 23
  • 36
Arief NH
  • 39
  • 7

2 Answers2

0

I think your problem comes from a lack of understanding how the order of execution of the program works. If you insert a cycle for and then you put inside an anonymous class as it is the case of View.onViewClickListener is normal that you will have only one result, because you break the for cycle.

The way to go should be to not use a for cycle, but assigning different Explicit Intents depending by what you want to obtain.

EDIT. On the base of your use case you need to trigger the Intent from the Adapter. Please see here and mainly here, basically you need to use the Android SDK functionality that tells you which card has been clicked mRecyclerView.getChildLayoutPosition(view); then depending from your needs you may (or not) pass a switch case for educational purposes, although possibly is not the most elegant and efficient way to solve.

trocchietto
  • 2,607
  • 2
  • 23
  • 36
0

If you want a different Activity to be started depending on what CardView is clicked try something like the following:

private void setSingleEvent(GridLayout mainGrid) {
    mainGrid.getChildAt(0).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(i);
            }
        });
    mainGrid.getChildAt(1).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(i);
            }
        });
        //do this for all 4 cardViews.
}

In short: set all Intents separately.