我创建了一个复合控件,其中包含以下内容:
爪哇
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
被抛出。)
答案 0 :(得分:0)
当您致电loadViews()
时,小部件不会出现在那里。等到onFinishInflate()
。
答案 1 :(得分:0)
你永远不会在只接受Context参数的构造函数中膨胀你的视图,这意味着quantity.setText(...);将抛出NPE,因为在findViewById(...)中找不到数量;