在Adapter Android中显示DialogFragment from按钮时出现问题



我想从适配器按钮中显示一个DialogFragment。我在适配器内部创建了一个DialogFragment类,我希望它在我按下按钮时显示对话框,但我得到了这个错误:

java.lang.ClassCastException: android.app.Application cannot be cast to androidx.appcompat.app.AppCompatActivity
at com.example.karate_manager.Adapters.AdapterMarket$1.onClick(AdapterMarket.java:106)

这是我的适配器:

public class AdapterMarket extends ArrayAdapter{
private FragmentManager fm;
Context context;
int item_Layaut;
ArrayList<Karateka> data;
ApiUtils apiUtils;
public AdapterMarket(@NonNull Context context, int resource, @NonNull ArrayList objects, FragmentManager fm) {
super(context, resource, objects);
this.context = context;
this.item_Layaut = resource;
this.data = objects;
this.fm = fm;
}
public void setData(MarketResponse data) {
if(data!=null){
this.data = data.getKaratekas();
this.notifyDataSetChanged();
}
}
@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
if (convertView == null) {
LayoutInflater layoutInflater = LayoutInflater.from(context);
convertView = layoutInflater.inflate(item_Layaut, parent, false);
}
String value = String.valueOf(data.get(position).getValue());
Button buttonValue = convertView.findViewById(R.id.item_button_value_karateka);
buttonValue.setText(value);
popupBidKarateka(buttonValue);
return convertView;
}
public void popupBidKarateka(Button buttonValue){
buttonValue.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
FragmentActivity activity = (FragmentActivity)(context);
fm = activity.getSupportFragmentManager();
DialogFragment newFragment = new BidKaratekaDialogFragment();
newFragment.show(fm, "bid" );
}
});
}
}

这是片段中的参考:

FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
adapterMarket = new AdapterMarket(getActivity().getApplicationContext(), R.layout.item_market_layout, marketResponse.getKaratekas(), fragmentManager);
public void onClick(View view) {
Application activity1 = (Application) view.getContext(); // bad
FragmentActivity activity = (FragmentActivity)(context); // context must come from FragmentActivity

//我假设FragmentActivity是调用适配器的类。

FragmentManager fm = activity.getSupportFragmentManager();
DialogFragment newFragment = new BidKaratekaDialogFragment();
newFragment.show(fm, "bid" );
}
});

一位智者说。。

即使在"活动"中,上下文也不总是"活动"。它可以是一个应用程序,也可以是另一个上下文的包装器。它是将上下文强制转换为活动几乎总是错误的。如果你绝对需要一个,您应该传入一个Activity作为参数,而不是上下文。或者更好的是,传入支持片段直接管理而不是活动,因为这就是你所需要的它为。

public AdapterMarket(@NonNull Context context, FragmentManager fm, int resource, @NonNull ArrayList objects) {
super(context, resource, objects);
this.context = context;
this.fm = fm;
this.item_Layaut = resource;
this.data = objects;
}

//比如,Afragment正在呼叫适配器。

AFragment.class
FM fm = getActivity.getSupportFM/getFM();
AdapterMarket market = new AdapterMarket(someContext, fm, ....) 

最新更新