Подтвердить что ты не робот

Как динамически добавлять флажки в android

Мне нужно создавать поля edittext динамически в android. Я прошел через ссылку и написал для нее действие нажатия кнопки. То есть, когда я нажимаю на кнопку, должны отображаться флажки. Но когда я создаю объект checkbox в действии onclick, он показывает ошибку.

Может кто-нибудь рассказать мне, почему это показывает ошибку?

Мой код:

public class InflationActivity extends Activity {

@Override

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    ScrollView sv = new ScrollView(this);
    final LinearLayout ll = new LinearLayout(this);
    ll.setOrientation(LinearLayout.VERTICAL);
    sv.addView(ll);

    TextView tv = new TextView(this);
    tv.setText("Dynamic layouts ftw!");
    ll.addView(tv);

    EditText et = new EditText(this);
    et.setText("weeeeeeeeeee~!");
    ll.addView(et);

    Button b = new Button(this);
    b.setText("I don't do anything, but I was added dynamically. :)");
    ll.addView(b);



    b.setOnClickListener(new View.OnClickListener() {

     @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub

        for(int i = 0; i < 20; i++) {
         CheckBox ch = new CheckBox(this);
         ch.setText("I'm dynamic!");

            ll.addView(ch);
        }


        }
    });


    this.setContentView(sv);

   }
 }
4b9b3361

Ответ 1

Просто измените слушателя на (отлично работает, я пробовал):

b.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View v) {
        for(int i = 0; i < 20; i++) {
            CheckBox cb = new CheckBox(getApplicationContext());
            cb.setText("I'm dynamic!");
            ll.addView(cb);
        }
    }
});

Обратите внимание на два изменения:

  • View.OnClickListener to OnClickListener
  • new CheckBox(this) to new CheckBox(getApplicationContext())

Ответ 2

 CheckBox ch = new CheckBox(this);

измените (это) на новый CheckBox (название вашей деятельности); потому что если вы пройдете это, он не примет контекст вашей активности, потому что вы кодируете эту строку внутри прослушивателя кликов.

Ответ 3

CheckBox ch = new CheckBox(this); "this" - это не активность, а слушатель. Вы можете использовать InflationActivity.this, но вы должны использовать getApplicationContext(); или getBaseContext(). Если у вас есть ошибка времени выполнения, вы должны включать stacktrace из файлов журнала. Если ваш проект не может выполнить сложность, просто измените это на то, что я предложил, и все будет в порядке.

Ответ 4

Через несколько лет после этого вопроса, но требование не изменилось... вот как я работал над API 22. Небольшая вариация заключается в том, что у меня есть плавающая кнопка (fab) на основном макете и где я динамически создаю LinearLayout.

Примечание: b.setOnClickListener(new View.OnClickListener() и

CheckBox ch = new CheckBox(v.getContext());

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay" />

    </android.support.design.widget.AppBarLayout>

    <include layout="@layout/content_main" />

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|end"
        android:layout_margin="@dimen/fab_margin"
        app:srcCompat="@android:drawable/ic_dialog_email" />

</android.support.design.widget.CoordinatorLayout>

content_main.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/layout_id"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context=".MainActivity"
    tools:showIn="@layout/activity_main"
    tools:layout_editor_absoluteY="81dp"
    tools:layout_editor_absoluteX="0dp">

</android.support.constraint.ConstraintLayout>

MainActivity.java

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        final Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        final ViewGroup layout = (ViewGroup) findViewById(R.id.layout_id);

        ScrollView sv = new ScrollView(this);
        final LinearLayout ll = new LinearLayout(this);
        ll.setOrientation(LinearLayout.VERTICAL);
        sv.addView(ll);

        TextView tv = new TextView(this);
        tv.setText("Dynamic layouts! Plain Text");
        ll.addView(tv);

        EditText et = new EditText(this);
        et.setText("This is edit text");
        ll.addView(et);

        Button b = new Button(this);
        b.setText("This is a dynamically added button");
        ll.addView(b);


        b.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub

                for(int i = 0; i < 20; i++) {
                    CheckBox ch = new CheckBox(v.getContext());
                    ch.setText("I'm dynamic! "+i);

                    ll.addView(ch);
                }
            }
        });


        //this.setContentView(sv);  // this causes the fab to fail
        layout.addView(sv);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();

            }
        });
    }