以编程方式创建的TextView未显示

时间:2016-08-16 19:07:29

标签: java android

我正在尝试以编程方式创建一个TextView,它将以另一个布局显示,该布局不属于同一个活动,但未显示TextView。以下是代码:

的活动:

公共类LogActivity扩展了AppCompatActivity {

...DataConnection.*

布局:

LinearLayout textLayout;
TextView textView;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.layout_one);

    LayoutInflater layoutInflater=getLayoutInflater();

View textEntryLayout=layoutInflater.inflate(R.layout.layout_two, null);

    textLayout=(LinearLayout) textEntryLayout.findViewById(R.id.layout);
    textView=new TextView(this);

    textView.setText("TextView");
    textView.setLayoutParams(new LayoutParams(
            LayoutParams.MATCH_PARENT,
            LayoutParams.WRAP_CONTENT));
    textLayout.addView(textView);

}

2 个答案:

答案 0 :(得分:1)

这是因为您的容器layout有其他孩子的高度设置为match_parent。您无法在Java代码中看到TextView,因为用XML添加的其他子代填充了整个屏幕。

答案 1 :(得分:0)

您需要将textEntryLayout添加到布局中。您正在修改该膨胀的视图,而不将其添加到(例如)layout_one中的布局。

尝试:

LinearLayout layout = (LinearLayout)findViewById(R.id.layout_id_in_layout1);
layout.addView(textEntryLayout);
相关问题