trakasi trakasi - 7 days ago 5
Android Question

Android studio set onclicklistener if arguments

I'm trying to figure out how to make one button, do different functions if arguments are true.

For example:

Got many possibilities(Flexible UI)

public void BuildCars(View view)
{
//Atver buildcarfragmentu.
switch(view.getId())
{
case R.id.button1:
// Set Frame Image, Part Cardviews and button.
ImageView Frame= (ImageView) findViewById(R.id.BCFrame);
Frame.setImageResource(R.drawable.frame_1_6);

Button button= (Button) findViewById(R.id.BCButton);
button.setOnClickListener(sellTiresLVL10_10());
break;

case R.id.button2:
// Set Frame Image, Part Cardviews and button.
break;

case R.id.button3:
// Set Frame Image, Part Cardviews and button.
break;
}
}


And in case 1, i want button, to do one thing and in case 2, to do another thing.

Like here:

public void BuildCars(View view)
{
//Atver buildcarfragmentu.
switch(view.getId())
{
case R.id.button1:
// Set Frame Image, Part Cardviews and button.
ImageView Frame= (ImageView) findViewById(R.id.BCFrame);
Frame.setImageResource(R.drawable.frame_1_6);

Button button= (Button) findViewById(R.id.BCButton);
button.setOnClickListener(sellTiresLVL10_10());
break;

case R.id.button2:
// Set Frame Image, Part Cardviews and button.

ImageView Frame= (ImageView) findViewById(R.id.BCFrame);
Frame.setImageResource(R.drawable.frame_1_6);

Button button= (Button) findViewById(R.id.BCButton);
button.setOnClickListener(sellTiresLVL9_4());
break;

case R.id.button3:
// Set Frame Image, Part Cardviews and button.
break;
}
}


But.. Got 2 problems.

1.Problem : Image
2.Problem : Image

Answer

Declare your frame outside of the switch statement, perhaps in your BuildCars() method, rather than in each case of the Switch Statement. I.e:

public void BuildCars(View view)
{ 
    ImageView Frame= (ImageView) findViewById(R.id.BCFrame);
    Button button= (Button) findViewById(R.id.BCButton);

    //Atver buildcarfragmentu.
    switch(view.getId())
    {
        case R.id.button1:
            // Set Frame Image, Part Cardviews and button.
            Frame.setImageResource(R.drawable.frame_1_6);

            button.setOnClickListener(sellTiresLVL10_10());
            break;

        case R.id.button2:
            Frame.setImageResource(R.drawable.frame_1_6);
            button.setOnClickListener(sellTiresLVL9_4());
            break;

        case R.id.button3:
            // Set Frame Image, Part Cardviews and button.
            break;
    }
}

You're also using the on click listener incorrectly. Your listener should look more like this:

final Button button = (Button) findViewById(R.id.button_id);
button.setOnClickListener(new View.OnClickListener() {
    public void onClick(View v) {
        // Perform action on click
    }
});

You should read the documentation to gain a better understanding of how exactly use the onClickListener: https://developer.android.com/reference/android/widget/Button.html