添加&在Android中以编程方式删除TextView

时间:2014-12-22 07:47:29

标签: android textview

我成功地以编程方式添加了TextView ...但我的问题是,如何通过编程方式删除TextView ...这是我的代码



MainActivity.java

package com.example.textviewdemo;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
<br>
public class MainActivity extends ActionBarActivity {

    private TextView addTv;
    private EditText edt;
    private Button add, delete;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        edt = (EditText) findViewById(R.id.editText1);
        add = (Button) findViewById(R.id.button1);
        delete = (Button) findViewById(R.id.button2);
        final LinearLayout ll = (LinearLayout) findViewById(R.id.LinearLayout);

        add.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                int no = Integer.parseInt(edt.getText().toString());
                for (int i = 1; i <= no; i++) {
                    addTv = new TextView(MainActivity.this);
                    addTv.setText("TextView " + i);
                    addTv.setId(i);
                    ll.addView(addTv);
                }
            }
        });
        delete.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                int no1 = Integer.parseInt(edt.getText().toString());
                for (int i = 1; i <= no1; i++) {
                    ll.removeView(addTv);
                }
            }
        });
    }
}





当我点击删除按钮它只删除最后一个TextView ..
我该怎么办?

2 个答案:

答案 0 :(得分:1)

将所有TextView存储在一个数组中并执行您想要的操作。现在addTv是最后创建的TextView。此外,如果您在添加之前单击删除,您将获得NullPointerException。

另请参阅:http://developer.android.com/reference/android/view/ViewGroup.html#removeViewAt(int)http://developer.android.com/reference/android/view/ViewGroup.html#removeViewsInLayout(int,%20int)

答案 1 :(得分:1)

for(int i = 0; i<ll.getChildrenCount(); i++){
    if(ll.getChildAt(i) instanceof TextView){
        ll.removeView(ll.getChildAt(i));
    } 
}

这将找到ll的所有子项,如果它们是TextView

的实例,则将其删除