TextView tv1 = new TextView(this);
tv1.setPadding(5, 0, 5, 0);
tv1.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT));
tv1.setBackgroundColor(Color.parseColor("#0099cc"));
tv1.setTextColor(Color.WHITE);
tv1.setTextSize(11);
tv1.setGravity(Gravity.LEFT | Gravity.BOTTOM);
tv1.setText("Test1");
ll.addView(tv1);
TextView tv2 = new TextView(this);
tv2.setPadding(5, 0, 5, 0);
tv2.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT));
tv2.setBackgroundColor(Color.parseColor("#0099cc"));
tv2.setTextColor(Color.WHITE);
tv2.setTextSize(11);
tv2.setGravity(Gravity.LEFT | Gravity.BOTTOM);
tv2.setText("Test2");
ll.addView(tv2);
Run Code Online (Sandbox Code Playgroud)
正如你所看到的,在这个代码的平静中,我设置了TextView背景颜色.我想要做的是我想将它们彼此分开TextView,这样它们的背景颜色就会被一条线分开.我不希望他们连接.据我了解,如果可以设定利润率,就有可能这样做TextView,但据我所知,TextView我们无法做到这一点.
我从不同的角度来看这个.基本上要点是:
我已经在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.我在这里搜索了论坛,但还没有找到答案.这不是那么罕见.
如果我使用xml文件,我有一个名为layout_margin的选项(例如layout_margin ="1dp"用于文本视图),但我想以编程方式设置,我不知道该怎么做.