即時通訊嘗試填充一個ListView與AlertDialog的輸入,它打開一個EditText。我的問題是每次我在AlertDialog中用EditText給出一些東西,並從AlertDialog中單擊我的添加按鈕,它會用相同的String填充我的Array的所有20套。但是我希望他從EditText中填充字符串只有1時間,我可以用這個1項進一步工作。添加ListView項目與用戶輸入AlertDialog
這裏是我的代碼
MainActivity.java
public class MainActivity extends Activity {
private static final int DIALOG_ALERT = 10;
ListView list;
Button addBtn;
EditText input;
String[] items;
ArrayAdapter<String> adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
list = (ListView) findViewById(R.id.list);
addBtn = (Button) findViewById(R.id.addPlanBtn);
input = new EditText(this);
items = new String[20];
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, items);
list.setAdapter(adapter);
addBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
AlertDialog alert = new AlertDialog.Builder(MainActivity.this).create();
alert.setTitle("Train plan name");
alert.setMessage("enter a name:");
alert.setView(input);
alert.setButton("add", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
String value = input.getText().toString();
for(int i=0; i < items.length; i++){
items[i] = value;
}
}
});
alert.show();
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
activity_main.xml中
<RelativeLayout 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"
tools:context=".MainActivity" >
<ListView
android:id="@+id/list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_above="@+id/addPlanBtn"
>
</ListView>
<Button
android:id="@+id/addPlanBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:text="add a new Plan" />
</RelativeLayout>
感謝您的任何幫助。
啊好的,我做了這個項目[which] = value;但該應用程序崩潰比完成 – atr
哎呀,對不起,我有錯誤的代碼工作位。我誤解了你的代碼。 在你的情況下,你沒有連接到數組的特定成員的按鈕。我要編輯我的答案來反映這一點。 – qzikl
@atr我給你跳轉到android dev的道具,但它似乎仍然有一些基本的編程概念,你需要繼續。如果你有一個項目數組[i],並且你試圖設置一個值「which」,它只是onClick方法的參數,那麼「which」是一個數字1,2,3等。如果你的items [i]數組的大小不是3,並且您嘗試設置項目[3],它會崩潰。 –