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

时间:2016-06-15 15:44:24

标签: android listview adapter

基本上我想要做的是:我的应用程序中有自定义列表适配器的列表视图。但我想根据适配器的调用活动更改TextLabel。我在活动中有三个列表,如产品列表,收藏夹和历史记录。那么我们可以通过任何方式调用(parentActivity)吗?

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

customListAdapter:

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;

};
}

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

1 个答案:

答案 0 :(得分:2)

调用适配器时,会传递活动上下文。您可以使用它来识别这样的调用活动

解决方案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
相关问题