我是编程的初学者,我在第二个项目中需要帮助,这是一个简单的字典。
很快,起初我想创建一个字符串数组并使用ListView
显示它。我有(现在我还有)list_item
布局,其中包含两个TextView
s(一个包含一个单词,第二个包含其翻译)和ListView
在另一个XML中。当我从非常清晰的教程中学习时,一切都很完美,但是,我决定扩大我的字典。出于这个原因,我不想在方法中声明所有单词,而是想从txt文件加载它们。我遵循了许多关于如何实现这一目标的教程,但是,我无法正确转换代码。这是我的代码:
public class MainActivity extends AppCompatActivity {
public static void main(String[] args) throws FileNotFoundException {
ArrayList<AndroidFlavor> androidFlavors = new ArrayList<AndroidFlavor>();
BufferedReader file = new BufferedReader(new FileReader("words.txt"));
try {
StringBuilder builder = new StringBuilder();
String line;
while ((line = file.readLine()) != null) {
String token[] = line.split("\\|");
String mPolish = token[0];
String mEnglish = token[1];
AndroidFlavor androidFlavor = new AndroidFlavor(mPolish, mEnglish);
androidFlavors.add(androidFlavor);
}
for (int i = 0; i < androidFlavors.size(); i++) {
System.out.println(androidFlavors.get(i).getPolish() + " "
+ androidFlavors.get(i).getEnglish() + " ");
}
file.close();
} catch (Exception e) {
}}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
public void button1(View view) {
setContentView(R.layout.free);
AndroidFlavorAdapter flavorAdapter = new AndroidFlavorAdapter(this, androidFlavors);
ListView listView = (ListView) findViewById(R.id.lista);
listView.setAdapter(flavorAdapter);
}
我也有:
public class AndroidFlavor {
// String for polish words
private String mPolish;
// String for English translations
private String mEnglish;
// New AndroidFlavor object.
public AndroidFlavor(String vPolish, String vEnglish) {
mPolish = vPolish;
mEnglish = vEnglish;
}
//Get Polish word
public String getPolish() {
return mPolish;
}
//Get English word
public String getEnglish() {
return mEnglish;
}
}
最后这个:
public class AndroidFlavorAdapter extends ArrayAdapter<AndroidFlavor> {
private static final String LOG_TAG = AndroidFlavorAdapter.class.getSimpleName();
super(context, 0, androidFlavors);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View listItemView = convertView;
if(listItemView == null) {
listItemView = LayoutInflater.from(getContext()).inflate(
R.layout.list_item, parent, false);
}
AndroidFlavor currentAndroidFlavor = getItem(position);
TextView nameTextView = (TextView) listItemView.findViewById(R.id.polish);
nameTextView.setText(currentAndroidFlavor.getPolish());
TextView numberTextView = (TextView) listItemView.findViewById(R.id.english);
numberTextView.setText(currentAndroidFlavor.getEnglish());
return listItemView;
}
}
我有以下问题:点击button1
后,如何根据txt文件中的字符串数组打开ListView
?我希望获得相同的效果(即显示ListView
来自2 TextView
s),就像我将txt文件添加到项目之前一样。