android:TextView的LayoutParams使视图以编程方式消失

Oct*_*rpe 27 android textview layoutparams

我从不同的角度来看这个.基本上要点是:

我已经在XML中为一个以编程方式运行NEEDS的接口布局了一个模板,因此它将在运行期间动态填充.

这里的问题是,XML TextView有很多布局调整(有效),是必要的.但是如果我实际上在代码中设置它们,TextView甚至都不显示.

(顺便说一下,TextView嵌套在TableRow中,因此调用了权重.)我首先设计的XML模板,用作代码的参考是这样的,它工作得很好:

<TextView
  android:id="@+id/txtviewWhiteBox"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:layout_weight="1.0"
  android:background="@drawable/textview_9patch_white"
  android:gravity="center"
  android:text="75"
  android:textColor="@android:color/black"
  android:layout_margin="20dp"
  android:padding="20dp"
  android:textSize="40dp" />
Run Code Online (Sandbox Code Playgroud)

就像我说的那样,完美地展示出来.当我在代码中运行相同的布局,并应用LayoutParams时,TextView消失.

这是相关的片段:

int textViewExampleID = 9001;

private TextView txtviewExample = new TextView(this);

private void buildTextView(){   
    LayoutParams paramsExample = new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT,1.0f);
    txtviewExample.setId(textViewExampleID);
    txtviewExample.setBackgroundResource(R.drawable.textview_9patch_white);
    txtviewExample.setGravity(Gravity.CENTER);
    txtviewExample.setTextColor(getResources().getColor(android.R.color.black));
    paramsExample.setMargins(20, 20, 20, 20);
    txtviewExample.setPadding(20, 20, 20, 20);
    txtviewExample.setTextSize(40); 
    txtviewExample.setText("customExample");

    //if I comment out the following line, this TextView displays.
    //if I leave it in, it doesn't display.
    txtviewExample.setLayoutParams(paramsExample);
}
Run Code Online (Sandbox Code Playgroud)

我意识到LayoutParams有各种各样的可用类,我一直在玩它们所有的LinearLayout.LayoutParams,TableView.LayoutParams,RelativeLayout.LayoutParams,LayoutParams本身...无论我尝试哪一个,任何尝试调用"setLayoutParams"渲染整个TextView.我在这里搜索了论坛,但还没有找到答案.这不是那么罕见.

Oct*_*rpe 104

好吧,这很痛苦,但我终于明白了.要记住的最重要的事情(我刚刚意识到)是所有无数的LayoutParams,你需要使用与你正在处理的视图的PARENT相关的那个,而不是实际的视图.

所以在我的情况下,我试图让TextView利润率发挥作用,但它被放入了一个TableRow.一个简单的改变是确保使用的类型LayoutParamsTableRow:

private void buildTextView(){   
    // the following change is what fixed it
    TableRow.LayoutParams paramsExample = new TableRow.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT,1.0f);
    txtviewExample.setId(textViewExampleID);
    txtviewExample.setBackgroundResource(R.drawable.textview_9patch_white);
    txtviewExample.setGravity(Gravity.CENTER);
    txtviewExample.setTextColor(getResources().getColor(android.R.color.black));
    paramsExample.setMargins(20, 20, 20, 20);
    txtviewExample.setPadding(20, 20, 20, 20);
    txtviewExample.setTextSize(40); 
    txtviewExample.setText("customExample");
    txtviewExample.setLayoutParams(paramsExample);
}
Run Code Online (Sandbox Code Playgroud)

谢谢大家,希望这对于其他人来说会派上用场,因为我在论坛中看到了很多半相关的问题,但没有真正定义问题的问题.

  • 谢谢!我有同样的问题,因为我使用LinearLayout.LayoutParams而不是TableRow.LayoutParams ...愚蠢的错误,但你让我免于很多挫折! (9认同)
  • 两个小时我试着解决这个问题.谢谢你,兄弟. (3认同)