• After 15+ years, we've made a big change: Android Forums is now Early Bird Club. Learn more here.

Apps Button

I'm new to development, and i'm trying to make a button display the word "Green" and another button to display "Orange"

I have made the button, and changed the text, but I can't get it do to anything. I have been using this code to attempt to make the button work

<Button android:id="@+id/Button01"
android:layout_width="wrap_content"
android:layout_height="wrap_content" android:text="Green!">
android:gravity="bottom"
public class MyActivity extends Activity {
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);

setContentView(R.layout.content_layout_id);

final Button button = (Button) findViewById(R.id.button_id);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click android:background="@color/green"</Button>

}
});
}
}

Please help.
 
Well first of all. You are not supposed to combine the XML code with the java code... The XML code goes in an XML file in the res/layout/ folder, where-as the java code goes in a java file in the src/package/ folder.


EDIT: I am feeling generous today, so I am gonna help you out:

res/layout/main.xml
Code:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/LinearLayout01"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
<Button android:id="@+id/Button01" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:text="Green!"
    android:gravity="bottom"/>
</LinearLayout>
MyActivity.java
Code:
public class MyActivity extends Activity {
Button button;
LinearLayout layout;
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);

setContentView(R.layout.main);

button = (Button) findViewById(R.id.Button01);
layout = (LinearLayout) findViewById(R.id.LinearLayout01);
button.setOnClickListener(new View.OnClickListener() {
   public void onClick(View v) {
      if(v == button) {
         layout.setBackgroundColor(getResources().getColor(R.color.green); /*must have green defined in the res/values/colors.xml file.*/
      }
   }
});
}
}
 
Upvote 0
Here is what the structure should look similar to:

examplestructure.png


Also see my edited post above.
 
Upvote 0

BEST TECH IN 2023

We've been tracking upcoming products and ranking the best tech since 2007. Thanks for trusting our opinion: we get rewarded through affiliate links that earn us a commission and we invite you to learn more about us.

Smartphones