如何点击ViewPager中的项目。我想返回位置当前项目,我点击。例如,我尝试运行下一个代码:
pager.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Toast toast = Toast.makeText(getApplicationContext(),
pager.getCurrentItem(), Toast.LENGTH_SHORT);
toast.show();
}
});
但没有任何事情发生。我已经为ViewPager编写了onClick in layout的选项。也许有人可以告诉我,我做错了什么?
答案 0 :(得分: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()
}
}