如何知道哪个 activity 正在调用自定义列表适配器?

how to know which activity is calling custom list adapter?

基本上我想做的是:我的应用程序中有一个带有自定义列表适配器的列表视图。但是我想根据适配器的调用 activity 更改一个 TextLabel。我在 activity 中有三个列表,例如产品列表、收藏夹和历史记录。那么有什么办法可以让我们调用(parentActivity)?

简单的解决方案是为所有列表设计不同的布局,但我不想要那种冗余代码。

自定义列表适配器:

public class CustomListAdapter extends BaseAdapter {

private final Context context;
private  ArrayList<Product> products=new ArrayList<>() ;

public CustomListAdapter(Context context, ArrayList<Product> product) {


    this.context=context;
    this.products=product;

}

@Override
public int getCount() {
    return products.size();
}

@Override
public Object getItem(int position) {
    return null;
}

@Override
public long getItemId(int position) {
    return 0;
}

public View getView(int position, View view, ViewGroup parent) {
    LayoutInflater inflater=(LayoutInflater) context
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View rowView=inflater.inflate(R.layout.product_list_item, null, true);

    TextView title = (TextView) rowView.findViewById(R.id.product_title);
    //TextView url = (TextView) rowView.findViewById(R.id.product_url);
    TextView createDate = (TextView) rowView.findViewById(R.id.product_create_date);
    ImageView icon=(ImageView)rowView.findViewById(R.id.imageArrow);


  ...........
    title.setText(productInfo.getTitle());

    createDate.setText("Created Date: "+productInfo.getCreatedDate());
    icon.setImageResource(R.drawable.go_right);
    return rowView;

};
}

所以我想更改历史列表的创建日期和修改日期。

当您调用适配器时,您会传递 activity 上下文。您可以使用它来识别呼叫 activity 像这样

解决方案 1

String currentActivity = this.context.getClass().getName();
if(!TextUtils.isEmpty(currentActivity)) { 
    if(currentActivity.contains("com.example.activity1")){
        // do this
    }
    else if(currentActivity.contains("com.example.activity2")){
        // do that
    }
}

解决方案 2

if(this.context instanceof Activity1){
    // do this
}
else if(this.context instanceof Activity2){
    // do that
}

注意:这就是您调用适配器的方式

CustomListAdapter myCustomListAdapter = new CustomListAdapter(this, myProducts); // In activity

CustomListAdapter myCustomListAdapter = new CustomListAdapter(getActivity(), myProducts); // In Fragment