how can I add single button programmatically to this activity? ( Telegram api) - java

actually I'm using this part of code but nothing shown in screen
// add single button for find near me
Button myButton = new Button(this);
myButton.setText("Press me");
myButton.setBackgroundColor(Color.YELLOW);
RelativeLayout.LayoutParams buttonParams = new RelativeLayout.LayoutParams( RelativeLayout.LayoutParams.WRAP_CONTENT, elativeLayout.LayoutParams.WRAP_CONTENT);
buttonParams.addRule(RelativeLayout.CENTER_HORIZONTAL);
buttonParams.addRule(RelativeLayout.CENTER_VERTICAL);
launchLayout.addView(myButton,buttonParams);
setContentView(launchLayout);
And this is the activity codes
public class LaunchActivity extends Activity implements ActionBarLayout.ActionBarLayoutDelegate, NotificationCenter.NotificationCenterDelegate, DialogsActivity.DialogsActivityDelegate {
private boolean finished;
private String videoPath;
private String sendingText;
private ArrayList<Uri> photoPathsArray;
private ArrayList<String> documentsPathsArray;
private ArrayList<Uri> documentsUrisArray;
private String documentsMimeType;
private ArrayList<String> documentsOriginalPathsArray;
private ArrayList<TLRPC.User> contactsToSend;
private int currentConnectionState;
private static ArrayList<BaseFragment> mainFragmentsStack = new ArrayList<>();
private static ArrayList<BaseFragment> layerFragmentsStack = new ArrayList<>();
private static ArrayList<BaseFragment> rightFragmentsStack = new ArrayList<>();
private ViewTreeObserver.OnGlobalLayoutListener onGlobalLayoutListener;
private ActionBarLayout actionBarLayout;
private ActionBarLayout layersActionBarLayout;
private ActionBarLayout rightActionBarLayout;
private FrameLayout shadowTablet;
private FrameLayout shadowTabletSide;
private View backgroundTablet;
protected DrawerLayoutContainer drawerLayoutContainer;
private DrawerLayoutAdapter drawerLayoutAdapter;
private PasscodeView passcodeView;
private AlertDialog visibleDialog;
private RecyclerListView sideMenu;
private AlertDialog localeDialog;
private boolean loadingLocaleDialog;
private HashMap<String, String> systemLocaleStrings;
private HashMap<String, String> englishLocaleStrings;
private Intent passcodeSaveIntent;
private boolean passcodeSaveIntentIsNew;
private boolean passcodeSaveIntentIsRestore;
private boolean tabletFullSize;
private Runnable lockRunnable;
#Override
protected void onCreate(Bundle savedInstanceState) {
ApplicationLoader.postInitApplication();
NativeCrashManager.handleDumpFiles(this);
AndroidUtilities.checkDisplaySize(this, getResources().getConfiguration());
Log.i(this.getClass().getName(), "onCreate: ");
if (!UserConfig.isClientActivated()) {
Intent intent = getIntent();
if (intent != null && intent.getAction() != null && (Intent.ACTION_SEND.equals(intent.getAction()) || intent.getAction().equals(Intent.ACTION_SEND_MULTIPLE))) {
super.onCreate(savedInstanceState);
finish();
return;
}
SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE);
long crashed_time = preferences.getLong("intro_crashed_time", 0);
boolean fromIntro = intent.getBooleanExtra("fromIntro", false);
if (fromIntro) {
preferences.edit().putLong("intro_crashed_time", 0).commit();
}
if (Math.abs(crashed_time - System.currentTimeMillis()) >= 60 * 2 * 1000 && intent != null && !fromIntro) {
preferences = ApplicationLoader.applicationContext.getSharedPreferences("logininfo2", MODE_PRIVATE);
Map<String, ?> state = preferences.getAll();
if (state.isEmpty()) {
Intent intent2 = new Intent(this, IntroActivity.class);
intent2.setData(intent.getData());
startActivity(intent2);
super.onCreate(savedInstanceState);
finish();
return;
}
}
}
requestWindowFeature(Window.FEATURE_NO_TITLE);
setTheme(R.style.Theme_TMessages);
getWindow().setBackgroundDrawableResource(R.drawable.transparent);
if (UserConfig.passcodeHash.length() > 0 && !UserConfig.allowScreenCapture) {
try {
getWindow().setFlags(WindowManager.LayoutParams.FLAG_SECURE, WindowManager.LayoutParams.FLAG_SECURE);
} catch (Exception e) {
FileLog.e(e);
}
}
super.onCreate(savedInstanceState);
if (Build.VERSION.SDK_INT >= 24) {
AndroidUtilities.isInMultiwindow = isInMultiWindowMode();
}
Theme.createChatResources(this, false);
if (UserConfig.passcodeHash.length() != 0 && UserConfig.appLocked) {
UserConfig.lastPauseTime = ConnectionsManager.getInstance().getCurrentTime();
}
int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
if (resourceId > 0) {
AndroidUtilities.statusBarHeight = getResources().getDimensionPixelSize(resourceId);
}
actionBarLayout = new ActionBarLayout(this);
drawerLayoutContainer = new DrawerLayoutContainer(this);
setContentView(drawerLayoutContainer, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
if (AndroidUtilities.isTablet()) {
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
RelativeLayout launchLayout = new RelativeLayout(this) {
private boolean inLayout;
#Override
public void requestLayout() {
if (inLayout) {
return;
}
super.requestLayout();
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
inLayout = true;
int width = MeasureSpec.getSize(widthMeasureSpec);
int height = MeasureSpec.getSize(heightMeasureSpec);
setMeasuredDimension(width, height);
if (!AndroidUtilities.isInMultiwindow && (!AndroidUtilities.isSmallTablet() || getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE)) {
tabletFullSize = false;
int leftWidth = width / 100 * 35;
if (leftWidth < AndroidUtilities.dp(320)) {
leftWidth = AndroidUtilities.dp(320);
}
actionBarLayout.measure(MeasureSpec.makeMeasureSpec(leftWidth, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY));
shadowTabletSide.measure(MeasureSpec.makeMeasureSpec(AndroidUtilities.dp(1), MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY));
rightActionBarLayout.measure(MeasureSpec.makeMeasureSpec(width - leftWidth, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY));
} else {
tabletFullSize = true;
actionBarLayout.measure(MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY));
}
backgroundTablet.measure(MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY));
shadowTablet.measure(MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY));
layersActionBarLayout.measure(MeasureSpec.makeMeasureSpec(Math.min(AndroidUtilities.dp(530), width), MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(Math.min(AndroidUtilities.dp(528), height), MeasureSpec.EXACTLY));
inLayout = false;
}
#Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
int width = r - l;
int height = b - t;
if (!AndroidUtilities.isInMultiwindow && (!AndroidUtilities.isSmallTablet() || getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE)) {
int leftWidth = width / 100 * 35;
if (leftWidth < AndroidUtilities.dp(320)) {
leftWidth = AndroidUtilities.dp(320);
}
shadowTabletSide.layout(leftWidth, 0, leftWidth + shadowTabletSide.getMeasuredWidth(), shadowTabletSide.getMeasuredHeight());
actionBarLayout.layout(0, 0, actionBarLayout.getMeasuredWidth(), actionBarLayout.getMeasuredHeight());
rightActionBarLayout.layout(leftWidth, 0, leftWidth + rightActionBarLayout.getMeasuredWidth(), rightActionBarLayout.getMeasuredHeight());
} else {
actionBarLayout.layout(0, 0, actionBarLayout.getMeasuredWidth(), actionBarLayout.getMeasuredHeight());
}
int x = (width - layersActionBarLayout.getMeasuredWidth()) / 2;
int y = (height - layersActionBarLayout.getMeasuredHeight()) / 2;
layersActionBarLayout.layout(x, y, x + layersActionBarLayout.getMeasuredWidth(), y + layersActionBarLayout.getMeasuredHeight());
backgroundTablet.layout(0, 0, backgroundTablet.getMeasuredWidth(), backgroundTablet.getMeasuredHeight());
shadowTablet.layout(0, 0, shadowTablet.getMeasuredWidth(), shadowTablet.getMeasuredHeight());
}
};
drawerLayoutContainer.addView(launchLayout, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT));
backgroundTablet = new View(this);
//BitmapDrawable drawable = (BitmapDrawable) getResources().getDrawable(R.drawable.catstile);
//drawable.setTileModeXY(Shader.TileMode.REPEAT, Shader.TileMode.REPEAT);
backgroundTablet.setBackgroundResource(R.drawable.catstile);
launchLayout.addView(backgroundTablet, LayoutHelper.createRelative(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT));
launchLayout.addView(actionBarLayout);
rightActionBarLayout = new ActionBarLayout(this);
rightActionBarLayout.init(rightFragmentsStack);
rightActionBarLayout.setDelegate(this);
launchLayout.addView(rightActionBarLayout);
shadowTabletSide = new FrameLayout(this);
shadowTabletSide.setBackgroundColor(0x40295274);
launchLayout.addView(shadowTabletSide);
shadowTablet = new FrameLayout(this);
shadowTablet.setVisibility(layerFragmentsStack.isEmpty() ? View.GONE : View.VISIBLE);
shadowTablet.setBackgroundColor(0x7f000000);
launchLayout.addView(shadowTablet);
shadowTablet.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if (!actionBarLayout.fragmentsStack.isEmpty() && event.getAction() == MotionEvent.ACTION_UP) {
float x = event.getX();
float y = event.getY();
int location[] = new int[2];
layersActionBarLayout.getLocationOnScreen(location);
int viewX = location[0];
int viewY = location[1];
if (layersActionBarLayout.checkTransitionAnimation() || x > viewX && x < viewX + layersActionBarLayout.getWidth() && y > viewY && y < viewY + layersActionBarLayout.getHeight()) {
return false;
} else {
if (!layersActionBarLayout.fragmentsStack.isEmpty()) {
for (int a = 0; a < layersActionBarLayout.fragmentsStack.size() - 1; a++) {
layersActionBarLayout.removeFragmentFromStack(layersActionBarLayout.fragmentsStack.get(0));
a--;
}
layersActionBarLayout.closeLastFragment(true);
}
return true;
}
}
return false;
}
});
shadowTablet.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
layersActionBarLayout = new ActionBarLayout(this);
layersActionBarLayout.setRemoveActionBarExtraHeight(true);
layersActionBarLayout.setBackgroundView(shadowTablet);
layersActionBarLayout.setUseAlphaAnimations(true);
layersActionBarLayout.setBackgroundResource(R.drawable.boxshadow);
layersActionBarLayout.init(layerFragmentsStack);
layersActionBarLayout.setDelegate(this);
layersActionBarLayout.setDrawerLayoutContainer(drawerLayoutContainer);
layersActionBarLayout.setVisibility(layerFragmentsStack.isEmpty() ? View.GONE : View.VISIBLE);
launchLayout.addView(layersActionBarLayout);
// add single button for find near me
Button myButton = new Button(this);
myButton.setText("Press me");
myButton.setBackgroundColor(Color.YELLOW);
RelativeLayout.LayoutParams buttonParams =
new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
buttonParams.addRule(RelativeLayout.CENTER_HORIZONTAL);
buttonParams.addRule(RelativeLayout.CENTER_VERTICAL);
launchLayout.addView(myButton,buttonParams);
setContentView(launchLayout);
} else {
drawerLayoutContainer.addView(actionBarLayout, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
}
sideMenu = new RecyclerListView(this);
sideMenu.setBackgroundColor(Theme.getColor(Theme.key_chats_menuBackground));
sideMenu.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
sideMenu.setAdapter(drawerLayoutAdapter = new DrawerLayoutAdapter(this));
drawerLayoutContainer.setDrawerLayout(sideMenu);
FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) sideMenu.getLayoutParams();
Point screenSize = AndroidUtilities.getRealScreenSize();
layoutParams.width = AndroidUtilities.isTablet() ? AndroidUtilities.dp(320) : Math.min(AndroidUtilities.dp(320), Math.min(screenSize.x, screenSize.y) - AndroidUtilities.dp(56));
layoutParams.height = LayoutHelper.MATCH_PARENT;
sideMenu.setLayoutParams(layoutParams);
sideMenu.setOnItemClickListener(new RecyclerListView.OnItemClickListener() {
#Override
public void onItemClick(final View view, int position) {
int id = drawerLayoutAdapter.getId(position);
if (position == 0) {
Bundle args = new Bundle();
args.putInt("user_id", UserConfig.getClientUserId());
presentFragment(new ChatActivity(args));
drawerLayoutContainer.closeDrawer(false);
} else if (id == 2) {
if (!MessagesController.isFeatureEnabled("chat_create", actionBarLayout.fragmentsStack.get(actionBarLayout.fragmentsStack.size() - 1))) {
return;
}
presentFragment(new GroupCreateActivity());
drawerLayoutContainer.closeDrawer(false);
} else if (id == 3) {
Bundle args = new Bundle();
args.putBoolean("onlyUsers", true);
args.putBoolean("destroyAfterSelect", true);
args.putBoolean("createSecretChat", true);
args.putBoolean("allowBots", false);
presentFragment(new ContactsActivity(args));
drawerLayoutContainer.closeDrawer(false);
} else if (id == 4) {
if (!MessagesController.isFeatureEnabled("broadcast_create", actionBarLayout.fragmentsStack.get(actionBarLayout.fragmentsStack.size() - 1))) {
return;
}
SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE);
if (!BuildVars.DEBUG_VERSION && preferences.getBoolean("channel_intro", false)) {
Bundle args = new Bundle();
args.putInt("step", 0);
presentFragment(new ChannelCreateActivity(args));
} else {
presentFragment(new ChannelIntroActivity());
preferences.edit().putBoolean("channel_intro", true).commit();
}
drawerLayoutContainer.closeDrawer(false);
} else if (id == 6) {
presentFragment(new ContactsActivity(null));
drawerLayoutContainer.closeDrawer(false);
} else if (id == 7) {
if (BuildVars.DEBUG_PRIVATE_VERSION) {
/*AlertDialog.Builder builder = new AlertDialog.Builder(LaunchActivity.this);
builder.setTopImage(R.drawable.permissions_contacts, 0xff35a8e0);
builder.setMessage(AndroidUtilities.replaceTags(LocaleController.getString("ContactsPermissionAlert", R.string.ContactsPermissionAlert)));
builder.setPositiveButton(LocaleController.getString("ContactsPermissionAlertContinue", R.string.ContactsPermissionAlertContinue), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
builder.setNegativeButton(LocaleController.getString("ContactsPermissionAlertNotNow", R.string.ContactsPermissionAlertNotNow), null);
showAlertDialog(builder);*/
showLanguageAlert(true);
} else {
try {
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_TEXT, ContactsController.getInstance().getInviteText());
startActivityForResult(Intent.createChooser(intent, LocaleController.getString("InviteFriends", R.string.InviteFriends)), 500);
} catch (Exception e) {
FileLog.e(e);
}
drawerLayoutContainer.closeDrawer(false);
}
} else if (id == 8) {
presentFragment(new SettingsActivity());
drawerLayoutContainer.closeDrawer(false);
} else if (id == 9) {
Browser.openUrl(LaunchActivity.this, LocaleController.getString("TelegramFaqUrl", R.string.TelegramFaqUrl));
drawerLayoutContainer.closeDrawer(false);
} else if (id == 10) {
presentFragment(new CallLogActivity());
drawerLayoutContainer.closeDrawer(false);
}
}
});
drawerLayoutContainer.setParentActionBarLayout(actionBarLayout);
actionBarLayout.setDrawerLayoutContainer(drawerLayoutContainer);
actionBarLayout.init(mainFragmentsStack);
actionBarLayout.setDelegate(this);
Theme.loadWallpaper();
passcodeView = new PasscodeView(this);
drawerLayoutContainer.addView(passcodeView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT));
NotificationCenter.getInstance().postNotificationName(NotificationCenter.closeOtherAppActivities, this);
currentConnectionState = ConnectionsManager.getInstance().getConnectionState();
NotificationCenter.getInstance().addObserver(this, NotificationCenter.appDidLogout);
NotificationCenter.getInstance().addObserver(this, NotificationCenter.mainUserInfoChanged);
NotificationCenter.getInstance().addObserver(this, NotificationCenter.closeOtherAppActivities);
NotificationCenter.getInstance().addObserver(this, NotificationCenter.didUpdatedConnectionState);
NotificationCenter.getInstance().addObserver(this, NotificationCenter.needShowAlert);
NotificationCenter.getInstance().addObserver(this, NotificationCenter.wasUnableToFindCurrentLocation);
NotificationCenter.getInstance().addObserver(this, NotificationCenter.didSetNewWallpapper);
NotificationCenter.getInstance().addObserver(this, NotificationCenter.didSetPasscode);
NotificationCenter.getInstance().addObserver(this, NotificationCenter.reloadInterface);
NotificationCenter.getInstance().addObserver(this, NotificationCenter.suggestedLangpack);
if (actionBarLayout.fragmentsStack.isEmpty()) {
if (!UserConfig.isClientActivated()) {
actionBarLayout.addFragmentToStack(new LoginActivity());
drawerLayoutContainer.setAllowOpenDrawer(false, false);
} else {
DialogsActivity dialogsActivity = new DialogsActivity(null);
dialogsActivity.setSideMenu(sideMenu);
actionBarLayout.addFragmentToStack(dialogsActivity);
drawerLayoutContainer.setAllowOpenDrawer(true, false);
}
try {
if (savedInstanceState != null) {
String fragmentName = savedInstanceState.getString("fragment");
if (fragmentName != null) {
Bundle args = savedInstanceState.getBundle("args");
switch (fragmentName) {
case "chat":
if (args != null) {
ChatActivity chat = new ChatActivity(args);
if (actionBarLayout.addFragmentToStack(chat)) {
chat.restoreSelfArgs(savedInstanceState);
}
}
break;
case "settings": {
SettingsActivity settings = new SettingsActivity();
actionBarLayout.addFragmentToStack(settings);
settings.restoreSelfArgs(savedInstanceState);
break;
}
case "group":
if (args != null) {
GroupCreateFinalActivity group = new GroupCreateFinalActivity(args);
if (actionBarLayout.addFragmentToStack(group)) {
group.restoreSelfArgs(savedInstanceState);
}
}
break;
case "channel":
if (args != null) {
ChannelCreateActivity channel = new ChannelCreateActivity(args);
if (actionBarLayout.addFragmentToStack(channel)) {
channel.restoreSelfArgs(savedInstanceState);
}
}
break;
case "edit":
if (args != null) {
ChannelEditActivity channel = new ChannelEditActivity(args);
if (actionBarLayout.addFragmentToStack(channel)) {
channel.restoreSelfArgs(savedInstanceState);
}
}
break;
case "chat_profile":
if (args != null) {
ProfileActivity profile = new ProfileActivity(args);
if (actionBarLayout.addFragmentToStack(profile)) {
profile.restoreSelfArgs(savedInstanceState);
}
}
break;
case "wallpapers": {
WallpapersActivity settings = new WallpapersActivity();
actionBarLayout.addFragmentToStack(settings);
settings.restoreSelfArgs(savedInstanceState);
break;
}
}
}
}
} catch (Exception e) {
FileLog.e(e);
}
} else {
BaseFragment fragment = actionBarLayout.fragmentsStack.get(0);
if (fragment instanceof DialogsActivity) {
((DialogsActivity) fragment).setSideMenu(sideMenu);
}
boolean allowOpen = true;
if (AndroidUtilities.isTablet()) {
allowOpen = actionBarLayout.fragmentsStack.size() <= 1 && layersActionBarLayout.fragmentsStack.isEmpty();
if (layersActionBarLayout.fragmentsStack.size() == 1 && layersActionBarLayout.fragmentsStack.get(0) instanceof LoginActivity) {
allowOpen = false;
}
}
if (actionBarLayout.fragmentsStack.size() == 1 && actionBarLayout.fragmentsStack.get(0) instanceof LoginActivity) {
allowOpen = false;
}
drawerLayoutContainer.setAllowOpenDrawer(allowOpen, false);
}
checkLayout();
handleIntent(getIntent(), false, savedInstanceState != null, false);
try {
String os1 = Build.DISPLAY;
String os2 = Build.USER;
if (os1 != null) {
os1 = os1.toLowerCase();
} else {
os1 = "";
}
if (os2 != null) {
os2 = os1.toLowerCase();
} else {
os2 = "";
}
if (os1.contains("flyme") || os2.contains("flyme")) {
AndroidUtilities.incorrectDisplaySizeFix = true;
final View view = getWindow().getDecorView().getRootView();
view.getViewTreeObserver().addOnGlobalLayoutListener(onGlobalLayoutListener = new ViewTreeObserver.OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
int height = view.getMeasuredHeight();
if (Build.VERSION.SDK_INT >= 21) {
height -= AndroidUtilities.statusBarHeight;
}
if (height > AndroidUtilities.dp(100) && height < AndroidUtilities.displaySize.y && height + AndroidUtilities.dp(100) > AndroidUtilities.displaySize.y) {
AndroidUtilities.displaySize.y = height;
FileLog.e("fix display size y to " + AndroidUtilities.displaySize.y);
}
}
});
}
} catch (Exception e) {
FileLog.e(e);
}
MediaController.getInstance().setBaseActivity(this, true);
}

Related

How to auto play first video in recyclerview in ExoPlayer

I have a problem in my code. I want to autoplay first video from recyclerview in ExoPlayer, The player is working good on scroll but the first video does not play automatically
public class VideoPlayerRecyclerView extends RecyclerView {
private static final String TAG = "VideoPlayerRecyclerView";
private enum VolumeState {ON, OFF};
// ui
private ImageView thumbnail, volumeControl;
private ProgressBar progressBar;
private View viewHolderParent;
private FrameLayout frameLayout;
private PlayerView videoSurfaceView;
private SimpleExoPlayer videoPlayer;
// vars
private ArrayList<Status_Bakend> mediaObjects = new ArrayList<>();
private int videoSurfaceDefaultHeight = 0;
private int screenDefaultHeight = 0;
private Context context;
private int playPosition = -1;
private boolean isVideoViewAdded;
private RequestManager requestManager;
// controlling playback state
private VolumeState volumeState;
public VideoPlayerRecyclerView(#NonNull Context context) {
super(context);
init(context);
}
public VideoPlayerRecyclerView(#NonNull Context context, #Nullable AttributeSet attrs) {
super(context, attrs);
init(context);
}
private void init(final Context context){
this.context = context.getApplicationContext();
Display display = ((WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
Point point = new Point();
display.getSize(point);
videoSurfaceDefaultHeight = point.x;
screenDefaultHeight = point.y;
videoSurfaceView = new PlayerView(this.context);
videoSurfaceView.setResizeMode(AspectRatioFrameLayout.RESIZE_MODE_ZOOM);
BandwidthMeter bandwidthMeter = new DefaultBandwidthMeter();
TrackSelection.Factory videoTrackSelectionFactory =
new AdaptiveTrackSelection.Factory(bandwidthMeter);
TrackSelector trackSelector =
new DefaultTrackSelector(videoTrackSelectionFactory);
// 2. Create the player
videoPlayer = ExoPlayerFactory.newSimpleInstance(context, trackSelector);
// Bind the player to the view.
videoSurfaceView.setUseController(false);
videoSurfaceView.setPlayer(videoPlayer);
setVolumeControl(VolumeState.ON);
playVideo(true);
videoPlayer.setPlayWhenReady(true);
addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
if (newState == RecyclerView.SCROLL_STATE_IDLE) {
Log.d(TAG, "onScrollStateChanged: called.");
if(thumbnail != null){ // show the old thumbnail
thumbnail.setVisibility(VISIBLE);
}
// There's a special case when the end of the list has been reached.
// Need to handle that with this bit of logic
if(!recyclerView.canScrollVertically(1)){
playVideo(true);
}
else{
playVideo(false);
}
}
}
#Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
}
});
addOnChildAttachStateChangeListener(new OnChildAttachStateChangeListener() {
#Override
public void onChildViewAttachedToWindow(View view) {
}
#Override
public void onChildViewDetachedFromWindow(View view) {
if (viewHolderParent != null && viewHolderParent.equals(view)) {
resetVideoView();
}
}
});
videoPlayer.addListener(new Player.EventListener() {
#Override
public void onTimelineChanged(Timeline timeline, #Nullable Object manifest, int reason) {
}
#Override
public void onTracksChanged(TrackGroupArray trackGroups, TrackSelectionArray trackSelections) {
}
#Override
public void onLoadingChanged(boolean isLoading) {
}
#Override
public void onPlayerStateChanged(boolean playWhenReady, int playbackState) {
switch (playbackState) {
case Player.STATE_BUFFERING:
Log.e(TAG, "onPlayerStateChanged: Buffering video.");
if (progressBar != null) {
progressBar.setVisibility(VISIBLE);
}
break;
case Player.STATE_ENDED:
Log.d(TAG, "onPlayerStateChanged: Video ended.");
videoPlayer.seekTo(0);
break;
case Player.STATE_IDLE:
break;
case Player.STATE_READY:
Log.e(TAG, "onPlayerStateChanged: Ready to play.");
if (progressBar != null) {
progressBar.setVisibility(GONE);
}
if(!isVideoViewAdded){
addVideoView();
}
break;
default:
break;
}
}
#Override
public void onRepeatModeChanged(int repeatMode) {
}
#Override
public void onShuffleModeEnabledChanged(boolean shuffleModeEnabled) {
}
#Override
public void onPlayerError(ExoPlaybackException error) {
}
#Override
public void onPositionDiscontinuity(int reason) {
}
#Override
public void onPlaybackParametersChanged(PlaybackParameters playbackParameters) {
}
#Override
public void onSeekProcessed() {
}
});
}
public void playVideo(boolean isEndOfList) {
int targetPosition;
if(!isEndOfList){
int startPosition = ((LinearLayoutManager) getLayoutManager()).findFirstVisibleItemPosition();
int endPosition = ((LinearLayoutManager) getLayoutManager()).findLastVisibleItemPosition();
// if there is more than 2 list-items on the screen, set the difference to be 1
if (endPosition - startPosition > 1) {
endPosition = startPosition + 1;
}
// something is wrong. return.
if (startPosition < 0 || endPosition < 0) {
return;
}
// if there is more than 1 list-item on the screen
if (startPosition != endPosition) {
int startPositionVideoHeight = getVisibleVideoSurfaceHeight(startPosition);
int endPositionVideoHeight = getVisibleVideoSurfaceHeight(endPosition);
targetPosition = startPositionVideoHeight > endPositionVideoHeight ? startPosition : endPosition;
}
else {
targetPosition = startPosition;
}
}
else{
targetPosition = mediaObjects.size() - 1;
}
Toast.makeText(context, "playVideo: target position: " + targetPosition, Toast.LENGTH_SHORT).show();
// video is already playing so return
if (targetPosition == playPosition) {
return;
}
// set the position of the list-item that is to be played
playPosition = targetPosition;
if (videoSurfaceView == null) {
return;
}
// remove any old surface views from previously playing videos
videoSurfaceView.setVisibility(INVISIBLE);
removeVideoView(videoSurfaceView);
int currentPosition = targetPosition - ((LinearLayoutManager) getLayoutManager()).findFirstVisibleItemPosition();
View child = getChildAt(currentPosition);
if (child == null) {
return;
}
VideoPlayerViewHolder holder = (VideoPlayerViewHolder) child.getTag();
if (holder == null) {
playPosition = -1;
return;
}
thumbnail = holder.thumbnail;
progressBar = holder.progressBar;
volumeControl = holder.volumeControl;
viewHolderParent = holder.itemView;
requestManager = holder.requestManager;
frameLayout = holder.itemView.findViewById(R.id.media_container);
videoSurfaceView.setPlayer(videoPlayer);
videoPlayer.addVideoListener(new VideoListener() {
#Override
public void onVideoSizeChanged(int width, int height, int unappliedRotationDegrees, float pixelWidthHeightRatio) {
frameLayout.getLayoutParams().height = (height * 2);
}
#Override
public void onRenderedFirstFrame() {
}
});
viewHolderParent.setOnClickListener(videoViewClickListener);
DataSource.Factory dataSourceFactory = new DefaultDataSourceFactory(
context, Util.getUserAgent(context, "RecyclerView VideoPlayer"));
String mediaUrl = mediaObjects.get(targetPosition).getStatus_link();
if (mediaUrl != null) {
MediaSource videoSource = new ExtractorMediaSource.Factory(dataSourceFactory)
.createMediaSource(Uri.parse(mediaUrl));
videoPlayer.prepare(videoSource);
videoPlayer.setPlayWhenReady(true);
}
}
private OnClickListener videoViewClickListener = new OnClickListener() {
#Override
public void onClick(View v) {
toggleVolume();
}
};
/**
* Returns the visible region of the video surface on the screen.
* if some are cut off, it will return less than the #videoSurfaceDefaultHeight
* #param playPosition
* #return
*/
private int getVisibleVideoSurfaceHeight(int playPosition) {
int at = playPosition - ((LinearLayoutManager) getLayoutManager()).findFirstVisibleItemPosition();
Log.d(TAG, "getVisibleVideoSurfaceHeight: at: " + at);
View child = getChildAt(at);
if (child == null) {
return 0;
}
int[] location = new int[2];
child.getLocationInWindow(location);
if (location[1] < 0) {
return location[1] + videoSurfaceDefaultHeight;
} else {
return screenDefaultHeight - location[1];
}
}
// Remove the old player
private void removeVideoView(PlayerView videoView) {
ViewGroup parent = (ViewGroup) videoView.getParent();
if (parent == null) {
return;
}
int index = parent.indexOfChild(videoView);
if (index >= 0) {
parent.removeViewAt(index);
isVideoViewAdded = false;
viewHolderParent.setOnClickListener(null);
}
}
private void addVideoView(){
frameLayout.addView(videoSurfaceView);
isVideoViewAdded = true;
videoSurfaceView.requestFocus();
videoSurfaceView.setVisibility(VISIBLE);
videoSurfaceView.setAlpha(1);
}
private void resetVideoView(){
if(isVideoViewAdded){
removeVideoView(videoSurfaceView);
playPosition = -1;
videoSurfaceView.setVisibility(INVISIBLE);
}
}
public void releasePlayer() {
if (videoPlayer != null) {
videoPlayer.release();
videoPlayer = null;
}
viewHolderParent = null;
}
private void toggleVolume() {
if (videoPlayer != null) {
if (volumeState == VolumeState.OFF) {
Log.d(TAG, "togglePlaybackState: enabling volume.");
setVolumeControl(VolumeState.ON);
} else if(volumeState == VolumeState.ON) {
Log.d(TAG, "togglePlaybackState: disabling volume.");
setVolumeControl(VolumeState.OFF);
}
}
}
private void setVolumeControl(VolumeState state){
volumeState = state;
if(state == VolumeState.OFF){
videoPlayer.setVolume(0f);
animateVolumeControl();
}
else if(state == VolumeState.ON){
videoPlayer.setVolume(1f);
animateVolumeControl();
}
}
private void animateVolumeControl(){
if(volumeControl != null){
volumeControl.bringToFront();
if(volumeState == VolumeState.OFF){
requestManager.load(R.drawable.ic_favorite_border_black_24dp)
.into(volumeControl);
}
else if(volumeState == VolumeState.ON){
requestManager.load(R.drawable.ic_favorite_border_black_24dp)
.into(volumeControl);
}
volumeControl.animate().cancel();
volumeControl.setAlpha(1f);
volumeControl.animate()
.alpha(0f)
.setDuration(600).setStartDelay(1000);
}
}
public void setMediaObjects(ArrayList<Status_Bakend> mediaObjects){
this.mediaObjects = mediaObjects;
}
}
This is my code on recyclerview scroll working fine on scroll but I want to autoplay my first video in recyclerview without scrolling.
Just add this line after setAdapter to the recycler view.
recyclerView.smoothScrollBy(0, -1);
OR
recyclerView.smoothScrollBy(0, 1);
This will solve your problem.
You only need to make the first video play using postDelayed().
I think the reason is that the views of the RecyclerView items are all drawn on the layout and the video play process are duplicated.

I am adding a tab layout with viewPager using fragments. The tab is dynamic on 0 tab is disabled and on 1 tab is enabled

I am adding a tab layout with viewPager using fragments. The tab is dynamic on 0 tab is disabled and on 1 tab is enabled.On disable the tab the tab position is gone but on swipe the next tab layout the content of fragment is repeating twice. How to solve it please help.
tabLayout = (TabLayout) findViewById(R.id.tabLayout);
mPager = (ViewPager) findViewById(R.id.viewPager);
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
mAdapter = new MyAdapter(this, getSupportFragmentManager());
mPager.setAdapter(mAdapter);
tabLayout.setupWithViewPager(mPager);
tabLayout.setSelectedTabIndicatorColor(Color.parseColor("#ffffff"));
tabLayout.setSelectedTabIndicatorHeight((int) (5 * getResources().getDisplayMetrics().density));
tabLayout.setTabTextColors(Color.parseColor("#ffffff"), Color.parseColor("#ffffff"));
tabLayout.setBackgroundColor(getResources().getColor(R.color.darkpurple));
if (updateValue == true) {
mPager.setCurrentItem(0);
} else if (updateNotice == true) {
mPager.setCurrentItem(1);
} else if (updateGallery == true) {
mPager.setCurrentItem(2);
} else if (updateClswork == true) {
mPager.setCurrentItem(3);
} else if (updateEnquiry == true) {
mPager.setCurrentItem(4);
} else if (updateCalender == true) {
mPager.setCurrentItem(5);
}
if (diary_view == 0) {
tabPos = tabLayout.getTabAt(0);
tabLayout.removeTab(tabPos);
} else if (notice_view == 0) {
tabPos = tabLayout.getTabAt(1);
tabLayout.removeTab(tabPos);
} else if (magical_moments_view == 0) {
tabPos = tabLayout.getTabAt(2);
tabLayout.removeTab(tabPos);
} else if (access_all_daily_class_work_view_listing == 0) {
tabPos = tabLayout.getTabAt(3);
tabLayout.removeTab(tabPos);
getSupportFragmentManager().beginTransaction().remove(new ClassworkFrag()).commit();
} else if (access_frontdesk_prospects_view == 0) {
tabPos = tabLayout.getTabAt(4);
tabLayout.removeTab(tabPos);
} else if (institute_event_view == 0) {
tabPos = tabLayout.getTabAt(5);
tabLayout.removeTab(tabPos);
}
View header = navigationView.getHeaderView(0);
headerLayout = (RelativeLayout) header.findViewById(R.id.headerLayout);
TextView nameTv = (TextView) header.findViewById(R.id.name);
TextView enailidTv = (TextView) header.findViewById(R.id.emailid);
ImageView logoIv = (ImageView) header.findViewById(R.id.logo);
headerLayout.setBackgroundColor(getResources().getColor(R.color.purple));
nameTv.setText(usernameStr);
enailidTv.setText(emailStr);
logoIv.setImageDrawable(drawable);
/*if (photoStr.isEmpty()) {
Picasso.get()
.load(R.drawable.placeholder)
.resize(50, 50)
.centerCrop()
.into(logoIv);
}
else {
Picasso.get()
.load(photoStr)
.resize(50, 50)
.centerCrop()
.into(logoIv);
}*/
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
Gson gson = new Gson();
String json = sharedPrefs.getString("listparent", null);
Type type = (Type) new TypeToken<ArrayList<Parent>>() {
}.getType();
parentList = gson.fromJson(json, (Type) type);
headerLayout.setBackgroundColor(getResources().getColor(R.color.purple));
tabLayout.setBackgroundColor(getResources().getColor(R.color.darkpurple));
toolbarCollapse.setContentScrimColor(getResources().getColor(R.color.purple));
appBarLayout.setBackgroundColor(getResources().getColor(R.color.purple));
studetailLayout.setBackgroundColor(getResources().getColor(R.color.purple));
toolbar.setBackgroundColor(getResources().getColor(R.color.purple));
fabMenu.setMenuButtonColor(getResources().getColor(R.color.purple));
//Picasso.get().load(schoolBanner).into(bannerIv);
/*Glide.with(this)
.load(schoolBanner)
.placeholder(R.drawable.coolgbnr)
.into(bannerIv);*/
Glide.with(MainActivity.this)
.load(schoolBanner)
.apply(new RequestOptions().placeholder(R.drawable.coolgbnr).error(R.drawable.coolgbnr))
.into(bannerIv);
mPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
int colorDiary = getResources().getColor(R.color.purple);
int colorNotice = getResources().getColor(R.color.colorAccent);
int colorCal = getResources().getColor(R.color.orange);
int colorMm = getResources().getColor(R.color.purpal);
int colorClswrk = getResources().getColor(R.color.colorGoogleGreen);
int colorEnquiry = getResources().getColor(R.color.litegold);
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
//Toast.makeText(getApplicationContext(),""+position,Toast.LENGTH_SHORT).show();
}
#Override
public void onPageSelected(int position) {
//tabLayout.getTabAt(position).select();
TabLayout.Tab tab = tabLayout.getTabAt(position);
if (tab != null) {
tab.select();
}
if (position == 0) {
headerLayout.setBackgroundColor(getResources().getColor(R.color.purple));
tabLayout.setBackgroundColor(getResources().getColor(R.color.darkpurple));
toolbarCollapse.setContentScrimColor(getResources().getColor(R.color.purple));
appBarLayout.setBackgroundColor(getResources().getColor(R.color.purple));
studetailLayout.setBackgroundColor(getResources().getColor(R.color.purple));
toolbar.setBackgroundColor(getResources().getColor(R.color.purple));
fabMenu.setMenuButtonColor(getResources().getColor(R.color.purple));
colorTitleBar(colorDiary);
if (create_diary == 1) {
//fabpostBtn.setEnabled(true);
fabMenu.setVisibility(View.VISIBLE);
} else if (create_diary == 0) {
//fabpostBtn.setEnabled(false);
fabMenu.setVisibility(View.GONE);
}
} else if (position == 1) {
headerLayout.setBackgroundColor(getResources().getColor(R.color.colorAccent));
tabLayout.setBackgroundColor(getResources().getColor(R.color.darkcoloraccent));
toolbarCollapse.setContentScrimColor(getResources().getColor(R.color.colorAccent));
appBarLayout.setBackgroundColor(getResources().getColor(R.color.colorAccent));
studetailLayout.setBackgroundColor(getResources().getColor(R.color.colorAccent));
toolbar.setBackgroundColor(getResources().getColor(R.color.colorAccent));
fabMenu.setMenuButtonColor(getResources().getColor(R.color.colorAccent));
colorTitleBar(colorNotice);
if (create_notice == 1) {
fabMenu.setVisibility(View.VISIBLE);
} else if (create_notice == 0) {
fabMenu.setVisibility(View.GONE);
}
} else if (position == 2) {
headerLayout.setBackgroundColor(getResources().getColor(R.color.purpal));
tabLayout.setBackgroundColor(getResources().getColor(R.color.darkpurpal));
toolbarCollapse.setContentScrimColor(getResources().getColor(R.color.purpal));
appBarLayout.setBackgroundColor(getResources().getColor(R.color.purpal));
studetailLayout.setBackgroundColor(getResources().getColor(R.color.purpal));
toolbar.setBackgroundColor(getResources().getColor(R.color.purpal));
fabMenu.setMenuButtonColor(getResources().getColor(R.color.purpal));
colorTitleBar(colorMm);
if (create_magical_moments == 1) {
//fabpostBtn.setEnabled(true);
fabMenu.setVisibility(View.VISIBLE);
} else if (create_magical_moments == 0) {
//fabpostBtn.setEnabled(false);
fabMenu.setVisibility(View.GONE);
}
} else if (position == 3) {
headerLayout.setBackgroundColor(getResources().getColor(R.color.colorGoogleGreen));
tabLayout.setBackgroundColor(getResources().getColor(R.color.selected));
toolbarCollapse.setContentScrimColor(getResources().getColor(R.color.colorGoogleGreen));
appBarLayout.setBackgroundColor(getResources().getColor(R.color.colorGoogleGreen));
studetailLayout.setBackgroundColor(getResources().getColor(R.color.colorGoogleGreen));
toolbar.setBackgroundColor(getResources().getColor(R.color.colorGoogleGreen));
fabMenu.setMenuButtonColor(getResources().getColor(R.color.colorGoogleGreen));
colorTitleBar(colorClswrk);
if (create_class_work == 1) {
//fabpostBtn.setEnabled(true);
fabMenu.setVisibility(View.VISIBLE);
} else if (create_class_work == 0) {
//fabpostBtn.setEnabled(false);
fabMenu.setVisibility(View.GONE);
}
} else if (position == 4) {
headerLayout.setBackgroundColor(getResources().getColor(R.color.litegold));
tabLayout.setBackgroundColor(getResources().getColor(R.color.darkgold));
toolbarCollapse.setContentScrimColor(getResources().getColor(R.color.litegold));
appBarLayout.setBackgroundColor(getResources().getColor(R.color.litegold));
studetailLayout.setBackgroundColor(getResources().getColor(R.color.litegold));
toolbar.setBackgroundColor(getResources().getColor(R.color.litegold));
fabMenu.setMenuButtonColor(getResources().getColor(R.color.litegold));
colorTitleBar(colorEnquiry);
if (create_institute_event == 1) {
fabMenu.setVisibility(View.VISIBLE);
} else if (create_institute_event == 0) {
fabMenu.setVisibility(View.GONE);
}
} else if (position == 5) {
headerLayout.setBackgroundColor(getResources().getColor(R.color.orange));
tabLayout.setBackgroundColor(getResources().getColor(R.color.darkorange));
toolbarCollapse.setContentScrimColor(getResources().getColor(R.color.orange));
appBarLayout.setBackgroundColor(getResources().getColor(R.color.orange));
studetailLayout.setBackgroundColor(getResources().getColor(R.color.orange));
toolbar.setBackgroundColor(getResources().getColor(R.color.orange));
fabMenu.setMenuButtonColor(getResources().getColor(R.color.orange));
colorTitleBar(colorCal);
if (create_institute_event == 1) {
//fabpostBtn.setEnabled(true);
fabMenu.setVisibility(View.VISIBLE);
} else if (create_institute_event == 0) {
//fabpostBtn.setEnabled(false);
fabMenu.setVisibility(View.GONE);
}
}
fragPos = position;
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
toggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
toggle.onConfigurationChanged(newConfig);
}
#Override
public boolean onNavigationItemSelected(MenuItem item) {
int id = item.getItemId();
int position = 0;
switch (id) {
case R.id.navigation_item_1:
Intent iArt = new Intent(MainActivity.this, MainActivity.class);
startActivity(iArt);
break;
case R.id.navigation_item_3:
if (student_attendance == 1 || staff_attendance == 0) {
Intent iPro = new Intent(MainActivity.this, DialogActivity.class);
startActivity(iPro);
} else if (student_attendance == 0 || staff_attendance == 1) {
Intent iPro = new Intent(MainActivity.this, DialogActivity.class);
startActivity(iPro);
} else if (student_attendance == 0 || staff_attendance == 0) {
Intent iPro = new Intent(MainActivity.this, DialogActivity.class);
startActivity(iPro);
}
break;
case R.id.navigation_item_4:
Intent iScn = new Intent(MainActivity.this, TeacherProfileActivity.class);
startActivity(iScn);
break;
case R.id.studentdetail:
Intent iStudtl = new Intent(MainActivity.this, StudentProfileActivity.class);
startActivity(iStudtl);
break;
case R.id.navigation_item_5:
sessionManage.logoutUser();
break;
case R.id.student:
Intent report = new Intent(MainActivity.this, RootDialogActivity.class);
startActivity(report);
break;
case R.id.attendance:
if (view_attendance == 1) {
Intent report1 = new Intent(MainActivity.this, AttendanceReportActivity.class);
startActivity(report1);
} else {
//Toast.makeText(getApplicationContext(),"Permission Not Access",Toast.LENGTH_SHORT).show();
}
break;
case R.id.fee:
if (fee_details == 1) {
Intent report2 = new Intent(MainActivity.this, FeeReportActivity.class);
startActivity(report2);
} else {
//Toast.makeText(getApplicationContext(),"Permission Not Access",Toast.LENGTH_SHORT).show();
}
break;
case R.id.payment:
if (daily_report == 1) {
Intent report3 = new Intent(MainActivity.this, PaymentReportActivity.class);
startActivity(report3);
} else {
//Toast.makeText(getApplicationContext(),"Permission Not Access",Toast.LENGTH_SHORT).show();
}
break;
}
if (getSupportActionBar() != null)
getSupportActionBar().setTitle(mTitle);
drawer.closeDrawer(GravityCompat.START);
return true;
}
public class MyAdapter extends FragmentPagerAdapter {
CharSequence mTabname[] = new CharSequence[]{"Diary", "Notice", "Gallery", "Class\nWork", "Enquiry", "Calendar"};
private static final int NUM_ITEMS = 6;
Context context;
int baseId =0;
public MyAdapter(Context context, FragmentManager fm) {
super(fm);
this.context = context;
}
#Override
public int getCount() {
Log.i("itemCount", "items = " + NUM_ITEMS);
return NUM_ITEMS;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
if (diary_view==0){
new DiaryFrag().onDestroy();
}else {
DiaryFrag diaryFrag = new DiaryFrag();
return diaryFrag;
}
case 1:
if (notice_view==0){
new NoticeFrag().onDestroy();
}else {
NoticeFrag noticeFrag = new NoticeFrag();
return noticeFrag;
}
case 2:
if (magical_moments_view==0){
new GalleryFrag().onDestroy();
}else {
GalleryFrag galleryFrag = new GalleryFrag();
return galleryFrag;
}
case 3:
if (access_all_daily_class_work_view_listing==0){
}else {
ClassworkFrag classworkFrag = new ClassworkFrag();
return classworkFrag;
}
case 4:
if ((access_frontdesk_prospects_view == 0)) {
} else {
return new EnquiryFrag();
}
case 5:
if (institute_event_view==0){
}else {
CalendarFrag calendarFrag = new CalendarFrag();
return calendarFrag;
}
}
return null;
}
#Override
public CharSequence getPageTitle(int position) {
return mTabname[position];
}
}
public void colorTitleBar(int color) {
/* Window window = getWindow();
window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.setStatusBarColor(color);*/
//Log.d("colorcodee",""+color);
try {
Window window = getWindow();
mainColor = color;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT && Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
SystemBarTintManager tintManager = new SystemBarTintManager(this);
tintManager.setStatusBarTintEnabled(true);
tintManager.setTintColor(ContextCompat.getColor(MainActivity.this, mainColor));
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
/* window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
window.setStatusBarColor(mainColor);*/
//Window window = getWindow();
window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.setStatusBarColor(color);
}
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onBackPressed() {
if (drawer.isDrawerOpen(GravityCompat.START)) {
//drawer is open
drawer.closeDrawers();
} else {
MainActivity.this.finishAffinity();
}
}
Create a method clearData() in adapter as:
private void clearData(){
//clear your Array/List/ArrayList
notifyDataSetChanged()
}
In your main activity, when you inflate the data in adapter, before setting data in it, clear the data using clearData().

How to make customize mediacontroller for videoview

I make whole video player app but stuck at mediacontroller. I want to show my own mediacontroller with different button, not the default one. It's 4rth day, i'm just trying to make my own mediacontroller but didn't succeed.
I succeed by doing it with surfaceview but i want to use it with videoview.
I try the following code.
public class MyMediaController extends MediaController {
private static final String TAG = "VideoControllerView";
MediaController.MediaPlayerControl mPlayer;
private Context mContext;
private View mAnchor;
private View mRoot;
private ProgressBar mProgress;
private TextView mEndTime, mCurrentTime;
private boolean mShowing;
private boolean mDragging;
private static final int sDefaultTimeout = 3000;
private static final int FADE_OUT = 1;
private static final int SHOW_PROGRESS = 2;
private boolean mUseFastForward;
private boolean mFromXml;
private boolean mListenersSet;
StringBuilder mFormatBuilder;
Formatter mFormatter;
private ImageButton mPauseButton;
private ImageButton mSubtitleButton;
private ImageButton mResizeButton;
private ImageButton mNextButton;
private ImageButton mPrevButton;
private final AccessibilityManager mAccessibilityManager;
public MyMediaController(Context context, AttributeSet attrs) {
super(context, attrs);
mRoot = null;
mContext = context;
mUseFastForward = true;
mFromXml = true;
mAccessibilityManager = (AccessibilityManager) context.getSystemService(Context.ACCESSIBILITY_SERVICE);
}
public MyMediaController(Context context, boolean useFastForward) {
super(context, useFastForward);
mUseFastForward = useFastForward;
mAccessibilityManager = (AccessibilityManager) context.getSystemService(Context.ACCESSIBILITY_SERVICE);
}
public MyMediaController(Context context) {
this(context, true);
mContext = context;
}
#Override
public void setMediaPlayer(MediaController.MediaPlayerControl player) {
mPlayer = player;
updatePausePlay();
}
#Override
public void setAnchorView(View view) {
mAnchor = view;
FrameLayout.LayoutParams frameParams = new FrameLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT
);
removeAllViews();
View v = makeControllerView();
addView(v, frameParams);
}
protected View makeControllerView() {
LayoutInflater inflate = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mRoot = inflate.inflate(R.layout.media_controller_layout, null);
initControllerView(mRoot);
return mRoot;
}
private void initControllerView(View mRoot) {
mPauseButton = mRoot.findViewById(R.id.pause);
if (mPauseButton != null) {
mPauseButton.requestFocus();
mPauseButton.setOnClickListener(mPauseListener);
}
mResizeButton = mRoot.findViewById(R.id.resize);
if (mResizeButton != null) {
mResizeButton.requestFocus();
mResizeButton.setOnClickListener(mResizeListener);
}
mSubtitleButton = mRoot.findViewById(R.id.subtitle);
if (mSubtitleButton != null)
{
mSubtitleButton.requestFocus();
mSubtitleButton.setOnClickListener(mSubtitleListener);
}
mNextButton = mRoot.findViewById(R.id.next);
if (mNextButton != null ) {
mNextButton.requestFocus();
mNextButton.setOnClickListener(mNextListener);
}
mPrevButton = mRoot.findViewById(R.id.prev);
if (mPrevButton != null ) {
mPrevButton.requestFocus();
mPrevButton.setOnClickListener(mPrevListener);
}
mProgress = mRoot.findViewById(R.id.mediacontroller_progress);
if (mProgress != null) {
if (mProgress instanceof SeekBar) {
SeekBar seeker = (SeekBar) mProgress;
seeker.setOnSeekBarChangeListener(mSeekListener);
}
mProgress.setMax(1000);
}
mEndTime = mRoot.findViewById(R.id.time);
mCurrentTime = mRoot.findViewById(R.id.time_current);
mFormatBuilder = new StringBuilder();
mFormatter = new Formatter(mFormatBuilder, Locale.getDefault());
}
public final View.OnClickListener mPauseListener = new OnClickListener() {
#Override
public void onClick(View v) {
doPauseResume();
show(sDefaultTimeout);
}
};
private void doPauseResume() {
if (mPlayer == null) {
return;
}
if (mPlayer.isPlaying()) {
mPlayer.pause();
} else {
mPlayer.start();
}
updatePausePlay();
}
private void updatePausePlay() {
if (mRoot == null || mPauseButton == null)
return;
if (mPlayer.isPlaying())
mPauseButton.setImageResource(R.drawable.ic_pause);
else
mPauseButton.setImageResource(R.drawable.ic_play);
}
public final View.OnClickListener mResizeListener = new OnClickListener() {
#Override
public void onClick(View v) {
//Todo
Toast.makeText(mContext,"Resize is clicked",Toast.LENGTH_SHORT).show();
}
};
public final View.OnClickListener mNextListener = new OnClickListener() {
#Override
public void onClick(View v) {
//Todo
Toast.makeText(mContext,"NextBtn is clicked",Toast.LENGTH_SHORT).show();
}
};
public final View.OnClickListener mPrevListener = new OnClickListener() {
#Override
public void onClick(View v) {
//Todo
Toast.makeText(mContext,"PreviousBtn is clicked",Toast.LENGTH_SHORT).show();
}
};
public final View.OnClickListener mSubtitleListener = new OnClickListener() {
#Override
public void onClick(View v) {
//Todo
Toast.makeText(mContext,"subtitleBtn is clicked",Toast.LENGTH_SHORT).show();
}
};
private final SeekBar.OnSeekBarChangeListener mSeekListener = new SeekBar.OnSeekBarChangeListener() {
#Override
public void onStartTrackingTouch(SeekBar bar) {
show(3600000);
mDragging = true;
// By removing these pending progress messages we make sure
// that a) we won't update the progress while the user adjusts
// the seekbar and b) once the user is done dragging the thumb
// we will post one of these messages to the queue again and
// this ensures that there will be exactly one message queued up.
removeCallbacks(mShowProgress);
}
#Override
public void onProgressChanged(SeekBar bar, int progress, boolean fromuser) {
if (!fromuser) {
// We're not interested in programmatically generated changes to
// the progress bar's position.
return;
}
long duration = mPlayer.getDuration();
long newposition = (duration * progress) / 1000L;
mPlayer.seekTo( (int) newposition);
if (mCurrentTime != null)
mCurrentTime.setText(stringForTime( (int) newposition));
}
#Override
public void onStopTrackingTouch(SeekBar bar) {
mDragging = false;
setProgress();
updatePausePlay();
show(sDefaultTimeout);
// Ensure that progress is properly updated in the future,
// the call to show() does not guarantee this because it is a
// no-op if we are already showing.
post(mShowProgress);
}
};
private int setProgress() {
if (mPlayer == null || mDragging) {
return 0;
}
int position = mPlayer.getCurrentPosition();
int duration = mPlayer.getDuration();
if (mProgress != null) {
if (duration > 0) {
// use long to avoid overflow
long pos = 1000L * position / duration;
mProgress.setProgress( (int) pos);
}
int percent = mPlayer.getBufferPercentage();
mProgress.setSecondaryProgress(percent * 10);
}
if (mEndTime != null)
mEndTime.setText(stringForTime(duration));
if (mCurrentTime != null)
mCurrentTime.setText(stringForTime(position));
return position;
}
private String stringForTime(int timeMs) {
int totalSeconds = timeMs / 1000;
int seconds = totalSeconds % 60;
int minutes = (totalSeconds / 60) % 60;
int hours = totalSeconds / 3600;
mFormatBuilder.setLength(0);
if (hours > 0) {
return mFormatter.format("%d:%02d:%02d", hours, minutes, seconds).toString();
} else {
return mFormatter.format("%02d:%02d", minutes, seconds).toString();
}
}
private final Runnable mShowProgress = new Runnable() {
#Override
public void run() {
int pos = setProgress();
if (!mDragging && mShowing && mPlayer.isPlaying()) {
postDelayed(mShowProgress, 1000 - (pos % 1000));
}
}
};
#Override
public void show(int timeout) {
if (!mShowing && mAnchor != null) {
setProgress();
if (mPauseButton != null) {
mPauseButton.requestFocus();
}
FrameLayout.LayoutParams tlp = new FrameLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT,
Gravity.BOTTOM
);
addView(this, tlp);
mShowing = true;
}
updatePausePlay();
// cause the progress bar to be updated even if mShowing
// was already true. This happens, for example, if we're
// paused with the progress bar showing the user hits play.
post(mShowProgress);
if (timeout != 0 && !mAccessibilityManager.isTouchExplorationEnabled()) {
removeCallbacks(mFadeOut);
postDelayed(mFadeOut, timeout);
}
}
#Override
public boolean isShowing() {
return mShowing;
}
/**
* Remove the controller from the screen.
*/
#Override
public void hide() {
if (mAnchor == null)
return;
if (mShowing) {
try {
removeCallbacks(mShowProgress);
removeView(this);
} catch (IllegalArgumentException ex) {
Log.w("MediaController", "already removed");
}
mShowing = false;
}
}
private final Runnable mFadeOut = new Runnable() {
#Override
public void run() {
hide();
}
};
#Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction())
{
case MotionEvent.ACTION_DOWN:
show(0);
break;
case MotionEvent.ACTION_UP:
show(sDefaultTimeout);
break;
case MotionEvent.ACTION_CANCEL:
hide();
break;
default:
break;
}
return true;
}
}
Plz someone suggest my the right way to do it. I realy need help.

Cannot resolve showQueston argument in getActivity().showQuestion inside my Fragment

I'm using activity class code to create a fragment of each. I was able to successfully change the Mainactivity class to main fragment with replacing this with getActivity() and adding view before each findmyID.
But I'm not able to convert showquestion which highlights in red color although I added getActivity() before it replacing Mainactivity.this which was before.
Here is the screenshot
Here is the whole code
public class question extends Fragment {
EditText question = null;
RadioButton answer1 = null;
RadioButton answer2 = null;
RadioButton answer3 = null;
RadioButton answer4 = null;
RadioGroup answers = null;
Button finish = null;
int selectedAnswer = -1;
int quesIndex = 0;
int numEvents = 0;
int selected[] = null;
int correctAns[] = null;
boolean review =false;
Button prev, next = null;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.question, container, false);
TableLayout quizLayout = (TableLayout) view.findViewById(R.id.quizLayout);
quizLayout.setVisibility(View.INVISIBLE);
try {
question = (EditText) view.findViewById(R.id.question);
answer1 = (RadioButton) view.findViewById(R.id.a0);
answer2 = (RadioButton) view.findViewById(R.id.a1);
answer3 = (RadioButton) view.findViewById(R.id.a2);
answer4 = (RadioButton) view.findViewById(R.id.a3);
answers = (RadioGroup) view.findViewById(R.id.answers);
RadioGroup questionLayout = (RadioGroup)view.findViewById(R.id.answers);
Button finish = (Button)view.findViewById(R.id.finish);
finish.setOnClickListener(finishListener);
prev = (Button)view.findViewById(R.id.Prev);
prev.setOnClickListener(prevListener);
next = (Button)view.findViewById(R.id.Next);
next.setOnClickListener(nextListener);
selected = new int[QuizFunActivity.getQuesList().length()];
Arrays.fill(selected, -1);
correctAns = new int[QuizFunActivity.getQuesList().length()];
Arrays.fill(correctAns, -1);
this.showQuestion(0,review);
quizLayout.setVisibility(View.VISIBLE);
} catch (Exception e) {
Log.e("", e.getMessage().toString(), e.getCause());
}
return view;
}
private void showQuestion(int qIndex,boolean review) {
try {
JSONObject aQues = QuizFunActivity.getQuesList().getJSONObject(qIndex);
String quesValue = aQues.getString("Question");
if (correctAns[qIndex] == -1) {
String correctAnsStr = aQues.getString("CorrectAnswer");
correctAns[qIndex] = Integer.parseInt(correctAnsStr);
}
question.setText(quesValue.toCharArray(), 0, quesValue.length());
answers.check(-1);
answer1.setTextColor(Color.WHITE);
answer2.setTextColor(Color.WHITE);
answer3.setTextColor(Color.WHITE);
answer4.setTextColor(Color.WHITE);
JSONArray ansList = aQues.getJSONArray("Answers");
String aAns = ansList.getJSONObject(0).getString("Answer");
answer1.setText(aAns.toCharArray(), 0, aAns.length());
aAns = ansList.getJSONObject(1).getString("Answer");
answer2.setText(aAns.toCharArray(), 0, aAns.length());
aAns = ansList.getJSONObject(2).getString("Answer");
answer3.setText(aAns.toCharArray(), 0, aAns.length());
aAns = ansList.getJSONObject(3).getString("Answer");
answer4.setText(aAns.toCharArray(), 0, aAns.length());
Log.d("",selected[qIndex]+"");
if (selected[qIndex] == 0)
answers.check(R.id.a0);
if (selected[qIndex] == 1)
answers.check(R.id.a1);
if (selected[qIndex] == 2)
answers.check(R.id.a2);
if (selected[qIndex] == 3)
answers.check(R.id.a3);
setScoreTitle();
if (quesIndex == (QuizFunActivity.getQuesList().length()-1))
next.setEnabled(false);
if (quesIndex == 0)
prev.setEnabled(false);
if (quesIndex > 0)
prev.setEnabled(true);
if (quesIndex < (QuizFunActivity.getQuesList().length()-1))
next.setEnabled(true);
if (review) {
Log.d("review",selected[qIndex]+""+correctAns[qIndex]);;
if (selected[qIndex] != correctAns[qIndex]) {
if (selected[qIndex] == 0)
answer1.setTextColor(Color.RED);
if (selected[qIndex] == 1)
answer2.setTextColor(Color.RED);
if (selected[qIndex] == 2)
answer3.setTextColor(Color.RED);
if (selected[qIndex] == 3)
answer4.setTextColor(Color.RED);
}
if (correctAns[qIndex] == 0)
answer1.setTextColor(Color.GREEN);
if (correctAns[qIndex] == 1)
answer2.setTextColor(Color.GREEN);
if (correctAns[qIndex] == 2)
answer3.setTextColor(Color.GREEN);
if (correctAns[qIndex] == 3)
answer4.setTextColor(Color.GREEN);
}
} catch (Exception e) {
Log.e(this.getClass().toString(), e.getMessage(), e.getCause());
}
}
private View.OnClickListener finishListener = new View.OnClickListener() {
public void onClick(View v) {
setAnswer();
//Calculate Score
int score = 0;
for(int i=0; i<correctAns.length; i++){
if ((correctAns[i] != -1) && (correctAns[i] == selected[i]))
score++;
}
AlertDialog alertDialog;
alertDialog = new AlertDialog.Builder(getActivity()).create();
alertDialog.setTitle("Score");
alertDialog.setMessage((score) +" out of " + (QuizFunActivity.getQuesList().length()));
alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "Retake", new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int which) {
review = false;
quesIndex=0;
getActivity().showQuestion(0, review);
}
});
alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "Review", new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int which) {
review = true;
quesIndex=0;
getActivity().showQuestion(0, review);
}
});
alertDialog.setButton(AlertDialog.BUTTON_NEGATIVE,"Quit", new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int which) {
review = false;
getActivity().finish();
}
});
alertDialog.show();
}
};
private void setAnswer() {
if (answer1.isChecked())
selected[quesIndex] = 0;
if (answer2.isChecked())
selected[quesIndex] = 1;
if (answer3.isChecked())
selected[quesIndex] = 2;
if (answer4.isChecked())
selected[quesIndex] = 3;
Log.d("",Arrays.toString(selected));
Log.d("",Arrays.toString(correctAns));
}
private View.OnClickListener nextListener = new View.OnClickListener() {
public void onClick(View v) {
setAnswer();
quesIndex++;
if (quesIndex >= QuizFunActivity.getQuesList().length())
quesIndex = QuizFunActivity.getQuesList().length() - 1;
showQuestion(quesIndex,review);
}
};
private View.OnClickListener prevListener = new View.OnClickListener() {
public void onClick(View v) {
setAnswer();
quesIndex--;
if (quesIndex < 0)
quesIndex = 0;
showQuestion(quesIndex,review);
}
};
private void setScoreTitle() {
getActivity().setTitle("SciQuiz3 " + (quesIndex+1)+ "/" + QuizFunActivity.getQuesList().length());
}
}
Any help is well appreciated. Thanks in advance.
getActivity() returns Activity. So cast it before use.
((YourActivity) getActivity()).showQuestion(...);
Make sure showQuestion() method is public in YourActivity.

Sharing Intent Not working Properly

I have one quote application. I have implemented share and copy function in it. I am facing issue is that I am not getting shared first time sharing quote. Means if there 50 quote in list and if I try to share any quote from list than it is not sharing anything. after that if I move on another quote and try to sharing than its working fine. I have same issue in copy function also. I also face some time issue like if I share quote number 50 than its sharing another number quote. Please help me for solve the bug. Thanks
My Activity for it is like below.
public class QuoteDialogActivity extends Activity {
DAO db;
static final String KEY_ID = "_quid";
static final String KEY_TEXT = "qu_text";
static final String KEY_AUTHOR = "au_name";
static final String KEY_PICTURE = "au_picture";
static final String KEY_PICTURE_SDCARD = "au_picture_sdcard";
static final String KEY_FAVORITE = "qu_favorite";
static final String KEY_WEB_ID = "au_web_id";
ArrayList<HashMap<String, String>> quotesList;
HashMap<String, String> map;
ImageButton btnnext,btnprev,star,copy;
int pos,lstcount = 0;
ScrollView ll_quote;
String quote_id;
TextView text;
String quText, quAuthor, quPicture, quFavorite,quoteShare;
int auPictureSDCard;
String isFavorite;
String auPictureDir;
String siteUrl;
private ImageLoader imgLoader;
/**
* Register your here app https://dev.twitter.com/apps/new and get your
* consumer key and secret
* */
String TWITTER_CONSUMER_KEY;
String TWITTER_CONSUMER_SECRET;
// Preference Constants
static String PREFERENCE_NAME = "twitter_oauth";
static final String PREF_KEY_OAUTH_TOKEN = "oauth_token";
static final String PREF_KEY_OAUTH_SECRET = "oauth_token_secret";
static final String PREF_KEY_TWITTER_LOGIN = "isTwitterLogedIn";
// Twitter oauth urls
static final String URL_TWITTER_AUTH = "auth_url";
static final String URL_TWITTER_OAUTH_VERIFIER = "oauth_verifier";
static final String URL_TWITTER_OAUTH_TOKEN = "oauth_token";
static final String PREF_KEY_FACEBOOK_LOGIN = "isFacebookLogedIn";
Typeface tf;
// Internet Connection detector
private ConnectionDetector cd;
// Alert Dialog Manager
AlertDialogManager alert = new AlertDialogManager();
String quote;
ProgressDialog pDialog;
private SharedPreferences mSharedPreferences;
private static SharedPreferences facebookPreferences, twitterPreferences;
Cursor c, c2;
private static final List<String> PERMISSIONS = Arrays.asList("publish_actions");
private static final String PENDING_PUBLISH_KEY = "pendingPublishReauthorization";
private boolean pendingPublishReauthorization = false;
//private UiLifecycleHelper uiHelper;
// ==============================================================================
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
imgLoader = new ImageLoader(this);
//TWITTER_CONSUMER_KEY = getResources().getString(R.string.TWITTER_CONSUMER_KEY);
//TWITTER_CONSUMER_SECRET = getResources().getString(R.string.TWITTER_CONSUMER_SECRET);
// uiHelper = new UiLifecycleHelper(this, callback);
//uiHelper.onCreate(savedInstanceState);
mSharedPreferences = getApplicationContext().getSharedPreferences("MyPref", 0);
//facebookPreferences = getApplicationContext().getSharedPreferences("facebookPref", 0);
//twitterPreferences = getApplicationContext().getSharedPreferences("twitterPref", 0);
db = new DAO(this);
db.open();
c2 = db.getSettings();
if (getIntent().getIntExtra("isQOTD", 0) == 1) {
c = db.getOneQuote(mSharedPreferences.getString("QOTD", ""));
} else {
c = db.getOneQuote(getIntent().getStringExtra("QuoteId"));
}
// if (c.getCount() != 0) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.quote_dialog);
// ============================ check if user want to display
// ============================ background image for quote
if (c2.getString(c2.getColumnIndex("background")).equals("1")) {
Random random = new Random();
int idNumber = random.nextInt(20 - 1 + 1) + 1;
RelativeLayout layout = (RelativeLayout) findViewById(R.id.RelativeLayout1);
Drawable d = null;
try {
View topShadow = (View) findViewById(R.id.topShadow);
View bottomShadow = (View) findViewById(R.id.bottomShadow);
topShadow.setVisibility(View.INVISIBLE);
bottomShadow.setVisibility(View.INVISIBLE);
d = Drawable.createFromStream(getAssets().open("backgrounds/" + String.valueOf(idNumber) + ".jpg"),
null);
layout.setBackgroundDrawable(d);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
// ===========================================================================================
quText = c.getString(c.getColumnIndex(KEY_TEXT));
quAuthor = c.getString(c.getColumnIndex(KEY_AUTHOR));
quPicture = c.getString(c.getColumnIndex(KEY_PICTURE));
auPictureSDCard = c.getInt(c.getColumnIndex(KEY_PICTURE_SDCARD));
quFavorite = c.getString(c.getColumnIndex(KEY_FAVORITE));
text = (TextView) findViewById(R.id.text); // title
// tf = Typeface.createFromAsset(getAssets(), "fonts/devnew.ttf");
//text.setTypeface(tf);
// author = (TextView) findViewById(R.id.author); // author
// picture = (ImageView) findViewById(R.id.picture); // thumb
text.setText(quText);
// author.setText("- " + quAuthor.trim());
// if (auPictureSDCard == 0) {
// AssetManager assetManager = getAssets();
// InputStream istr = null;
// try {
// istr = assetManager.open("authors_pics/" + quPicture);
// } catch (IOException e) {
// Log.e("assets", assetManager.toString());
// e.printStackTrace();
// }
// Bitmap bmp = BitmapFactory.decodeStream(istr);
// picture.setImageBitmap(bmp);
// } else {
// siteUrl = getResources().getString(R.string.siteUrl);
//
// auPictureDir = siteUrl + "global/uploads/authors/";
// imgLoader.DisplayImage(
// auPictureDir + quPicture, picture);
// }
AssetManager assetManager = getAssets();
InputStream istr = null;
try {
istr = assetManager.open("authors_pics/" + quPicture);
} catch (IOException e) {
Log.e("assets", assetManager.toString());
e.printStackTrace();
}
// Bitmap bmp = BitmapFactory.decodeStream(istr);
// picture.setImageBitmap(bmp);
final ImageButton dismiss = (ImageButton) findViewById(R.id.close);
dismiss.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
finish();
}
});
//=============================Next Button and Prev Button
star = (ImageButton) findViewById(R.id.star);
btnnext = (ImageButton)findViewById(R.id.nextButton);
btnprev = (ImageButton)findViewById(R.id.PrevioustButton);
pos= getIntent().getIntExtra("Pos",0);
quote_id = getIntent().getStringExtra("QuoteId");
lstcount = getIntent().getIntExtra("LstCount",0);
#SuppressWarnings("unchecked")
final ArrayList<HashMap<String, String>> quotesList =(ArrayList<HashMap<String, String>>) getIntent().getSerializableExtra("Quotes");
btnnext.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
if(pos == lstcount)
{
Toast.makeText(getApplicationContext(), "End of List", Toast.LENGTH_SHORT).show();
}
else
{
int p = pos+1;
text.setText(quotesList.get(pos).get(KEY_TEXT));
quFavorite = quotesList.get(pos).get(KEY_FAVORITE);
quoteShare = quotesList.get(pos).get(KEY_TEXT);
Log.e("ErrorMsg", "quoteShare is: " + quoteShare);
quote_id = quotesList.get(pos).get(QuoteDialogActivity.KEY_ID);
isFavorite = quFavorite;
if (isFavorite.equals("0")) {
star.setImageResource(R.drawable.star_off);
} else {
star.setImageResource(R.drawable.star_on);
}
pos = p;
FirstFav();//new
Log.i("quote is",quote_id);
}
}
});
btnprev.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
if(pos == 1 ||pos == 0)
{
Toast.makeText(getApplicationContext(), "Start of List",Toast.LENGTH_SHORT).show();
}
else
{
int p = pos-1;
text.setText(quotesList.get(p-1).get(KEY_TEXT));
quFavorite = quotesList.get(p-1).get(KEY_FAVORITE);
quote_id = quotesList.get(p-1).get(QuoteDialogActivity.KEY_ID);
isFavorite = quFavorite;
if (isFavorite.equals("0")) {
star.setImageResource(R.drawable.star_off);
} else {
star.setImageResource(R.drawable.star_on);
}
pos = p;
FirstFav();
}
}
});
//======================================================= Swipe
ll_quote = (ScrollView)findViewById(R.id.scrollView1);
ll_quote.setOnTouchListener(new OnTouchListener() {
int downX, upX;
#Override
public boolean onTouch(View arg0, MotionEvent event) {
// TODO Auto-generated method stub
if (event.getAction() == MotionEvent.ACTION_DOWN) {
downX = (int) event.getX();
Log.i("event.getX()", " downX " + downX);
return true;
}
else if (event.getAction() == MotionEvent.ACTION_UP) {
upX = (int) event.getX();
Log.i("event.getX()", " upX " + downX);
if (upX - downX > 100) {
if(pos == 0 || pos == 1)
{
Toast.makeText(getApplicationContext(), "Start of List",Toast.LENGTH_SHORT).show();
}
else
{
int p = pos-1;
quFavorite = quotesList.get(p-1).get(KEY_FAVORITE);
quote_id = quotesList.get(p-1).get(QuoteDialogActivity.KEY_ID);
isFavorite = quFavorite;
if (isFavorite.equals("0")) {
star.setImageResource(R.drawable.star_off);
} else {
star.setImageResource(R.drawable.star_on);
}
text.setText(quotesList.get(p-1).get(KEY_TEXT));
pos = p;
FirstFav();
}
}
else if (downX - upX > -100) {
if(pos == lstcount)
{
Toast.makeText(getApplicationContext(), "End of List", Toast.LENGTH_SHORT).show();
}
else
{
int p = pos+1;
quFavorite = quotesList.get(pos).get(KEY_FAVORITE);
quote_id = quotesList.get(pos).get(QuoteDialogActivity.KEY_ID);
isFavorite = quFavorite;
if (isFavorite.equals("0")) {
star.setImageResource(R.drawable.star_off);
} else {
star.setImageResource(R.drawable.star_on);
}
text.setText(quotesList.get(pos).get(KEY_TEXT));
pos = p;
FirstFav();
}
}
return true;
}
return false;
}
});
// ========================== share button
final ImageButton share = (ImageButton) findViewById(R.id.share);
share.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT,pos);
sendIntent.setType("text/plain");
startActivity(sendIntent);
}
});
//copy button
final ImageButton copyy = (ImageButton) findViewById(R.id.copy);
copyy.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
ClipData clip = ClipData.newPlainText("simple text",quoteShare);
clipboard.setPrimaryClip(clip);
Toast.makeText(getApplicationContext(), "Status Copied",
Toast.LENGTH_LONG).show();
}
});
// ========================== set as favorite and unfavorite
isFavorite = quFavorite;
if (isFavorite.equals("0")) {
star.setImageResource(R.drawable.star_off);
} else {
star.setImageResource(R.drawable.star_on);
}
star.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (isFavorite.equals("0")) {
isFavorite = "1";
star.setImageResource(R.drawable.star_on);
} else {
isFavorite = "0";
star.setImageResource(R.drawable.star_off);
}
if (getIntent().getIntExtra("isQOTD", 0) == 1) {
db.addOrRemoveFavorites(mSharedPreferences.getString("QOTD", ""), isFavorite);
} else {
// Log.i("quotes",quotesList.get(pos).get(String.valueOf(KEY_WEB_ID))+"POS"+pos+"quid"+quotesList.get(pos).get(KEY_ID));
db.addOrRemoveFavorites(quote_id, isFavorite);
// db.addOrRemoveFavorites(getIntent().getStringExtra("QuoteId"), isFavorite);
if (getIntent().getIntExtra("quotesType", 0) == 2 && isFavorite.equals("0")) {
Intent i = new Intent(QuoteDialogActivity.this, QuotesActivity.class);
i.putExtra("quotesType", 2);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
i.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
finish();
startActivity(i);
}
}
}
});
// }
}
// ==============================================================================
public void FirstFav()
{
String Image_id=quote_id;
quFavorite = db.getFavQuotes(quote_id);
if(quFavorite.length()>0)
isFavorite = quFavorite;
else
isFavorite = "0";
if (isFavorite.equals("0")) {
star.setImageResource(R.drawable.star_off);
} else {
star.setImageResource(R.drawable.star_on);
}
}
//===================================================================================
}
Thanks

Categories

Resources