我已經動態創建微調和按鈕使用佈局充氣器。當我嘗試用按鈕點擊刪除這些,我得到空指針異常錯誤,當我運行it.Here程序只是崩潰是我的代碼:Android刪除動態創建的微調和按鈕,點擊一個按鈕
public class MainActivity extends FragmentActivity implements OnClickListener{
SampleAlarmReceiver alarm = new SampleAlarmReceiver();
static EditText startTime;
static EditText endTime;
static EditText startDate;
static EditText EndDate;
View buttonRem;
Spinner spinnerNew;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startTime = (EditText)findViewById(R.id.EditTextST);
startDate = (EditText)findViewById(R.id.editTextSD);
//Set up Click Listener for all Buttons
View buttonAdd = findViewById(R.id.button1);
buttonAdd.setOnClickListener(this);
buttonRem = findViewById(R.id.buttonRem);
buttonRem.setOnClickListener(this);
}
public void onClick(View v)
{
switch(v.getId()){
case (R.id.button1):
RelativeLayout rootLayout = (RelativeLayout)findViewById(R.id.main_layout);
//use layout inflater to create 'spinnerNew' on the fly
final LayoutInflater spnInflater=(LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
spinnerNew = (Spinner)spnInflater.inflate(R.layout.extra_spinner, null);
rootLayout.addView(spinnerNew);
//move the dynamic spinner to different position
RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams)spinnerNew.getLayoutParams();
params.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
params.addRule(RelativeLayout.BELOW, R.id.spinner1);
spinnerNew.setLayoutParams(params); //causes layout update
//use layout inflater to create 'remove button' on the fly
final LayoutInflater btnInflater=(LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
buttonRem = (Button)btnInflater.inflate(R.layout.btn_remove, null);
rootLayout.addView(buttonRem);
//move the dynamic button to different position
RelativeLayout.LayoutParams params1 = (RelativeLayout.LayoutParams)buttonRem.getLayoutParams();
params1.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
params1.addRule(RelativeLayout.ALIGN_BOTTOM, R.id.spinnerNew);
break;
case(R.id.buttonRem):
//spinnerNew.setVisibility(View.GONE); //does nothing
//buttonRem.setVisibility(View.GONE);//does nothing
ViewGroup layout = (ViewGroup) spinnerNew.getParent();
if(null!=layout)
layout.removeView(spinnerNew);//does nothing
break;
}
}
你在哪裏設置'buttonRem'的onClickListener? – Apoorv
@Apoorv,對不起。請看我編輯的代碼。現在,我得到Nullpointer異常錯誤。 – Gantavya
你在哪一行獲取NLP –