在Android中创建动态的EditText [英] Creating EditText Dynamically in Android
问题描述
我工作的一个应用程序,我要创建多个
的EditText
和微调动态。于是我开始寻找
该解决方案,因为我没有权限使用隐身
属性的XML文件。我搜索了很多,得到了非常少
仅在计算器的。我跟着他们,并创造了这个计划。
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);
}
});
}
}
} }
当我运行这个code,它是创造得到的EditText单击按钮时。但仅一次。我不知道什么是之后发生的事情。无论是创建新的EditText或者是重叠的旧人,否则就不是创建多个的EditText。
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.
推荐答案
我已经简单地更换解决我的问题的 RelativeLayout的与的LinearLayout 的
I have Solved my Problem by simply replacing RelativeLayout with LinearLayout
这篇关于在Android中创建动态的EditText的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!