就像标题一样。有没有办法从其他活动/片段的ListView中获取组件? (即,如果ListView显示“ apple”,“ banana”,“ coconut”,有没有办法获取Array或其中的某些单词?)请帮助我!我正在尝试在其他活动/片段中使用ListView中的单词。 这是我的零件代码。
startButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
List<String> wordList = new ArrayList<>();
for (int i = 0; i < listView.getCount(); i++) {
wordList.add((String) listView.getItemAtPosition(i));
}
if(listView.getCount() == 0) {
Toast.makeText(MainActivity.this, "단어가 생성되지 않았습니다.", Toast.LENGTH_SHORT).show();
} else {
Intent intent;
intent = new Intent(MainActivity.this, Start.class);
startActivity(intent);
}
}
});
答案 0 :(得分:0)
解决方案::假定您的列表视图显示String的列表,例如“ apple”,“ banana”,“ coconut”等...
// Declare an array list to store list view components
List<String> listToPass = new ArrayList<>();
// Loop through the list view to get all components
for (int i = 0; i < yourListView.getCount(); ++i) {
listToPass.add((String) yourListView.getItemAtPosition(i));
}
// TODO: Send listToPass to another class.
尝试一下。
更新1:根据您的用例。
MainActivity.java
startButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
ArrayList<String> wordList = new ArrayList<>();
for (int i = 0; i < listView.getCount(); i++) {
wordList.add((String) listView.getItemAtPosition(i));
}
if(listView.getCount() == 0) {
Toast.makeText(MainActivity.this, "단어가 생성되지 않았습니다.", Toast.LENGTH_SHORT).show();
} else {
Intent intent = new Intent(MainActivity.this, Start.class);
intent.putStringArrayListExtra("word_list", wordList);
startActivity(intent);
}
}
});
Start.java
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ArrayList<String> wordList = getIntent().getStringArrayListExtra("word_list");
// TODO: Process your word list here
}