android - 如何从 .txt 文件填充自定义列表视图?安卓工作室
问题描述
尝试从 .txt 文件填充自定义列表视图。
自定义列表视图有 2 行,主标题和副标题。
这就是我尝试过的:
在 MainActivity.java 中:
public void readTxt() {
String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/MyApp/file.txt";
File file = new File( path );
StringBuilder text = new StringBuilder();
try {
BufferedReader br2 = new BufferedReader( new FileReader( file ) );
String line;
while ((line = br2.readLine()) != null) {
String[] maintitle = {
line
};
String[] subtitle = {
line
};
MyListAdapter adapter = new MyListAdapter( this, maintitle, subtitle );
lv = (ListView) findViewById( R.id.lv );
lv.setAdapter( adapter );
}
br2.close();
} catch (IOException e) {
Toast.makeText( this, "Error loading playlist", Toast.LENGTH_SHORT ).show();
}
}
}
在 MyListAdapter.java 中:
import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
public class MyListAdapter extends ArrayAdapter<String> {
private final Activity context;
private final String[] maintitle;
private final String[] subtitle;
public MyListAdapter(Activity context, String[] maintitle, String[] subtitle) {
super(context, R.layout.lv_player, maintitle);
// TODO Auto-generated constructor stub
this.context=context;
this.maintitle=maintitle;
this.subtitle=subtitle;
}
public View getView(int position,View view,ViewGroup parent) {
LayoutInflater inflater=context.getLayoutInflater();
View rowView=inflater.inflate(R.layout.lv_player, null,true);
TextView titleText = (TextView) rowView.findViewById(R.id.maintitle);
TextView subtitleText = (TextView) rowView.findViewById(R.id.subtitle);
titleText.setText(maintitle[position]);
subtitleText.setText(subtitle[position]);
return rowView;
};
}
我的 .txt 文件如下所示:Apple,think different,诺基亚,connecting people,Huawei,Make it possible
使用此代码仅填充第一项,如何填充所有?
解决方案
您是否尝试过向您的适配器添加一个方法来设置内容并从您的文件中传递所有信息?
它可能看起来像这样
适配器:
...
public MyListAdapter(Activity context) {
super(context, R.layout.lv_player, maintitle);
this.context=context;
}
...
public void setContent (String[] titleFromAfile, String [] subtitleFromAfile){
maintitle = titleFromAfile
subtitle = subtitleFromAfile
}
活动:
while (){
...
}
MyListAdapter adapter = new MyListAdapter( this);
lv = (ListView) findViewById( R.id.lv );
lv.setAdapter( adapter )
adapter.setContent(mainTitle, subTitle);
不要忘记附加数组
推荐阅读
- slickgrid - 如何以编程方式设置或更改具体单元格的值?
- python-2.7 - 在 spark 数据帧上使用 persist() 什么时候性能不实用?
- r - 提取两个冒号/特殊字符之间的子字符串
- android - gradle错误:错误:找不到参数的方法实现()
- forms - 如何同时使用 OnChanged 和 Validator?
- javascript - Uncaught ReferenceError: firebase is not defined, in web application
- java - java中的Lambda:变量与类字段
- java - Spring Data Repository:集合的“包含”
- python - 每组python 1:1分层抽样
- ffmpeg - 使用 Ffmpeg 快速创建、保持质量和压缩视频(Mp4)。我需要通过压缩转换更快和最好的质量