java创建activity视图_java-动态创建的视图id始终为null-findviewbyid不起作用
我正在構建一個應用程序,其中有一個編輯文本字段,并從用戶那里獲取數據并將其存儲在數據庫中,它工作正常,現在我使用一個按鈕來動態創建另一個編輯文本字段(僅當用戶使用時才創建此字段現在,動態創建的字段的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()));
(此處數據是使用此代碼插入到數據庫中的,但是在嘗試查看數據時,應用程序崩潰了.)
總結
以上是生活随笔為你收集整理的java创建activity视图_java-动态创建的视图id始终为null-findviewbyid不起作用的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 我的世界手机版怎么扩大地图
- 下一篇: oracle查看语句执行历史,AWT查看