简体   繁体   English

LinearLayout返回activity后不显示children

[英]LinearLayout does not show children after returning to the activity

Trying to create an app which makes lists.试图创建一个制作列表的应用程序。 To create a new element in my list I want to use another activity.要在我的列表中创建一个新元素,我想使用另一个活动。 I do it like that:我这样做:

public void onNewTask(View view)
{
    Intent newTask = new Intent(MainActivity.this, NewTaskActivity.class);

    MainActivity.this.startActivityForResult(newTask, 0);
}

After returning to the main activity with results like this:返回到主要活动后,结果如下:

public void onSave(View view){
    Intent main = new Intent();

    String[] data;

    //getting data here//

    main.putExtra("New_task", data);
    setResult(RESULT_OK, main);

    finish();
}

After that, the linear layout does not show any children, though if I debug my code, I can see that the layout still has them inside.之后,线性布局不显示任何子级,但如果我调试我的代码,我可以看到布局内部仍然有它们。 I am adding children programmatically, like this:我正在以编程方式添加孩子,如下所示:

LinearLayout linearLayout = findViewById(R.id.toDoLayout); //is in OnCreate()

LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams //is in OnCreate()
         (LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);

LinearLayout newLayout = new LinearLayout(this);
newLayout.setOrientation(LinearLayout.HORIZONTAL);

TextView newNumberTextView = new LargeTextViewWithMargins(this);
newNumberTextView.setText("Test");
newLayout.addView(newNumberTextView);

linearLayout.addView(newLayout, layoutParams);

And the onActivityResult is now in this form: onActivityResult 现在是这种形式:

@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    setContentView(R.layout.activity_main);
}

I've found a similar question here .我在这里发现了一个类似的问题。 Does anyone know what may cause such a situation and how it is better to overcome it?有谁知道什么可能导致这种情况以及如何更好地克服它?

As kelvin suggested, I've removed setContenView from activityResult and this helped.正如kelvin建议的那样,我已经从 activityResult 中删除了 setContenView,这很有帮助。 However, I do not understand how it works, but it will do for me for now.但是,我不明白它是如何工作的,但它现在对我有用。

setContentView(R.layout.activity_main); setContentView(R.layout.activity_main); sets the XML (Layout ) for your activity when you call setContentView it will inflate the Layout on the Screen.当您调用 setContentView 时,为您的活动设置 XML (布局),它将使屏幕上的布局膨胀。 Now when you are calling it again in onActivityResult You are inflating the view again.现在,当您在 onActivityResult 中再次调用它时,您将再次膨胀视图。

Also I would suggest you to use ListView / RecyclerView for showing lists.另外我建议您使用 ListView / RecyclerView 来显示列表。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM