【发布时间】:2021-11-05 13:10:34
【问题描述】:
在我的活动中,我尝试从一个类中调用一个方法,但它没有得到正确的值。 这是活动二:
int id = intent.getIntExtra("id", 0);
LayoutInflater inflater = getLayoutInflater();
View mainActivity = inflater.inflate(R.layout.activity_main, null);
LinearLayout eventsLayout = mainActivity.findViewById(R.id.eventsLayout);
Log.d("ACTIVITY_eventlayout", String.valueOf(eventsLayout)); // gives the layout perfectly
Event.RemoveSpecific(eventsLayout, id);
finish();
这是带有方法的类(事件):
public static void RemoveSpecific(LinearLayout layout, int id){
View event = layout.findViewById(id);
Log.d("INSIDE_removespecific", String.valueOf(event));// event is null
layout.removeView(event);
}
在我的 MainActivity 中它工作正常:
LinearLayout eventsLayout = findViewById(R.id.eventsLayout);
View event = eventsLayout.findViewById(id);
//Log.d("MAIN_event", String.valueOf(event1)); // gives it perfectly
eventsLayout.removeView(event);
我还在我的 MainActivity 中添加了这个视图,并使用 .setId(id) 为其提供正确的 ID。所以我的问题是,为什么我的类方法中的 View 为 null,而我从我的 activityTwo 传递了正确的 LinearLayout?
id 是从哪里来的?
我有一个包含 id、名称、日期和描述的 Event 类。此类还有一个名为 eventsList 的静态 ArrayList。每当用户创建一个新提醒时,我使用我的类创建一个新事件并给它一个 ID 为Event.eventsList().size()(将其添加到我的 eventsList [所以第一个事件 id 始终为 1]),然后我创建一个新视图和传递最近创建的事件详细信息并使用setId() 为其指定一个 id [1]。然后在这个视图中,我有一个按钮,它有一个 onClickListener,它将给定的视图 ID 和 LinearLayout(添加视图的位置)传递给我的 Event.removeSpecific() 方法。
应用流程:
用户单击 MainActivity 中的按钮以创建事件,然后单击按钮然后使用 startActivityForResult() 意图打开一个新 Activity,用户在其中输入事件的名称、描述和日期,然后我创建使用putExtra() 方法的意图,然后使用setResult(RESULT_OK, resultintent) 将数据发送回MainActivity。现在,当 MainActivity 取回数据时,我使用 .getStringExtra() 使用数据创建一个新的 Event 对象并将其添加到 may Event.eventsList ArrayList,然后我使用以下内容:
LayoutInflater inflater = getLayoutInflater();
View event_Exmaple = inflater.inflate(R.layout.event_example, null);
并用我得到的数据设置 textView,并使用 event_example.setId(Event.eventsList.size()) 给它一个 id。
之后,我将它添加到我的 LinearLayout(我已经在 MainActivity 中声明):
eventsLayout.addView(event_example)
现在我提到了 Event 类有一个日期字段。我用它来使用 AlarmManager 设置警报。使用 AlarmManager,我通过意图发送当前 Event 对象的数据,当用户收到通知时,它会打开一个新的 Activity,该 Activity 会获取给定的 Event 对象数据(使用intent.putExtra()'s),这就是用户点击的部分一个按钮。我想从 MainActivity XML 中的 LinearLayout 中删除给定的 Event 对象的 View。
【问题讨论】:
标签: java android android-studio android-linearlayout cardview