【发布时间】:2019-07-31 19:04:01
【问题描述】:
我正在构建一个应用程序,其中我有一个编辑文本字段并从用户获取数据并将其存储在数据库中它工作正常,现在我使用一个按钮动态创建另一个编辑文本字段(此字段仅创建如果用户希望通过单击按钮),现在动态创建的字段的 id 始终为 null 并显示错误。我将分享我的代码。
对于动态编辑文本:
//update start
final LinearLayout ll = (LinearLayout) findViewById(R.id.li1);
mContext = getApplicationContext();
RelativeLayout.LayoutParams params1 = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
//update end
et1 = new EditText(AddTask.this);
et1.setLayoutParams(new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT,
RelativeLayout.LayoutParams.WRAP_CONTENT));
et1.setHint("Enter Item Name");
et1.setId(View.generateViewId());
//updates
layout.addView(et1, params1);
ll.addView(layout);
访问它:
EditText item_name = (EditText) findViewById(et1.getId());
运行应用程序时,我在这一行出现错误,像这样。
日志猫:
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
Caused by: java.lang.NullPointerException:
Attempt to invoke virtual method 'int android.widget.EditText.getId()' on a null object reference
更新:
这个方法我也试过了,还是没用,
EditText item_name = (EditText) findViewById(getResources().getIdentifier(String.valueOf(et1.getId()), "id", getPackageName()));
(此处数据是使用此代码插入到数据库中的,但在尝试查看数据时,应用程序崩溃了。)
【问题讨论】:
-
视图中不存在新的et1字段,因为它是动态创建的,所以可以直接使用et1字段而不需要从findViewById获取。
-
你能推荐一个@SushilMittal 的代码
-
当两者都是 EditText 那么你为什么要使用这一行进行投射,EditText item_name = (EditText) findViewById(et1.getId());
-
首先 edittext 用于从用户获取数据并将其存储在 db 中,稍后更新用户打开相同的活动并在 edittext 中进行更改(其中 edittext 视图位于动态创建一个),所以我就是这样投射的。
标签: java android-edittext dynamic-view