我是Android工作室的初学者,我正在尝试创建一个应用程序。 我有一个问题:我有一个自定义ListView,当我点击一个按钮(打开一个带有editText的对话框)时,我想向这个ListView添加项目。 但我不成功! 目前我成功地将项目添加到一个简单的列表视图中,但我现在想要将项目添加到我的自定义ListView中:
这是我的自定义ListView(我的灵感来自互联网):
public class CustomList extends ArrayAdapter<String> {
private final Activity context;
private String[] web;
private final Integer[] imageId;
public CustomList(Activity context,
String[] web, Integer[] imageId) {
super(context, R.layout.list_single, web);
this.context = context;
this.web = web;
this.imageId = imageId;
}
@Override
public View getView(int position, View view, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View rowView= inflater.inflate(R.layout.list_single, null, true);
TextView txtTitle = (TextView) rowView.findViewById(R.id.txt);
ImageView imageView = (ImageView) rowView.findViewById(R.id.img);
txtTitle.setText(web[position]);
imageView.setImageResource(imageId[position]);
return rowView;
}
}
这是我现在的代码,但只是将项目添加到“普通”ListView
public class MenuActivity extends Activity {
ListView listplayer=null;
ImageButton addButton = null;
/** Items entered by the user is stored in this ArrayList variable */
ArrayList<String> list = new ArrayList<String>();
/** Declaring an ArrayAdapter to set items to ListView */
ArrayAdapter<String> adapter;
@Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu);
listplayer=(ListView) findViewById(R.id.list);
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, list);
addButton = (ImageButton) findViewById(R.id.buttonaddplayer);
addButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Create custom dialog object
final Dialog dialog = new Dialog(MenuActivity.this);
dialog.setTitle(getResources().getString(R.string.addperson));
// Include dialog.xml file
dialog.setContentView(R.layout.dialoglayout);
// Set dialog title
// dialog.setTitle("Custom Dialog");
// set values for custom dialog components - text, image and button
final EditText text = (EditText) dialog.findViewById(R.id.editTextdialog);
dialog.show();
ImageButton validButton = (ImageButton) dialog.findViewById(R.id.imageButtonvalid);
// if decline button is clicked, close the custom dialog
validButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
list.add(text.getText().toString());
text.setText("");
adapter.notifyDataSetChanged();
dialog.dismiss();
}
});
listplayer.setAdapter(adapter);
}
});
}
感谢您帮助我。 事实上我想做一个你可以添加播放器的应用程序,但是smth“漂亮”而不是android工作室的法线列表视图
答案 0 :(得分:0)
阅读此on adapters
检查here
找出你的'数据'的位置。
onButtonClick() - &gt;将新项插入适配器数据的“head”,调用'notifyDataSetChanged()'来更新视图