我有应用程序,它使用谷歌SlidingTabLayout.And每个标签标题是不同的位置名称,它是数据库驱动的。在应用程序中我使用gcm推送通知和之前和notifiactions是关于不同的位置,保持locationId跟踪共享首选项的帮助。从通知中打开MainActivity时,我需要转到特定的位置选项卡。请帮我 这是用于声明选项卡的MainActivity代码
try {
SQLiteDatabase sqLiteDatabase;
sqLiteDatabase = fhiSqLiteDatabase.getReadableDatabase();
String readQuery = "SELECT * FROM " + DatabaseConstants.TableLocation.TABLE_NAME;
Cursor cursor = sqLiteDatabase.rawQuery(readQuery, null);
if (cursor.moveToFirst()) {
Log.d("My Log", "Inside Cursor");
locationCount = 0;
do {
Log.d("My Log", "Inside Cursor, Inside do");
try {
String location = cursor.getString(cursor.getColumnIndex(DatabaseConstants.TableLocation.COLUMN_LOCATION_NAME));
Log.d(Constants.LOG_TAG, " Location " + location);
Titles[locationCount] = location;
locationCount++;
Log.d(Constants.LOG_TAG, Titles[locationCount].toString());
} catch (Exception e) {
Log.d("My Log", e.toString());
}
Log.d("My Log", Titles[locationCount]);
}
while (cursor.moveToNext());
}
} catch (Exception e) {
Log.d("My Log", e.toString());
}
Numboftabs = locationCount;
// Creating The ViewPagerAdapter and Passing Fragment Manager, Titles fot the Tabs and Number Of Tabs.
adapter = new ViewPagerAdapter(getSupportFragmentManager(), Titles, Numboftabs);
// Assigning ViewPager View and setting the adapter
pager = (ViewPager) findViewById(R.id.pager);
pager.setAdapter(adapter);
// Assiging the Sliding Tab Layout View
tabs = (SlidingTabLayout) findViewById(R.id.tabs);
tabs.setDistributeEvenly(true); // To make the Tabs Fixed set this true, This makes the tabs Space Evenly in Available width
// Setting Custom Color for the Scroll bar indicator of the Tab View
tabs.setCustomTabColorizer(new SlidingTabLayout.TabColorizer() {
@Override
public int getIndicatorColor(int position) {
return getResources().getColor(R.color.tabsScrollColor);
}
});
// Setting the ViewPager For the SlidingTabsLayout
tabs.setViewPager(pager);
用户通知由方法sendNotification
处理 private void sendNotification(int planId,String notification,int updateId)
{
if(updateId==0)
{
Cursor cursor=fhiSqLiteDatabase.getAllBatchPlanDetails(planId);
sharedPreferencesToday = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
if (cursor != null && cursor.moveToFirst()) {
int locationId=cursor.getInt(cursor.getColumnIndex(DatabaseConstants.TableTourBatchPlan.COLUMN_LOCATION_ID));
Log.d(Constants.LOG_TAG, "Count Update item is for location Id : "+locationId);
SharedPreferences.Editor editor = sharedPreferencesToday.edit();
editor.putInt(locationIdShared,locationId);
editor.commit();
}
Log.d(Constants.LOG_TAG," User Notification For Cont Update ");
Intent resultIntent = new Intent(this, MainActivity.class);
resultIntent.putExtra("msg", notification);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
// Adds the back stack
stackBuilder.addParentStack(MainActivity.class);
// Adds the Intent to the top of the stack
stackBuilder.addNextIntent(resultIntent);
// Gets a PendingIntent containing the entire back stack
PendingIntent resultPendingIntent =
stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder mNotifyBuilder;
NotificationManager mNotificationManager;
mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mNotifyBuilder = new NotificationCompat.Builder(this)
.setContentTitle("FHI")
.setContentText(notification)
.setNumber(++countNum)
.setSmallIcon(R.drawable.group_38_std)
.setTicker("FHI :New Count Update ")
;
// Set pending intent
mNotifyBuilder.setContentIntent(resultPendingIntent);
// Set Vibrate, Sound and Light
int defaults = 0;
defaults = defaults | Notification.DEFAULT_LIGHTS;
defaults = defaults | Notification.DEFAULT_VIBRATE;
defaults = defaults | Notification.DEFAULT_SOUND;
mNotifyBuilder.setDefaults(defaults);
// Set the content for Notification
//mNotifyBuilder.setContentText(diff + " message: " + notification);
mNotifyBuilder.setContentText(notification);
// Set autoCancel
mNotifyBuilder.setAutoCancel(true);
// Post a notification
mNotificationManager.notify(notifyIdCount, mNotifyBuilder.build());
}
}
在此之后我更改了slidingTabLayout以获取选项卡以在单击用户通知时获得选定,更改方法是onAttachedToWindow()&私有类TabClickListener实现OnClickListener
public class SlidingTabLayout extends HorizontalScrollView
{
/**
* Allows complete control over the colors drawn in the tab layout. Set with
* {@link #setCustomTabColorizer(TabColorizer)}.
*/
public interface TabColorizer {
/**
* @return return the color of the indicator used when {@code position} is selected.
*/
int getIndicatorColor(int position);
}
private static final int TITLE_OFFSET_DIPS = 24;
private static final int TAB_VIEW_PADDING_DIPS = 16;
private static final int TAB_VIEW_TEXT_SIZE_SP = 12;
private static final int TAB_VIEW_NOTIFICATION_TEXT_SIZE_SP=10;
private int mTitleOffset;
private int mTabViewLayoutId;
private int mTabViewTextViewId;
private boolean mDistributeEvenly;
TextView textViewUnreadMessages;
private ViewPager mViewPager;
private SparseArray<String> mContentDescriptions = new SparseArray<String>();
private ViewPager.OnPageChangeListener mViewPagerPageChangeListener;
private final SlidingTabStrip mTabStrip;
public SlidingTabLayout(Context context)
{
this(context, null);
}
public SlidingTabLayout(Context context, AttributeSet attrs)
{
this(context, attrs, 0);
}
public SlidingTabLayout(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
// Disable the Scroll Bar
setHorizontalScrollBarEnabled(false);
// Make sure that the Tab Strips fills this View
setFillViewport(true);
mTitleOffset = (int) (TITLE_OFFSET_DIPS * getResources().getDisplayMetrics().density);
mTabStrip = new SlidingTabStrip(context);
addView(mTabStrip, LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
}
/**
* Set the custom {@link TabColorizer} to be used.
*
* If you only require simple custmisation then you can use
* {@link #setSelectedIndicatorColors(int...)} to achieve
* similar effects.
*/
public void setCustomTabColorizer(TabColorizer tabColorizer) {
mTabStrip.setCustomTabColorizer(tabColorizer);
}
public void setDistributeEvenly(boolean distributeEvenly) {
mDistributeEvenly = distributeEvenly;
}
/**
* Sets the colors to be used for indicating the selected tab. These colors are treated as a
* circular array. Providing one color will mean that all tabs are indicated with the same color.
*/
public void setSelectedIndicatorColors(int... colors) {
mTabStrip.setSelectedIndicatorColors(colors);
}
/**
* Set the {@link android.support.v4.view.ViewPager.OnPageChangeListener}. When using {@link SlidingTabLayout} you are
* required to set any {@link android.support.v4.view.ViewPager.OnPageChangeListener} through this method. This is so
* that the layout can update it's scroll position correctly.
*
* @see android.support.v4.view.ViewPager#setOnPageChangeListener(android.support.v4.view.ViewPager.OnPageChangeListener)
*/
public void setOnPageChangeListener(ViewPager.OnPageChangeListener listener) {
Log.d(Constants.LOG_TAG," To check Tab Change setOnPageChangeListener(ViewPager.OnPageChangeListener listener) ");
mViewPagerPageChangeListener = listener;
}
/**
* Set the custom layout to be inflated for the tab views.
*
* @param layoutResId Layout id to be inflated
* @param textViewId id of the {@link android.widget.TextView} in the inflated view
*/
public void setCustomTabView(int layoutResId, int textViewId) {
mTabViewLayoutId = layoutResId;
mTabViewTextViewId = textViewId;
}
/**
* Sets the associated view pager. Note that the assumption here is that the pager content
* (number of tabs and tab titles) does not change after this call has been made.
*/
public void setViewPager(ViewPager viewPager) {
mTabStrip.removeAllViews();
mViewPager = viewPager;
if (viewPager != null) {
viewPager.setOnPageChangeListener(new InternalViewPagerListener());
populateTabStrip();
}
}
/**
* Create a default view to be used for tabs. This is called if a custom tab view is not set via
* {@link #setCustomTabView(int, int)}.
*/
protected TextView createDefaultTabView(Context context) {
View v = LayoutInflater.from(context).inflate(R.layout.tab_loc_notification, null);
TextView textView = new TextView(context);
textView.setGravity(Gravity.CENTER);
textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, TAB_VIEW_TEXT_SIZE_SP);
textView.setTextColor(Color.WHITE);
textView.setTypeface(Typeface.DEFAULT_BOLD);
textView.setLayoutParams(new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
TypedValue outValue = new TypedValue();
getContext().getTheme().resolveAttribute(android.R.attr.selectableItemBackground,
outValue, true);
textView.setBackgroundResource(outValue.resourceId);
textView.setAllCaps(false);
int padding = (int) (TAB_VIEW_PADDING_DIPS * getResources().getDisplayMetrics().density);
textView.setPadding(padding, padding, padding, padding);
return textView;
}
protected TextView createDefaultTabViewNotification(Context context)
{
TextView textViewNotification=new TextView(context);
textViewNotification.setGravity(Gravity.RIGHT);
textViewNotification.setTextSize(TypedValue.COMPLEX_UNIT_SP, TAB_VIEW_NOTIFICATION_TEXT_SIZE_SP);
textViewNotification.setTextColor(Color.WHITE);
textViewNotification.setBackgroundDrawable(getContext().getResources().getDrawable(R.drawable.badge_std_circle));
textViewNotification.setLayoutParams(new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
TypedValue outValue = new TypedValue();
getContext().getTheme().resolveAttribute(android.R.attr.selectableItemBackground,
outValue, true);
textViewNotification.setAllCaps(false);
int padding = (int) (TAB_VIEW_PADDING_DIPS * getResources().getDisplayMetrics().density);
textViewNotification.setPadding(padding, padding, padding, padding);
return textViewNotification;
}
private void populateTabStrip() {
final PagerAdapter adapter = mViewPager.getAdapter();
final OnClickListener tabClickListener = new TabClickListener();
for (int i = 0; i < adapter.getCount(); i++) {
View tabView = null;
TextView tabTitleView = null;
if (mTabViewLayoutId != 0) {
// If there is a custom tab view layout id set, try and inflate it
tabView = LayoutInflater.from(getContext()).inflate(mTabViewLayoutId, mTabStrip,
false);
tabTitleView = (TextView) tabView.findViewById(mTabViewTextViewId);
}
if (tabView == null) {
tabView = createDefaultTabView(getContext());
}
if (tabTitleView == null && TextView.class.isInstance(tabView)) {
tabTitleView = (TextView) tabView;
}
if (mDistributeEvenly) {
LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) tabView.getLayoutParams();
lp.width = 0;
lp.weight = 1;
}
tabTitleView.setText(adapter.getPageTitle(i));
tabView.setOnClickListener(tabClickListener);
String desc = mContentDescriptions.get(i, null);
if (desc != null) {
tabView.setContentDescription(desc);
}
mTabStrip.addView(tabView);
if (i == mViewPager.getCurrentItem()) {
tabView.setSelected(true);
}
}
}
public void setContentDescription(int i, String desc)
{
mContentDescriptions.put(i, desc);
}
@Override
protected void onAttachedToWindow()
{
super.onAttachedToWindow();
final String MyPREFERENCES = "MyPrefs" ;
String dateTimeToolbarTitle="DateTime";
String locationIdShared="LocationId";
SharedPreferences sharedPreferencesToday =getContext().getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
int locationId=sharedPreferencesToday.getInt(locationIdShared,1);
if (mViewPager != null) {
// scrollToTab(locationId-1,0);
mViewPager.setCurrentItem(locationId-1,true);
//smoothScrollTo(locationId - 1, locationId - 1);
// scrollTo(locationId - 1, locationId - 1);
//mViewPager.setCurrentItem(locationId-1);
//scrollToTab(mViewPager.getCurrentItem(),locationId-1);
MainActivity.fillDataToTourPoint(locationId);
}
}
private void scrollToTab(int tabIndex, int positionOffset)
{
final int tabStripChildCount = mTabStrip.getChildCount();
if (tabStripChildCount == 0 || tabIndex < 0 || tabIndex >= tabStripChildCount) {
return;
}
View selectedChild = mTabStrip.getChildAt(tabIndex);
if (selectedChild != null) {
int targetScrollX = selectedChild.getLeft() + positionOffset;
if (tabIndex > 0 || positionOffset > 0) {
// If we're not at the first child and are mid-scroll, make sure we obey the offset
targetScrollX -= mTitleOffset;
}
scrollTo(targetScrollX, 0);
}
}
private class InternalViewPagerListener implements ViewPager.OnPageChangeListener
{
private int mScrollState;
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
int tabStripChildCount = mTabStrip.getChildCount();
if ((tabStripChildCount == 0) || (position < 0) || (position >= tabStripChildCount)) {
return;
}
mTabStrip.onViewPagerPageChanged(position, positionOffset);
View selectedTitle = mTabStrip.getChildAt(position);
int extraOffset = (selectedTitle != null)
? (int) (positionOffset * selectedTitle.getWidth())
: 0;
scrollToTab(position, extraOffset);
if (mViewPagerPageChangeListener != null) {
mViewPagerPageChangeListener.onPageScrolled(position, positionOffset,
positionOffsetPixels);
}
}
@Override
public void onPageScrollStateChanged(int state)
{
Log.d(Constants.LOG_TAG," To check Tab Change onPageScrollStateChanged(int state)");
mScrollState = state;
if (mViewPagerPageChangeListener != null) {
mViewPagerPageChangeListener.onPageScrollStateChanged(state);
}
}
@Override
public void onPageSelected(int position) {
if (mScrollState == ViewPager.SCROLL_STATE_IDLE) {
mTabStrip.onViewPagerPageChanged(position, 0f);
scrollToTab(position, 0);
}
for (int i = 0; i < mTabStrip.getChildCount(); i++) {
mTabStrip.getChildAt(i).setSelected(position == i);
}
if (mViewPagerPageChangeListener != null) {
mViewPagerPageChangeListener.onPageSelected(position);
}
}
}
private class TabClickListener implements OnClickListener
{
final PagerAdapter adapter = mViewPager.getAdapter();
ListView updateWidgetListView;
public static final String MyPREFERENCES = "MyPrefs" ;
String dateTimeToolbarTitle="DateTime";
String locationIdShared="LocationId";
@Override
public void onClick(View v)
{
for (int i = 0; i < mTabStrip.getChildCount(); i++) {
if (v == mTabStrip.getChildAt(i))
{
SharedPreferences sharedPreferencesToday =getContext().getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
String dateShared=sharedPreferencesToday.getString(dateTimeToolbarTitle,"");
SharedPreferences.Editor editor = sharedPreferencesToday.edit();
editor.putInt(locationIdShared,i+1);
editor.commit();
mViewPager.setCurrentItem(i);
String location= (String) adapter.getPageTitle(i);
Log.d(Constants.LOG_TAG, " Location " + location + " position " + i);
FHI_SQLite_Database fhiSqLiteDatabase=new FHI_SQLite_Database(getContext());
long dateSharedToday=0;
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Log.d(Constants.LOG_TAG," ValidUntilTimeSpan of LoginCall converted into DateFormat");
try {
Date convertedDate;
convertedDate = dateFormat.parse(dateShared);
Log.d(Constants.LOG_TAG, " Date shared using shared preferences" + convertedDate.toString());
dateSharedToday = convertedDate.getTime();
Log.d(Constants.LOG_TAG, "Converted date in date format to long int format " + dateSharedToday);
} catch (ParseException e) {
e.printStackTrace();
}
return;
}
}
}
}
}