public class MyAdapter extends BaseAdapter {
...
public View getView(int position, View convertView, ViewGroup parent) {
View view = mLayoutInflater.inflate(R.layout.my_listview_item, null);
TextView myTv = (TextView) view.findViewById(R.id.myTv);
myTv.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// I want to replace another fragment
}
});
return view;
}
我无法在stackoverflow中找到解决方案...
我可以替换一个片段吗?救救我..
答案 0 :(得分:2)
有两种方法可以从适配器类调用片段:
1)你可以为它创建一个界面。
2)您可以通过特定操作注册自己的BroadcastReceiver
。
点击按钮的直接调用片段不是一个好的,正确的,干净的方式。所以我只想为我的第二种方法发布答案。
按钮单击适配器类
context.sendBroadcast(new Intent("call.myfragment.action"))
这是android中的简单事情,就是发送广播消息。
urButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
context.sendBroadcast(new Intent("call.myfragment.action"))
}
});
现在,在您的活动中,您需要使用BroadcastReceiver
注册一个"call.myfragment.action"
,并在其内部调用您的片段:
context.registerReceiver(mBroadcastReceiver, new IntentFilter("call.myfragment.action")) // This code is in your Activity will be in onCreate() or in onResume() method.
BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
// Now just call your Fragment here now.
}
};
答案 1 :(得分:0)
您有两种方式:
1-将您的片段或活动传递给您的适配器并引用它。在onClick()
方法中,使用它来替换片段。
2-让BroadcastReceiver
替换片段。然后在onClick()
方法中,只需发送一个BroadCast。
答案 2 :(得分:0)
您可以使用片段管理器弹出或重新制作片段。 片段与行为有关,
FragmentTransaction trans = mStack.getInstance().beginTransaction();
trans.replace(R.id.fragment_container, mFragment,
mFragment.getCustomTag());
trans.addToBackStack(mFragment.getCustomTag())
.commitAllowingStateLoss();
getSupportFragmentManager().executePendingTransactions();
mStack.setTopFragment(mFragment, mFragment.getCustomTag());