Home > database >  How to initialize several buttons in java
How to initialize several buttons in java

Time:10-16

It's any way to initialize buttons in a loop?

I've tried `public class MainActivity extends AppCompatActivity {

// CLICK SOUND //
private MediaPlayer clickSound;

// BUTTONS //

private Button btnAC;
private Button btnMasMenos;

private List<Button> listaBotones;
private List<String> listaIDs;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    clickSound = MediaPlayer.create(this,R.raw.click);

    // INITIALIZE BUTTONS //

    listaBotones = Arrays.asList(btnAC,btnMasMenos);
    listaIDs = Arrays.asList("R.id.btnAC","R.id.btnMasMenos");

    for(Button b: listaBotones){

        int id = 0;

        b = findViewById(listaIDs.get(id));

        id  ;
    }

}

This is the error:

reason: String is not compatible with int

I understand that R.id.button it's a int, and not a String... so I was wondering how can I initialize them automatically in a loop.

Thx in advance

CodePudding user response:

If you want to continue with what you are doing then use a list of Integer not String, and put ids inside of it.

BUT if the reason you are doing this is that you don't want to use findViewById() a lot then there are solutions for this like view binding it is very simple

read more at: https://developer.android.com/topic/libraries/view-binding

CodePudding user response:

You should not use findViewById, it's a tedious process to get each view. Instead, you should use viewBinding which would generate a binding class for your XML and it'll contain direct references to all views.

For using viewBinding, enable it in your module's build.gradle

android {
    ...
    buildFeatures {
        viewBinding true
    }
}

Sync your Gradle build and it'll generate binding classes for each view.

In your activity

private lateinit var binding: ActivityMainBinding

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    binding = ActivityMainBinding.inflate(layoutInflater)
    setContentView(binding.root)

    //access views using binding
    binding.btnAc.setOnClickListener  {}
}

For using in a fragment

private var _binding: FragmentBinding? = null
// This property is only valid between onCreateView and
// onDestroyView.
private val binding get() = _binding!!

override fun onCreateView(
    inflater: LayoutInflater,
    container: ViewGroup?,
    savedInstanceState: Bundle?
): View? {
    _binding = FragmentBinding.inflate(inflater, container, false)
    val view = binding.root
    return view
}

override fun onDestroyView() {
    super.onDestroyView()
    _binding = null // setting it null, otherwise it would lead to memory leak
}
  • Related