2017-05-26 2 views
-1

Die unten ist mein Testcode, um die Listenansicht zu erstellen, die Listenansicht wird erfolgreich angezeigt, jedoch gibt es Fehler beim Klickereignis. Hier ist mein einfacher Code:Android Listview Klicken stürzt ab

public class MainActivity extends Activity { 

    private String[] Ass; 
    private TextView textView; 
    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 

     setContentView(R.layout.activity_main); 
     Ass=new String[]{"Ass1","Ass"}; 
     ListView mListView = (ListView) findViewById(R.id.ass); 

     ArrayAdapter<String> mAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, Ass); 
     mListView.setAdapter(mAdapter); 
     mListView.setClickable(true); 

     mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { 

      @Override 
      public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,long arg3) { 

       textView.setText(Ass[arg2]); 

     }); 

    } 

Hier ist die XML-Datei

<?xml version="1.0" encoding="utf-8"?> 
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:tools="http://schemas.android.com/tools" 
    android:id="@+id/activity_main" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    tools:context="com.example.a21.proplay.MainActivity"> 

    <ListView 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" 
     android:id="@+id/ass" 
     android:layout_alignParentBottom="true" 
     android:layout_alignParentLeft="true" 
     android:layout_alignParentStart="true" 
     android:layout_marginBottom="67dp" /> 

    <TextView 
     android:text="TextView" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_alignParentBottom="true" 
     android:layout_alignParentLeft="true" 
     android:layout_alignParentStart="true" 
     android:layout_marginLeft="20dp" 
     android:layout_marginStart="20dp" 
     android:layout_marginBottom="23dp" 
     android:id="@+id/textView" /> 
</RelativeLayout> 

Wenn ich es nicht heraus zur Liste klicken crashes.I kann, warum der Klick nicht ist working.How kann ich das beheben, dass ?

+1

schöne Benennung von Variablen –

Antwort

2

Fügen Sie diese Zeile

textView = (TextView) findViewById(R.id.textView) 
1

Ihre textView ist null.

initialisieren es mögen:

TextView textView = (TextView) findViewById(R.id.textView); 

ändern Sie Ihren Code:

mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { 

     @Override 
     public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,long arg3) { 

      String selectedFromList =(String) (mListView.getItemAtPosition(arg2)); 
      textView.setText(selectedFromList); 

    });