2013-10-24 81 views
2

我如何點擊ViewPager中的項目。我想返回位置當前項目,我點擊。例如,我嘗試運行下一個代碼:如何點擊ViewPager中的項目

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

但沒有任何結果。我已爲ViewPager的佈局編寫了全部已編寫的選項。也許有人可以告訴我,我做錯了什麼?

+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() 
} 
} 
相關問題