2016-01-21 40 views
-3

我得到用戶的輸入,然後把它們放在ListView,但是當我點擊按鈕時,它沒有錯誤,打開佈局並立即關閉。當我嘗試arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, m_list);時,它完美。我的適配器是否工作?

public class HomeChat extends AppCompatActivity { 

    ListView listView; 
    EditText writeSms; 

    ArrayAdapter<String> arrayAdapter; 
    ArrayList<String> m_list = new ArrayList<String>(); 
    String emriUser; 

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

     writeSms = (EditText) findViewById(R.id.shkrunSms); 
     listView = (ListView) findViewById(R.id.listView); 


     emriUser = getIntent().getExtras().getString("emri"); 

     arrayAdapter = new ArrayAdapter<String>(this,R.layout.list_chat,m_list); 
     listView.setAdapter(arrayAdapter); 

    } 


    public void sentSmsButton(View view) { 

     String mesazhet = emriUser + ": " + writeSms.getText().toString(); 

     if (writeSms != null && writeSms.length() > 0) { 

      m_list.add(mesazhet); 
      arrayAdapter.notifyDataSetChanged(); 
      writeSms.setText(""); 

     }else 
     { 
      Toast.makeText(getApplicationContext(),"Something Wrong",Toast.LENGTH_LONG).show(); 
     } 
    } 
} 

下面是聊天佈局:

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:orientation="vertical" android:layout_width="match_parent" 
    android:layout_height="match_parent"> 

    <TextView 
     android:id="@+id/test123" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:textColor="#000" 
     android:background="#cccccc" 
     android:paddingTop="5dp" 
     android:paddingBottom="5dp" 
     android:paddingLeft="5dp" 
     android:paddingRight="5dp" 
     /> 

</LinearLayout> 

回答

2

的問題是,ArrayAdapter期待只在一個單一TextView的佈局。因此,包含TextViewLinearLayout的佈局將不起作用。嘗試將R.layout.list_chat更改爲:

<TextView 
    xmlns:android="http://schemas.android.com/apk/res/android" 
    android:id="@+id/test123" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:textColor="#000" 
    android:background="#cccccc" 
    android:paddingTop="5dp" 
    android:paddingBottom="5dp" 
    android:paddingLeft="5dp" 
    android:paddingRight="5dp" 
    /> 
+0

其工作完美非常感謝您 –