2015-09-10 40 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"); 
}