[英]How can I set the position of a TextView using Java Code?
我仍在学习Android,所以我知道这个问题听起来很愚蠢。 到这里,我需要在Activity上设置大量TextView的位置。 我使用来自意图的变量来接收数字,但是稍后当我需要创建与数字一样多的TextView时,它们将出现在布局中的位置(0,0)。 我需要创建一个格栅,例如:__ __ __ __但是,它们全部都出现在同一位置(0,0),而我的应用程序仅显示:__
这是我尝试的代码:
public class Play extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.act_play);
Intent intent=getIntent();
String n = intent.getStringExtra("NUM");
int times = Integer.parseInt(n);
TextView [] espaces = new TextView[times];
for(int i = 0; i < espaces.length; i++){
espaces[i] = new TextView(this);
espaces[i].setText(" __ ");
//Here I would like to set the position of my text view
setContentView(espaces[i]);
}
}
}
您似乎不了解setContentView()
作用。 它将现有的内容视图替换为传入的视图。因此,您无需添加视图,而是始终显示最后设置的视图。 如果要全部显示它们,请将它们添加到LinearLayout
并在其上设置setContentView()
的视图。
如果我没看错,我假设您使用的是相对布局,则需要更改为LinearLayout。
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/linear_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
</LinearLayout>
另外,您以错误的方式添加视图,您需要引用线性布局的变量。
//you create a field outside the onCreate Method
LinearLayout layout;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.act_play);
//then initialize the variable like this.
layout = (LinearLayout) findViewById(R.id.linear_layout);
Intent intent=getIntent();
String n = intent.getStringExtra("NUM");
int times = Integer.parseInt(n);
TextView [] espaces = new TextView[times];
for(int i = 0; i < espaces.length; i++){
espaces[i] = new TextView(this);
espaces[i].setText(" __ ");
//you add like this
layout.addView(espaces[i]);
}
}
我不知道布局xml act_play
内容。 但我希望它是带有id container
LinearLayout
。
因此,将代码更改为next:
public class Play extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.act_play);
ViewGroup content = (ViewGroup)findViewById(R.id.container); //<-this id from xml
Intent intent=getIntent();
String n = intent.getStringExtra("NUM");
int times = Integer.parseInt(n);
TextView [] espaces = new TextView[times];
for(int i = 0; i < espaces.length; i++){
espaces[i] = new TextView(this);
espaces[i].setText(" __ ");
content.addView(espaces[i]);//<-add to view group and not replace content view of activity
}
}
}
顺便说一句,您可以将整数放在意向中,因此找回它时无需进行转换。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.