2015-09-10 41 views
1

我剛剛進入Android的世界,我使用Android的工作室和一本書上手,所以以後看了一些章節我想使我剛纔看了一些做法。創建多個TextViews編程

我想創建一個簡單的應用程序,要求你輸入一個字和一個號碼,點擊一個按鈕,你得到你所提交的字一個全新的活動後,顯示你以前說的確切數額。

實施例:您好,4 =你好你好你好你好(垂直地)

所以,我沒有創建在主活動此方法:

public void submit(){ 

    EditText Edtword = (EditText) findViewById(R.id.text); 
    EditText Edtnum = (EditText) findViewById(R.id.number); 

    String word = Edtword.getText().toString(); 
    int num = Integer.parseInt(Edtnum.getText().toString()); 

    Intent intent = new Intent(this, display.class); 
    intent.putExtra(display.EXTRA_MESSAGE, word); 
    intent.putExtra("number", (int)num); 
    startActivity(intent); 
} 

並通過按鈕啓動該第二活動:

public class display extends AppCompatActivity { 

public static final String EXTRA_MESSAGE = "word"; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_display); 
    Intent intent = getIntent(); 

    String word = intent.getStringExtra(EXTRA_MESSAGE); 
    int num = intent.getIntExtra("number", 0); 


} 

我應該添加在第2個活動,以創建編程那些TextViews?我嘗試了循環,但無法成功。

感謝

+1

你不需要4個textviews顯示4行文字。您只需在每個單詞之間添加「\ n」以獲得一個新行,並且它將適合單個TextView –

+0

好的,謝謝!但是現在以編程方式創建TextView的問題仍然存在 – FET

+0

如果您只需要在XML中定義TextView,則更簡單。如果你真的必須以編程方式做到這一點,看看這個線程:http://stackoverflow.com/questions/3204852/android-add-a-textview-to-linear-layout-programmatically –

回答

2

在你的第二個活動,首先你需要的屬性 android:orientation="vertical"在AndroidManifest文件中定義一個LinearLayout中。 即:

<LinearLayout 
     android:id="@+id/llMain" 
     android:layout_width="fill_parent" 
     android:layout_height="fill_parent" 
     android:orientation="vertical"> 
</LinearLayout> 

然後,你可以寫代碼在java文件如下圖所示:

LinearLayout m_ll = (LinearLayout) findViewById(R.id.llMain); 
     for(int i=0;i<num;i++) 
     { 
      TextView text = new TextView(this); 
      text.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT)); 
      text.setText(""+i); 
      m_ll.addView(text); 
     } 

我仍然相信,由Frank D.建議的方法是最佳的,但是這僅僅是供你參考,希望它有幫助。 :)

+0

我認爲這應該可行,但是當我在第二個活動中添加行時,我需要做出一些具有多個選擇的導入,我應該得到哪一個? – FET

+0

你的意思是說,你有一些數據的列表,你想要顯示在這些textviews? –

+0

等待,發佈截圖來清除它 – FET

3

我不會編程你的情況增加TextViews,這對你的目標太複雜。一個單獨的TextView(只需在您的佈局XML中定義它)可以保存多行文本。

TextView yourTextView = (TextView) findViewById(R.id.textView); //however your textview is defined in your xml 
String word = "Hello"; 
int num = 5; //or whatever value 

String multiLineText = ""; //empty at first 
for(int i = 0, i < num; i++){ 
    multiLineText = multiLineText + word + "\n"; 
} 

yourTextView.setText(multiLineText); 
1

您可以使用像這樣的循環,

for(i=1;i<=num;i++){ 
    txtView.append(word+"\n"); 
}