Android: How do you create an EditText field in java class

只愿长相守 提交于 2019-12-24 03:24:13

问题


I was just wondering how to create an editText field on the click of a button. Is it possible? I cant find anything online. If anyone knows how to do this please answer! and if you know how to configure the size, placement ect also include that information.


回答1:


import android.widget.Button;
import android.widget.EditText;    
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;

LinearLayout mLinearLayout = new LinearLayout(this);
mLinearLayout = (LinearLayout)findViewById(R.id.mylinearlayout);

Button lButton = (Button)findViewById(R.id.mybtnid);
lButton.setOnClickListener(new View.OnClickListener() {
    public void onClick(View arg0) {
        EditText lEditText = new EditText(this);
        lEditText .setLayoutParams(
            new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, 
                                          LayoutParams.WRAP_CONTENT));
        lEditText.SetText("Text Here");
        mLinearLayout.addView(lEditText);
        lEditText.setWidth(width);     // change width
        lEditText.setHeight(height);   // change height
        lEditText.setX(<x value>);     // set absolute position of x
        lEditText.setY(<y value>);     // set absolute position of y
    }
}

also you can use

int X = 50; // Arbitrary values - use whatever you want
int Y = 100;

lEditText.setPadding(X, Y, 0, 0);  // set x and y using padding



回答2:


Set it invisible where you want the EditText? Can be one of the first things you do in your Activity. And use the button to set it visible.

EditText edtext = (EditText) findViewById(R.id.edtext);
edtext.setVisibility(View.GONE);
...
button.setOnClickListener(new OnClickListener()
{
        @Override
        public void onClick(View view) 
        {
            edtext.setVisibility(View.VISIBLE);
        }
    });

You really should do some basic work first before requesting help here, regarding size and placement etc, which is done in xml mostly.




回答3:


Better still don't set it to invisible but to set it to "gone" you do this in the xml by adding the line

android:visibility="gone"<br/>

If you add

android:visibility="visible"<br/>

the EditText will still take up space but be invisible whereas gone means that not only is is invisible but it is gone and not taking up space



来源:https://stackoverflow.com/questions/9857232/android-how-do-you-create-an-edittext-field-in-java-class

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