I tried to make an simple custom ListView listitem to help me understand how this works but it won't work.
When I use the commented line in my MainActivity.java, everything works (it uses the built-in layout). But when I try my own layout row_layout instead of the simple_list_item_1 I get an ANR when starting the program.
MainActivity.java
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String[] colors = {"blue", "red", "yellow", "green", "purple", "orange"};
//ListAdapter listAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, colors);
ListAdapter listAdapter = new ArrayAdapter<String>(this, R.layout.row_layout, colors);
ListView listView = (ListView)findViewById(R.id.theListView);
listView.setAdapter(listAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String auswahl = "Auswahl:" + String.valueOf(parent.getItemAtPosition(position));
Toast.makeText(MainActivity.this, auswahl, Toast.LENGTH_LONG).show();
}
});
}
}
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity">
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/theListView"></ListView></LinearLayout>
row_layout.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/textView1"
android:textSize="30sp"
android:textStyle="bold"
android:padding="15dp"/></LinearLayout>
You need to provide the id of the TextView inside your custom row when you're calling the adapter.