我是android的新手,被要求为Android开发应用程序。我正在使用Android 2.2。我遇到的问题是,一旦我点击基本教程中的“添加”按钮,就会出现客户端的名称,但它不会那样工作。单击按钮后,列表视图中未显示该名称。
这里是代码:
public class MainActivity extends Activity implements OnClickListener,
OnKeyListener {
ArrayList<String> appointment;
ArrayAdapter<String> aa;
EditText editText1;
Button addButton;
ListView listView1;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
editText1 = (EditText)findViewById(R.id.editText1);
addButton = (Button)findViewById(R.id.addButton);
listView1 = (ListView)findViewById(R.id.listView1);
addButton.setOnClickListener(this);
editText1.setOnKeyListener(this);
appointment = new ArrayList<String>();
aa = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,
appointment);
listView1.setAdapter(aa);
}
private void addItems(String item){
if (item.length()>0){
this.appointment.add(item);
this.aa.notifyDataSetChanged();
this.editText1.setText("");
}
}
public void onClick(View v) {
if(v==this.addButton){
this.addItems(this.editText1.getText().toString());
}
}
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (event.getAction()==KeyEvent.ACTION_DOWN &&
keyCode==KeyEvent.KEYCODE_DPAD_CENTER)
this.addItems(this. editText1.getText().toString());
return false;
}
}
main.xml中:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android">
<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent" android:layout_height="wrap_content"
android:weightSum="1">
<ImageView
android:id="@+id/phones_icon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:src="@drawable/user"
android:layout_margin="20dp"
/>
<Button
android:text="Add New Appoinments"
android:id="@+id/addButton"
android:layout_gravity="center_horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textStyle="bold"
android:typeface="sans"
></Button>
<EditText android:id="@+id/editText1" android:layout_height="wrap_content"
android:layout_width="match_parent" android:inputType="textPersonName">
<requestFocus></requestFocus>
</EditText>
<ListView android:id="@+id/listView1" android:layout_width="wrap_content"
android:layout_height="252dp"></ListView>
</LinearLayout>
</ScrollView>
请指导我。提前致谢
答案 0 :(得分:5)
您不需要保留ArrayList和ArrayAdapter
ArrayAdapter实际上会在其中保存字符串列表。
摆脱你的ArrayList并改变这一行
this.appointment.add(item);
到
this.aa.add(item);
你应该好好去。
我也对您使用所有变量的完全限定名称的原因感兴趣。我肯定得到的,有时你的各种课程的范围将使得必须使用“这个”。面前的事情,但在我的例子中,我觉得如果没有“这个”,你会好的。
这是您在阅读代码时为了清晰起见而做的事情,还是用于其他目的?
编辑:p.s. @Selvin完全钉了这个,如果他们发布了答案,请接受他们而不是我的。
答案 1 :(得分:0)
您应该可以使用aa.add(item)
执行此操作;无需ArrayList
。