Что еще мне нужно, чтобы вызвать мой составной контроль? - PullRequest
0 голосов
/ 22 ноября 2011

Я создал составной элемент управления со следующим:

Java

public class QuantityBox extends LinearLayout 
{
    private TextView partNmbr;
    private Button decrease;
    private Button increase;
    private EditText quantity;
    private int qty;

    public QuantityBox(Context context)
    {
        super(context);

        // load views
        loadViews();
    }

    /**
     * This constructor is necessary in order to use this compound
     * control in an XML layout.
     * @param context Application context
     * @param attrs
     */
    public QuantityBox(Context context, AttributeSet attrs)
    {
        super(context, attrs);

        // inflate the view we created
        LayoutInflater inflater = LayoutInflater.from(context);
        inflater.inflate(R.layout.quantity_box, this);

        // load views
        loadViews();
    }

    /**
     * Load the views created from the constructor
     */
    private void loadViews()
    {
        this.qty = 1;

        partNmbr = (TextView) findViewById(R.id.tvPartNmbr);
        decrease = (Button) findViewById(R.id.btnDecrease);
        increase = (Button) findViewById(R.id.btnIncrease);
        quantity = (EditText) findViewById(R.id.etQty);

        // set initial text
        quantity.setText(this.qty);

        decrease.setOnClickListener(new OnClickListener(){

            @Override
            public void onClick(View arg0) {
                // decrease quantity
                qty--;

                // update view
                quantity.setText(qty);
            }

        });

        increase.setOnClickListener(new OnClickListener(){

            @Override
            public void onClick(View arg0) {
                // increase quantity
                qty++;

                // update view
                quantity.setText(qty);
            }

        });
    }
}

XML

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal" >

    <TextView
        android:id="@+id/tvPartNmbr"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginRight="5dp"
        />
    <Button
        android:id="@+id/btnDecrease"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginRight="5dp"
        android:text="-"
        />
    <EditText
        android:id="@+id/etQty"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginRight="5dp"
        />  
    <Button
        android:id="@+id/btnIncrease"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginRight="5dp"
        android:text="+"
        />
</LinearLayout>

И я пытаюсь создать это здесь, программно-союзник:

    public class CustomHeaderActivity extends Activity {
        /** Called when the activity is first created. */
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.custom_title_bar);

            QuantityBox qb = new QuantityBox(this);
        }
}

Почему это не работает? Я пропускаю шаг? (NullPointerException брошен.)

Ответы [ 2 ]

0 голосов
/ 22 ноября 2011

Вы никогда не будете раздувать свое представление в конструкторе, который принимает только аргумент Context, то есть количество .setText (...); сгенерирует NPE, потому что количество не было найдено в findViewById (...);

0 голосов
/ 22 ноября 2011

Виджетов не будет там к тому времени, когда вы позвоните loadViews().Подождите, пока onFinishInflate().

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...