mardi 14 juin 2016

Android: ArrayAdapter not being applied to ListView

I have a problem when I set an ArrayAdapter to the ListView in my layout. Everything looks fine and I don't have any errors but all I see in the list view is item1,item2 etc when I load up the XML file. Is there something I didn't add in?

Here's my code below:

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class LaunchActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_launch);

    ListView lv = (ListView) findViewById(R.id.subjectListView);

    String[] subjectArray = new String[]{"Physics","Chemistry","Economics", "Geography"};

    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, subjectArray);
    lv.setAdapter(adapter);

    lv.setOnItemClickListener(
            new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {


                    if (position == 0) {
                        Intent intent = new Intent(LaunchActivity.this, PhysicsFragment.class);
                        startActivity(intent);
                    } else if (position == 1) {
                        Intent intent = new Intent(LaunchActivity.this, ChemFragment.class);
                        startActivity(intent);
                    } else if (position == 2) {
                        Intent intent = new Intent(LaunchActivity.this, EconFragment.class);
                        startActivity(intent);
                    } else if (position == 3) {
                        Intent intent = new Intent(LaunchActivity.this, GeoActivity.class);
                        startActivity(intent);
                    }

                }
            }


    );

}


}

And here is my XML file:

<ListView
    android:layout_width="wrap_content"
    android:layout_height="fill_parent"
    android:id="@+id/subjectListView"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:layout_alignParentRight="true"
    android:layout_alignParentEnd="true"/>

Aucun commentaire:

Enregistrer un commentaire