Android 如何以编程方式显示TextView?
我有一个名为Android 如何以编程方式显示TextView?,android,Android,我有一个名为current\u layout的RelativeLayout,我把我的视图放在上面。当我尝试添加视图(文本视图)时,没有显示任何内容。但是,当添加ImageView时,它可以正常工作。为什么我的TextView不显示 public static void draw_shard(int x, int y, int amount_collected){//X and Y are GAMESURFACE values. Needs to increment by gamesurface
current\u layout
的RelativeLayout
,我把我的视图放在上面。当我尝试添加视图(文本视图)时,没有显示任何内容。但是,当添加ImageView
时,它可以正常工作。为什么我的TextView
不显示
public static void draw_shard(int x, int y, int amount_collected){//X and Y are GAMESURFACE values. Needs to increment by gamesurface y.
ImageView shard = create_iv(); // Creates a new instance of an ImageView (parameter is the context of MainActivity)
shard.setBackgroundDrawable(shard_icon);
shard.setX(x);
shard.setY(y+ImageLoader.get_score_bar_height());
TextView tv = new TextView(MainActivity.current_context);
tv.setX(shard.getX() + shard.getWidth());
tv.setY(shard.getY());
tv.setTypeface(Variables.joystix);
tv.setTextSize(shard.getHeight());
tv.setLayoutParams(new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT));
tv.setText("+" + amount_collected);
tv.setTextColor(Color.WHITE);
current_layout.addView(shard);
current_layout.addView(tv);
}
我还在黑色背景上添加了
TextView
。另一种简单的方法是:
在布局文件中添加TextView
,并将其可见性设置为gone,当需要显示TextView
时,只需更改该TextView
的可见性即可
XML
文件的示例代码:
<TextView
android:id="@+id/textview"
android:layout_height="wrap_content"
android:layout-width="wrap_content"
android:visibility="gone">
<!-- Add other attributes too -->
问题在于
shard.getWidth()
和shard.getHeight()
,它们返回0 但是为什么要使用java代码添加TextView
您可以用XML轻松地完成这项工作
<TextView
android:layout_width="wrap_content"
android:id="@+id/textView"
android:layout_height="wrap_content"
android:text="Hello World!"
android:background="@color/colorPrimary"
android:textColor="@color/colorPrimary" />
请试一试。它将帮助您理解
LinearLayout linearLayout = new LinearLayout(this);
setContentView(linearLayout);
linearLayout.setOrientation(LinearLayout.VERTICAL);
TextView textView = new TextView(this);
textView.setText("Your Text that you want to add");
linearLayout.addView(textView);
谢谢这太傻了。也许他的设计不需要一直绘制文本视图?我在代码中创建自定义UI是因为我必须..它显示我从服务器获得的信息。
// Create LinearLayout
LinearLayout ll = new LinearLayout(this);
ll.setOrientation(LinearLayout.HORIZONTAL);
// Create TextView
TextView product = new TextView(this);
product.setText(" Product");
ll.addView(product);
LinearLayout linearLayout = new LinearLayout(this);
setContentView(linearLayout);
linearLayout.setOrientation(LinearLayout.VERTICAL);
TextView textView = new TextView(this);
textView.setText("Your Text that you want to add");
linearLayout.addView(textView);