2011-08-03 11 views
14

今私は、その下にボタン(追加+)付きのテキストフィールドを持っています。Android - ボタンが押されたときにレイアウトにテキストビューを追加します

テキストフィールドにテキストが入力され、[追加]ボタンが押されるたびに新しいテキストビューがフィールドの下にある垂直レイアウトに追加されます。

テキストビューを非表示にしてクリックしたときに表示されたくないのは、入力したテキストを複数のテキストビューに追加できるようにするためです。

+0

使用addView方法でViewGroupクラスを使用すると、詳細情報が表示されます。http://developer.android.com/reference/android/view/ViewGroup.html – sunriser

答えて

31

このコードには、必要なものが含まれています。 (ビューでは、ボタンをクリックした後のテキストはのLinearLayoutに追加されます、のEditTextとボタンを表示)

private LinearLayout mLayout; 
private EditText mEditText; 
private Button mButton; 

@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 
    mLayout = (LinearLayout) findViewById(R.id.linearLayout); 
    mEditText = (EditText) findViewById(R.id.editText); 
    mButton = (Button) findViewById(R.id.button); 
    mButton.setOnClickListener(onClick()); 
    TextView textView = new TextView(this); 
    textView.setText("New text"); 
} 

private OnClickListener onClick() { 
    return new OnClickListener() { 

     @Override 
     public void onClick(View v) { 
      mLayout.addView(createNewTextView(mEditText.getText().toString())); 
     } 
    }; 
} 

private TextView createNewTextView(String text) { 
    final LayoutParams lparams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); 
    final TextView textView = new TextView(this); 
    textView.setLayoutParams(lparams); 
    textView.setText("New text: " + text); 
    return textView; 
} 

とXMLは次のとおりです。

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
android:orientation="vertical" 
android:layout_width="fill_parent" 
android:layout_height="fill_parent" 
android:id="@+id/linearLayout"> 
<EditText 
    android:id="@+id/editText" 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
/> 
<Button 
    android:id="@+id/button" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:text="Add+" 
/> 

+0

私はあなたを今とても愛しています。 – user802609

+0

本当に素晴らしい人 – Harshid

+0

他のアクティビティにテキストビューを追加するにはどうすればいいですか? 2回目のアクティビティでボタンをクリックして最初のアクティビティにテキストビューを追加したい – CraZyDroiD

関連する問題