所以我有一個類在按下按鈕時動態添加文本字段和微調器。問題是添加的文本字段和按鈕沒有正確對齊。它在彼此頂部,但我希望它放在一起。我將方向設置爲「水平」,但不起作用。此外,項目列表不會顯示給添加的微調器。有人能幫我嗎?我是Android開發新手。謝謝。這是我的代碼。以編程方式點擊按鈕時添加EditText和Spinner
import java.util.ArrayList;
import java.util.List;
import android.os.Bundle;
import android.app.ActionBar.LayoutParams;
import android.app.Activity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Spinner;
public class AddField extends Activity {
private LinearLayout mLayout, mLayout2;
private EditText qty, price ;
private Button mButton;
private Spinner mspinner;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_field);
final List<String> list=new ArrayList<String>();
list.add("Male");
list.add("Female");
final String[] str={"Male","Female"};
mspinner = (Spinner) findViewById(R.id.itemSpin);
ArrayAdapter<String> adp1=new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1,list);
adp1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mspinner.setAdapter(adp1);
mLayout = (LinearLayout) findViewById(R.id.linearLayout);
mLayout2 = (LinearLayout) findViewById(R.id.linearLayout);
qty = (EditText) findViewById(R.id.inputQty);
price = (EditText) findViewById(R.id.inputPrice);
mButton = (Button) findViewById(R.id.button);
mButton.setOnClickListener(onClick());
}
private OnClickListener onClick() {
return new OnClickListener() {
@Override
public void onClick(View v) {
mLayout2.addView(createNewSpin(mspinner.getContext().toString()));
mLayout2.addView(createNewQty(qty.getText().toString()));
mLayout2.addView(createNewPrice(price.getText().toString()));
}
};
}
private Spinner createNewSpin(String text) {
final LayoutParams lparams = new LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
final Spinner spinner = new Spinner(this);
spinner.setLayoutParams(lparams);
return spinner;
}
private EditText createNewQty(String text) {
final LayoutParams lparams = new LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
final EditText editText = new EditText(this);
editText.setLayoutParams(lparams);
editText.setHint("Quantity");
return editText;
}
private EditText createNewPrice(String text) {
final LayoutParams paramss = new LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
final EditText editText2 = new EditText(this);
editText2.setLayoutParams(paramss);
editText2.setHint("Price");
return editText2;
}
我已經添加了導入。 – jajaja