我编写了一个简单的程序来熟悉android中的UI设计。我在线性布局中动态添加了文本。当我调试代码时,我无法在logcat中看到任何错误,代码运行得非常好。但是我无法在设备中看到任何文字。我正在使用Galaxy S2。我也试过使用模拟器。但没有出现。我不知道为什么它没有在我的设备/模拟器中显示任何文本。请帮忙。
这是我的活动
public class ViewActivity extends Activity {
/** Called when the activity is first created. */
LinearLayout bar;
String myarray[]={"Foot Ball","Basket Ball","Cricket"};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
bar= (LinearLayout) findViewById(R.id.tag);// Map the Layout
bar.setVisibility(View.VISIBLE);
TextView bs_text[]= new TextView[myarray.length]; // Create TextView according to value in length variable;
for(int z=0;z< myarray.length ;z++)
{
try
{
bs_text[z] = (TextView) new TextView(this);
bs_text[z].setText( myarray [z]);
//bs_text[z].setTextSize(1);
bs_text[z].setBackgroundColor(android.graphics.Color.TRANSPARENT);
bs_text[z].setTextColor(android.graphics.Color.BLACK);
int height_in_pixels = bs_text[z].getLineCount() * bs_text[z].getLineHeight(); //approx height text
bs_text[z].setHeight(height_in_pixels);
//bs_text[z].setHeight(android.graphics.)
bar.addView(bs_text[z]);
}
catch(ArrayIndexOutOfBoundsException e)
{
Log.d("ArrayIndexOutOfBoundsException",e.toString());
}
}
}
}
这是我的main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/tag"
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</LinearLayout>
答案 0 :(得分:3)
将layoutparams设置为textview:
bs_text[z].setBackgroundColor(0xffffffff);
bar.addView(bs_text[z],new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
答案 1 :(得分:0)
尝试将layoutparams设置为textview,如
LayoutParams lp = new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT);
textview.setLayoutParams(lp);
答案 2 :(得分:0)
首次展示时,LinearView
可能会显示width
= 0和height
= 0:
android:layout_width="wrap_content"
android:layout_height="wrap_content"
由于它没有内容,因此大小为0.您应该重置视图,例如:
LayoutParams lp = new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT);
bar.setLayoutParams(lp);
添加TextViews
之后答案 3 :(得分:0)
如果要为TextViews赋予特定权重,则可以将布局参数设置如下 -
LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT,1.0f);
其中1.0f
表示TextView
的权重。然后将param添加到TextView
bs_text[z].setLayoutParams(param);