我必须将包含 3 个 editText 的 linearLayout 膨胀到另一个 linearLayout。我可以使用 linearLayout[] 数组来实现吗?
public class PurchaseVoucher extends Activity implements OnFocusChangeListener, OnClickListener{
LinearLayout[] row=new LinearLayout[30];
AutoCompleteTextView[] items=new AutoCompleteTextView[30];
EditText[] quants=new EditText[30];
EditText[] rates=new EditText[30];
TextView[] totals=new TextView[30];
Boolean[] flag=new Boolean[30];
EditText date;
Button save;
LinearLayout container;
int no;
int id;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.sale_purchase_vouch);
no=0;
for(int i=0;i<30;i++)
flag[i]=true;
save=(Button)findViewById(R.id.Save);
save.setText("Confirm Purchase");
LayoutInflater l=getLayoutInflater();
container=(LinearLayout)findViewById(R.id.container);
row[no]=(LinearLayout)l.inflate(R.layout.row, container);
items[no]=(AutoCompleteTextView)row[no].findViewById(R.id.item);
quants[no]=(EditText)row[no].findViewById(R.id.quant);
rates[no]=(EditText)row[no].findViewById(R.id.rate);
save.setOnClickListener(this);
quants[no].setOnFocusChangeListener(this);
flag[no]=false;
}
@Override
public void onFocusChange(View arg0, boolean arg1) {
// TODO Auto-generated method stub
if(flag[no+1]==true){
if(arg1==false){
no++;
LayoutInflater g=getLayoutInflater();
row[no]=(LinearLayout)g.inflate(R.layout.row, container);
items[no]=(AutoCompleteTextView)row[no].findViewById(R.id.item);
quants[no]=(EditText)row[no].findViewById(R.id.quant);
rates[no]=(EditText)row[no].findViewById(R.id.rate);
Log.d("detection", "Row is "+ no+ arg0.getId());
}
}
}
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Log.d("quant", quants[0].getText().toString()+" "+quants[0].getText().toString());
Log.d("item", items[1].getText().toString()+" "+quants[1].getText().toString());
Log.d("rate", rates[2].getText().toString()+" "+quants[2].getText().toString());
}
当我按下按钮在 logcat 中获取结果时,所有值都等于前 3 个 editText,即等于 items[0]、quants[0] 和 rates[0]。其次,onFocusChangeListener() 仅适用于预定义的第一个 linearLayout 中存在的 editText。
最佳答案
我认为一个更简单的方法来做你正在尝试的就是创建一个新的 LinearLayout
和你每次需要的 EditText
的数量。然后你也可以在那个时候将这些值添加到一个数组中。这样你就可以拥有无限数量的行,我认为它可以让你的代码更干净。也许像
@Override
public void onFocusChange(View arg0, boolean arg1)
{
if(flag[no+1]==true){ // not sure if this is needed
if(arg1==false){
no++;
LinearLayout ll = new LinearLayout(PurchaseVoucher.this);
for (int i= 0; i < noOfEditTextNeeded; i++)
{
EditText et = new EditText(PurchaseVoucher.this);
ll.addView(et);
}
container.addView(ll);
llArray.add(ll); // create a member variable ArrayList-- ArrayList<LinearLayout> = new ArrayList<LinearLayout>()
}
我还没有对此进行测试,因此可能需要进行调整,但对我来说这会更容易管理。我创建了一个 ArrayList
来保存 LinearLayout
,但您也可以为 EditText
或您需要的任何内容执行此操作。
关于android - 我可以通过数组定义多个 LinearLayouts 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18273597/