2011-08-03 7 views
14

그래서 지금은 그 아래에 버튼이있는 텍스트 필드가 있습니다.안드로이드 - 버튼을 눌렀을 때 레이아웃에 텍스트 뷰 추가

텍스트 필드에 텍스트를 입력 할 때마다 추가 버튼을 누르면 필드 아래에있는 세로 레이아웃에 필드에 입력 한 텍스트가 추가되어 새로운 텍스트 뷰가 추가됩니다. .

단순히 텍스트보기를 보이지 않게 한 다음 클릭하면 표시됩니다. 입력 한 텍스트가 둘 이상인 텍스트보기를 추가 할 수 있기를 바랍니다.

+0

사용 addView 방법에 ViewGroup 클래스를 사용하면 더 많은 정보를 얻을 수 있습니다. http : //developer.android.com/reference/android/view/ViewGroup.html – sunriser

답변

31

이 코드에는 원하는 내용이 포함되어 있습니다. (뷰는 사용자가 버튼을 클릭 한 후 텍스트가있는 LinearLayout에 추가합니다, 글고 치기와 버튼을 보여)

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

다른 활동에 텍스트 뷰를 추가하려면 어떻게해야합니까? 내 두 번째 활동에서 버튼 클릭으로 첫 활동에 텍스트 뷰를 추가하고 싶습니다. – CraZyDroiD

관련 문제