gpt4 book ai didi

java - 将项目添加到 Android ListView

转载 作者:行者123 更新时间:2023-12-02 05:11:23 25 4
gpt4 key购买 nike

我想主要从java类向listview添加项目

<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/listView"
android:layout_below="@+id/textView"
android:layout_centerHorizontal="true"
android:layout_above="@+id/txtMsg" />

我的java代码是

ListView list = (ListView) findViewById(R.id.listView);

我想添加到 ListView(list) 值中,这些值应该显示在手机上,并且应该是可点击的,所有代码都应该在 java 类上

最佳答案

 final ListView listview = (ListView) findViewById(R.id.listview);
String[] values = new String[] { "Android", "iPhone", "WindowsMobile",
"Blackberry", "WebOS", "Ubuntu", "Windows7", "Max OS X",
"Linux", "OS/2", "Ubuntu", "Windows7", "Max OS X", "Linux",
"OS/2", "Ubuntu", "Windows7", "Max OS X", "Linux", "OS/2",
"Android", "iPhone", "WindowsMobile" };

final ArrayList<String> list = new ArrayList<String>();
for (int i = 0; i < values.length; ++i) {
list.add(values[i]);
}
final StableArrayAdapter adapter = new StableArrayAdapter(this,
android.R.layout.simple_list_item_1, list);
listview.setAdapter(adapter);



private class StableArrayAdapter extends ArrayAdapter<String> {

HashMap<String, Integer> mIdMap = new HashMap<String, Integer>();

public StableArrayAdapter(Context context, int textViewResourceId,
List<String> objects) {
super(context, textViewResourceId, objects);
for (int i = 0; i < objects.size(); ++i) {
mIdMap.put(objects.get(i), i);
}
}

@Override
public long getItemId(int position) {
String item = getItem(position);
return mIdMap.get(item);
}

@Override
public boolean hasStableIds() {
return true;
}

}

让项目在 ListView 中可点击

listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {

@Override
public void onItemClick(AdapterView<?> parent, final View view,
int position, long id) {
final String item = (String) parent.getItemAtPosition(position);
view.animate().setDuration(2000).alpha(0)
.withEndAction(new Runnable() {
@Override
public void run() {
list.remove(item);
adapter.notifyDataSetChanged();
view.setAlpha(1);
}
});
}

});
}

代码取自Vogella

关于java - 将项目添加到 Android ListView ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27309640/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com