如何从.txt文件填充自定义列表视图? Android Studio

时间:2019-12-06 00:50:56

标签: android file listview text populate

尝试从.txt文件填充自定义列表视图。

自定义列表视图有两行,分别是主标题和副标题。

这是我尝试过的:

在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文件如下所示: 苹果公司,与众不同,诺基亚,联系人们,华为,让一切成为可能

使用此代码仅填充第一项,如何填充全部?

1 个答案:

答案 0 :(得分:0)

您是否尝试过将一种方法添加到您的适配器中以设置内容并将所有信息从那里传递到那里?

它可能看起来像这样

适配器:

...
 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);

别忘了添加数组