我有Fragment
在RelativeLayout
中夸大了onCreateView()
。我在ActionBar
中有一个按钮,我想在每次点击时向视图添加EditText
窗口小部件。我制作了ArrayList
EditTexts
个EditText
,其中添加了自定义EditText
类。如何为ArrayList
中的所有OnTouchListener
字段充气?有没有办法通过引用数组的索引来膨胀。注意我最终想为每个领域添加public class SomeFragment extends Fragment {
private View v;
private List<EditText> editTextList = new ArrayList<EditText>();
private int n = 0;
private View.OnTouchListener TouchHandler;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
setHasOptionsMenu(true);
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater){
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.edit_actionbar, menu);
}
public boolean onOptionsItemSelected(MenuItem item){
switch(item.getItemId()){
case R.id.menu_item_add_text:
n=n+1;
editTextList.add(editText(n));
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private EditText editText(int id){
EditText editText = new EditText(getActivity());
editText.setId(id);
editText.setOnTouchListener(TouchHandler);
editTextList.add(editText);
return editText;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState) {
v = inflater.inflate(R.layout.edit_fragment, parent, false);
TouchHandler = new View.OnTouchListener() {
public boolean onTouch(View v, MotionEvent ev) {
// .......................
};
return v;
}
}
。
{{1}}
答案 0 :(得分:0)
全球维护一个柜台,
private int counter;
view.setOnClickListener(new OnClickListener){
@override
public void onClick(View view){
EditText editText = editTextList.get(counter);
// you can add the editText to the view you want
counter++;
}
}
希望这可以帮助你:)
答案 1 :(得分:0)
我最终做了这个问题的回答中提出的建议Adding array of textviews dynamically to linear layout。
在OnCreateView中:
ViewGroup.LayoutParams lp = new ViewGroup.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
pairs=new EditText[9];
for(int l=0; l<9; l++)
{
pairs[l] = new EditText(getActivity() );
pairs[l].setTextSize(15);
pairs[l].setLayoutParams(lp);
pairs[l].setId(l);
pairs[l].setText((l + 1));
pairs[l].setFocusableInTouchMode(false);
pairs[l].setOnTouchListener(new MyTouchListener());
}
在onOptionsItemselected:
private int counter;
case R.id.menu_item_add_text:
myLayout.addView(pairs[counter]);
counter++;
return true;