-1

下面的代码用于创建笔记列表。我想获取笔记的标题并添加到动态布局中。但布局没有膨胀。

public class TakeNote extends AppCompatActivity {

List<String> titles = new ArrayList<>();

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_take_note);
    reader();
    LinearLayout layout = (LinearLayout) findViewById(R.id.tn);
    try {
        addlist(titles, layout);
    }
    catch(Exception e){

    }
}

这将读取存储标题的文件...

 public void reader(){


        try {
            Scanner sc = new Scanner(openFileInput("titles.txt"));
            while(sc.hasNextLine()){
                titles.add(sc.nextLine());
            }
            sc.close();

        }
        catch(Exception e){
        }

    }

这会将标题写入文件。

 public void writer(String title){
    try {
        PrintStream write = new PrintStream(openFileOutput("titles.txt", MODE_PRIVATE | MODE_APPEND));
        write.println(title);

        write.close();
    }
    catch(Exception e){

    }

}
ArrayAdapter<String> adap;

private void addlist(List<String> l,LinearLayout layout){
    View v = getLayoutInflater().inflate(R.layout.newnote,null);
    adap = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, l);
    ListView list = (ListView) findViewById(R.id.tit);
    try {
        list.setAdapter(adap);
    }
    catch(Exception e){}
    layout.addView(v);

}

单击添加按钮时,将出现一个自定义输入对话框,以获取注释的标题。

 public void addnote(View view) {
    LayoutInflater layoutInflater = LayoutInflater.from(this);
    View promptView = layoutInflater.inflate(R.layout.addworddialog, null);
    AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
    // set prompts.xml to be the layout file of the alertdialog builder
    alertDialogBuilder.setView(promptView);
    final EditText input = (EditText) promptView.findViewById(R.id.nw);
    // setup a dialog window
    alertDialogBuilder
            .setCancelable(false)
            .setPositiveButton("ADD", (dialog, id) -> {
                // get user input and set it to result
                writer(input.getText().toString());

            })
            .setNegativeButton("Cancel",
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            dialog.cancel();
                        }
                    });
    // create an alert dialog
    AlertDialog alertD = alertDialogBuilder.create();
    alertD.show();
    LinearLayout layout = (LinearLayout) findViewById(R.id.tn);
    addlist(titles,layout);
}
}

此外,在整个过程中没有错误。
它只是没有显示新的列表布局

4

1 回答 1

0
alertD.show();
LinearLayout layout = (LinearLayout) findViewById(R.id.tn);
addlist(titles,layout);

Dialog.show不会阻塞,因此在被调用titles时可能不会更改addlist,从而导致您看到的行为。

此外,更改“titles.txt”文件并不意味着读取的标题列表reader()会改变。

于 2018-10-21T18:42:26.647 回答