布局不膨胀

时间:2018-10-21 18:13:27

标签: java android android-layout layout-inflater dynamic-ui

下面的代码用于创建笔记列表。我想将注释的标题添加到动态布局中。 但布局不会膨胀。

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

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

1 个答案:

答案 0 :(得分:0)

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

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

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