Android - dynamically defined settings

I am trying to pass the id of my new activity on creation.

The obvious solution is to use "Intent.putExtra (name, value);". But since the intention is only created when clicked, all of my buttons have the same Intent padding (usually null).

Is there a way to initialize them from a loop?

for ( int i = 0; i< IDList.size() ; i++) 
    {
        //Get Information from ID

        btnDetails.setOnClickListener(new OnClickListener() 
        {
            public void onClick(View v)
            {
                Intent intent = new Intent(getApplicationContext(),DetailActivity.class);
                intent.putExtra("", IDList.get(i));
                startActivity(intent);
            }
        });

        //Add To Screen
    }

In snippit code, IDList.get (i) goes out of scope, and the new Final Int is not checked until a button is pressed that also goes out of scope.

Is there another I can send the variable to click on?

+4
source share
1 answer

, OnClickListener id. ,

 private class MyOnClickListener implements OnClickListener {
  private final int mId;
  public MyOnClickListener(int id) {
    mId = id;
  }

  public void onClick(View v) {
      Intent intent = new Intent(getApplicationContext(), DetailActivity.class);
      intent.putExtra("", mId);
      startActivity(intent);
   }

} 

 for ( int i = 0; i< IDList.size() ; i++)   {       
        btnDetails.setOnClickListener(new MyOnClickListener(IDList.get(i)));
 }
+4

Source: https://habr.com/ru/post/1528119/


All Articles