2

我如何单击 ViewPager 中的项目。我想返回位置当前项目,我点击。例如,我尝试运行下一个代码:

pager.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
        Toast toast = Toast.makeText(getApplicationContext(),
            pager.getCurrentItem(), Toast.LENGTH_SHORT);
        toast.show();
        }
    });

但什么也没发生。我已经在 ViewPager 的布局中编写了 onClick 选项。也许有人可以告诉我,我做错了什么?

4

1 回答 1

3

为什么不将 onclick 侦听器添加到片段中。然后只是广播一个意图。

public class Your extends  Fragment
{
 @Override
 public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle  savedInstanceState) {
    super.onCreateView(inflater, container, savedInstanceState);
    View inflatedView = inflater.inflate(R.layout.customlayout, null);
    inflatedView.setOnClickListener(new OnClickListener() {
    public void onClick(View v) {
    Intent temp =  new Intent("anything.com.com.CHECK_CURRENT_PAGE_ITEM");
    getActivity().sendBroadcast(temp);
    }
    });
    }
}

然后在您的主要活动中注册一个广播接收器

public class Youractivity extends FragmentActivity
{

private BroadcastReceiver clickedReceiver = new BroadcastReceiver() {

    @Override
    public void onReceive(Context context, Intent intent) {
        Toast toast = Toast.makeText(getApplicationContext(),
        pager.getCurrentItem(), Toast.LENGTH_SHORT);
    }
};

@Override
public void onCreate()
{
...
   registerBroadcstReceiver(clickedReceiver, new IntentFilter("anything.com.com.CHECK_CURRENT_PAGE_ITEM"))

...
}
@Override
public void onDestroy()
{
unregisterBroadcastReceiver()
}
}
于 2013-10-24T09:13:54.660 回答