I am recently struggling with creating a java based code on Android Studio which I am working on since 2days now. Unfortunately, I cannot find any resolution for my problem on the stackoverflow or any other forum..
I try to highlight a button when clicked in red or green depending on if the buttons text is text1 or text2 of a string-array.
If I run the application it always shows me an error or the button simply doesn't change it's color when I press it. I guess that this has to do with the if-clause, but I don't really know how to solve this problem in any other way.
I would really appreciate any help on this matter!
XML code for green button
<item
android:state_pressed="true"
android:drawable="#81c784"/>
<item
android:state_selected="true"
android:drawable="@color/#4caf50"/>
XML code for red button
<item
android:state_pressed="true"
android:drawable="#FF4081"/>
<item
android:state_selected="true"
android:drawable="#d50000"/>
Java code:
Button button1;
Button button2;
String[] txtString;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.first_layout);
txtString = getResources().getStringArray(R.array.optiontxt);
String random = answerString[new random().nextInt(txtString.length)];
button1 = (Button)findViewById(R.id.btn1);
button2 = (Button)findViewById(R.id.btn2);
if (random == txtString[0])
{
button1.setText(txtString[0]);
button1.setBackgroundResource(R.drawable.button_green);
button2.setText(txtString[1]);
button2.setBackgroundResource(R.drawable.button_red);
}
else
{
button1.setText(txtString[1]);
button1.setBackgroundResource(R.drawable.button_red);
button2.setText(txtString[0]);
button2.setBackgroundResource(R.drawable.button_green);
} button1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {}}; button2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {}};
I also tried varies other codes which didn't work aswell, like
button1.setBackground(Drawable.createFromPath("/drawable/button_green"));
or
button1.getBackground().setState(new int[]{R.drawable.button_green});
or
button1.setBackgroundResource(R.drawable.button_green);
If anybody could help me with my problem I would be very thankful. Thank you for any help in advance!!
Aucun commentaire:
Enregistrer un commentaire