添加动态文本视图

问题描述 投票:0回答:1

试图创建笔记应用程序。我想在按钮点击后添加动态文本视图,它应该一个接一个地添加到布局中。在我的代码中,只有一个文本视图成功添加,但从第二次,应用程序崩溃。请帮忙

XML code:

   <EditText
        android:id="@+id/text_thingsToDo"
        android:layout_width="@dimen/ThingsToDo_EditText_Width"
        android:layout_height="@dimen/ThingsToDo_EditText_Height"
        android:layout_margin="@dimen/Standardize_Margin"
        android:background="@color/ThingsToDo_EditText_Color"/>

    <Button
        android:id="@+id/save_thingsToDo"
        android:layout_toRightOf="@+id/text_thingsToDo"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/ThingsToDo_Save_Button_Text"
        android:layout_marginRight="@dimen/Standardize_Margin"
        android:layout_marginTop="@dimen/Standardize_Margin"
        android:layout_marginBottom="@dimen/Standardize_Margin"
        android:background="@color/ThingsToDo_Save_Button"
        android:textColor="@color/White"
        android:layout_centerVertical="true"/>

Java代码:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_things_to_do);

    final EditText editText = (EditText) findViewById(R.id.text_thingsToDo);
    Button button = (Button) findViewById(R.id.save_thingsToDo);
    final TextView notesView = new TextView(this);
    final LinearLayout linearLayout = (LinearLayout) findViewById(R.id.rootView_ThingsToDo);
    final ArrayList<String> arrayList = new ArrayList<String>();

    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            notesView.setText(editText.getText().toString());
            linearLayout.addView(notesView);
        }
    });

}
java android
1个回答
2
投票

也许每次按下按钮都会创建一个新的TextView?尝试将TextView声明为类成员,然后在OnClickListener中执行此操作:

button.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        notesView = new TextView(this);
        notesView.setText(editText.getText().toString());
        linearLayout.addView(notesView);
    }
});

希望这将解决您的问题!

© www.soinside.com 2019 - 2024. All rights reserved.