问题
在debug的时候发现我的 labItem 对象里面的属性啥的都是空,这是为啥呢?
代码如下:
你现在是android高手。要求详细说明,举例代码,保证正确可运行,并支持当前主流的android版本。
/**
* 选择Lab模式所需要的东西
*/
public class LabItem {
/**
* 组件背景
*/
@DrawableRes
int background;
/**
* 跳转的类
*/
Class<?> jumpingClass;
/**
* 模式名称
*/
String title;
/**
* 模式描述
*/
String desc;
/**
* 点击事件
*/
View.OnClickListener listener = new View.OnClickListener() {
@Override
public void onClick(View view) {
}
};
public LabItem() {
}
public LabItem(String title, String desc) {
new LabItem( title, desc,null);
}
public LabItem(String title, String desc, View.OnClickListener listener) {
this.title = title;
this.desc = desc;
this.listener = listener;
// 默认的bg
this.background = R.drawable.app_ability_item_bg;
}
public LabItem(int background, int picResource, Class<?> jumpingClass, String title, String desc) {
this.background = background;
this.jumpingClass = jumpingClass;
this.title = title;
this.desc = desc;
}
// 跳转的类
public Class<?> getJumpingClass() {
return jumpingClass;
}
}
我再通过如下的代码调用:
private ArrayList<LabItem> initLabsList() {
ArrayList<LabItem> labItems = new ArrayList<>();
LabItem labItem = new LabItem(getString(R.string.zego_sr_title), getString(R.string.zego_sr_des));
labItems.add(labItem);
return labItems;
}
private void initLabRecycleView() {
rvLabItem = findViewById(R.id.rv_lab_item);
ArrayList<LabItem> labItems = initLabsList();
LabItemAdapter adapter = new LabItemAdapter(labItems);
// 适配
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
rvLabItem.setAdapter(adapter);
rvLabItem.setLayoutManager(layoutManager);
adapter.setListener(holder -> {
if (holder instanceof LabItem) {
if (shouldJumpToNextActivity) {
return;
}
shouldJumpToNextActivity = true;
// TODO: 2023/9/1 待定跳转
// startActivity(new Intent(KTVClassActivity.this, ((LabItemViewHolder) holder).jumpClass));
}
});
}
为什么 ArrayList labItems = initLabsList(); 里面的数据都是null呢?
解决
LabItem类有多个构造函数,但在LabItem(String title, String desc)构造函数中,没有正确调用其他构造函数来初始化LabItem对象的属性。因此,当你调用initLabsList()方法时,返回的ArrayList中的LabItem对象都是未初始化的,因此它们的属性值都为null。
为了解决这个问题,你可以在LabItem(String title, String desc)构造函数中调用其他构造函数来初始化属性。修改LabItem(String title, String desc)构造函数的代码如下:
public LabItem(String title, String desc) {
this(title, desc, null);
}
这样,当你调用initLabsList()方法时,LabItem对象将会正确初始化,并且ArrayList中的LabItem对象将包含正确的属性值。
所以是我傻了~写了那么久的代码,这种低级错误都会犯。