Creating EditText Dynamically in Android

ぃ、小莉子 提交于 2019-12-20 10:23:58

问题


I am working on a application where I have to create multiple EditText and Spinner dynamically. So I started looking for the solution as I don't have permission to use Invisible property in XML file. I searched a lot and got a very few examples only on stackoverflow . I follow them and created this program.

       **MainActivity.java code** 

public class MainActivity extends Activity {

        RelativeLayout containerLayout;
        static int totalEditTexts = 0;
        Button button;
        Context context;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    containerLayout = (RelativeLayout)findViewById(R.id.relative1);
    button = (Button)findViewById(R.id.button1);

    button.setOnClickListener(new View.OnClickListener() {

    @Override
    public void onClick(View arg0) {
    // TODO Auto-generated method stub

     totalEditTexts++;
     if (totalEditTexts > 100)
    return;
    EditText editText = new EditText(getBaseContext());
    containerLayout.addView(editText);
      editText.setGravity(Gravity.RIGHT);
     RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) editText.getLayoutParams();
      layoutParams.width = RelativeLayout.LayoutParams.MATCH_PARENT;
        layoutParams.setMargins(23, 34, 0, 0);
     // RelativeLayout.LayoutParams()
       editText.setLayoutParams(layoutParams);
    //if you want to identify the created editTexts, set a tag, like below
     editText.setTag("EditText" + totalEditTexts);
                }
            });

} }

When I am running this code, It is creating the EditText when the button got clicked. But only one time. I don't know what is happening after that. whether it is creating new EditText or it is overlapping the old one, otherwise it is not creating more than one EditText.

Can anyone explain me what I have to do now to resolve this issue.


回答1:


I have Solved my Problem by simply replacing RelativeLayout with LinearLayout




回答2:


The problem with using RelativeLayout and adding stuff dynamically is that if you don't set the relative position of the view, it overlaps each other. So when you click and add new views, the new views are being added but they overlap each other. But adding a LinearLayout, the views are visible below one another as you can set the orientation to vertical.



来源:https://stackoverflow.com/questions/24056649/creating-edittext-dynamically-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!