[英]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.