I am currently designing an app in which the user clicks on a button, and the text from that button is added to the listview. Here are condensed versions of activity_main.xml
and MainActivity.java
activity_main.xml
:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
tools:context=".MainActivity" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:id="@+id/good"
android:text="Good"
android:background="#99CC00"/>
<Button
android:id="@+id/bad"
android:text="Bad"
android:background="#FFBB33"/>
<Button
android:id="@+id/ugly"
android:text="Ugly"
android:background="#9933CC"/>
</LinearLayout>
<ListView
android:id="@android:id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
</LinearLayout>
MainActivity.java
:
public class MainActivity extends ListActivity {
public static ArrayList<String> mylist = new ArrayList<String>();
ArrayAdapter<String> adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ListView listview = (ListView) findViewById(android.R.id.list);
Button good = (Button) findViewById(R.id.good);
Button bad = (Button) findViewById(R.id.bad);
Button ugly = (Button) findViewById(R.id.ugly);
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, mylist);
good.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mylist.add("Good");
adapter.notifyDataSetChanged();
listview.setAdapter(adapter);
}
});
bad.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mylist.add("Bad");
adapter.notifyDataSetChanged();
listview.setAdapter(adapter);
}
});
ugly.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mylist.add("Good");
adapter.notifyDataSetChanged();
listview.setAdapter(adapter);
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
This design works great, but I'm trying to add one more thing: when a particular button is clicked and that particular word is added as an element in the listview
, I would like to make that element have the same background color as the button. For example, if the user clicks the button Good
, I would like the text Good
that appears in the listview
to have the background color #99CC00
. Similarly, for Bad
, I would like the background color to be #FFBB33
, and #9933CC
for Ugly
. Does anyone know how to approach this?