Image slider moving fast in android when comeback from another activity - android

In my android app I have an image slider using viewpager,which changes images every 2.5 seconds in the main activity,it works fine when I open the app,but the problem is when I jump to another Activity from the MainActivity and come back it,starts to move the images in the slides very fast,as much as I jump to another activity the sliding become more faster.please help.
This is where I have included my 3 slider images
slidelist.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ImageView
android:id="#+id/image1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:adjustViewBounds="true"
android:layout_gravity="center"
android:src="#drawable/slidetwo"
android:scaleType="centerCrop"/>
<ImageView
android:id="#+id/image2"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:adjustViewBounds="true"
android:layout_gravity="center"
android:src="#drawable/slideone"
android:scaleType="centerCrop"/>
<ImageView
android:id="#+id/image3"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:adjustViewBounds="true"
android:layout_gravity="center"
android:src="#drawable/slidethree"
android:scaleType="centerCrop"/>
</FrameLayout>
This the slider layout in content main.xml(included in activity)
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="250dp"
android:layout_below="#+id/linearone">
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_alignParentTop="true" />
<me.relex.circleindicator.CircleIndicator
android:id="#+id/indicator"
android:layout_width="match_parent"
android:layout_height="48dp"
android:layout_alignParentBottom="true"/>
</RelativeLayout>
The following is the adpater class
import android.content.Context;
import android.support.v4.view.PagerAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import com.example.rimapps.icar_iisr_turmeric.R;
import java.util.ArrayList;
public class SlideAdapter extends PagerAdapter {
private ArrayList<Integer> images;
private LayoutInflater inflater;
private Context context;
public SlideAdapter(Context context, ArrayList<Integer> images) {
this.context = context;
this.images=images;
inflater = LayoutInflater.from(context);
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
}
#Override
public int getCount() {
return images.size();
}
#Override
public Object instantiateItem(ViewGroup view, int position) {
View myImageLayout = inflater.inflate(R.layout.slidelist, view, false);
ImageView myImage1 = (ImageView) myImageLayout.findViewById(R.id.image1);
ImageView myImage2 = (ImageView) myImageLayout.findViewById(R.id.image2);
ImageView myImage3 = (ImageView) myImageLayout.findViewById(R.id.image3);
myImage1.setImageResource(images.get(position));
myImage2.setImageResource(images.get(position));
myImage3.setImageResource(images.get(position));
view.addView(myImageLayout, 0);
return myImageLayout;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view.equals(object);
}
}
This is my MainActivity class and here I have defined the timer for the slider
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Bundle;
import android.os.Handler;
import android.support.design.internal.NavigationMenuItemView;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import com.example.rimapps.icar_iisr_turmeric.R;
import com.example.rimapps.icar_iisr_turmeric.control.ButtonAdapter;
import com.example.rimapps.icar_iisr_turmeric.control.SlideAdapter;
import com.example.rimapps.icar_iisr_turmeric.model.ContentsDep;
import com.example.rimapps.icar_iisr_turmeric.utils.LocaleHelper;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import me.relex.circleindicator.CircleIndicator;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
CircleIndicator indicator;
int period=2500, delay = 2500;
private static ViewPager mPager;
private static int currentPage = 0;
private static final Integer[] slide = {R.drawable.slideone, R.drawable.slidetwo, R.drawable.slidethree};
private ArrayList<Integer> slidearray = new ArrayList<Integer>();
Timer swipeTimer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
}
//Image slider function//
private void init() {
for (int i = 0; i < slide.length; i++)
slidearray.add(slide[i]);
mPager = (ViewPager) findViewById(R.id.pager);
mPager.setAdapter(new SlideAdapter(MainActivity.this, slidearray));
CircleIndicator indicator = (CircleIndicator) findViewById(R.id.indicator);
indicator.setViewPager(mPager);
// Auto start of viewpager
final Handler handler = new Handler();
final Runnable Update = new Runnable() {
public void run() {
if (currentPage == slide.length) {
currentPage = 0;
}
mPager.setCurrentItem(currentPage++, true);
}
};
swipeTimer =new Timer();
swipeTimer.schedule(new
TimerTask() {
#Override
public void run () {
Log.d("hjgv","yughi");
handler.post(Update);
}
},delay,period);
}
#Override
protected void onStop() {
super.onStop();
// swipeTimer.cancel();
delay=0;
period=0;
}
#Override
protected void onRestart() {
super.onRestart();
delay=2500;
period=2500;
}
}

The problem is in your Timer.
when you go another fragment or activity then back to that fragment you must have to cancel your timer ondestroyview because when you back to fragment your oncreateview is call again so timer are initialise and then speed is multiple by 2 time.this happens everytime.
This code in kotlin.
override fun onDestroyView() {
if(swipeTimer != null) {
swipeTimer.cancel()
}
super.onDestroyView()
}
Hope this help you

Just call cancel the instance of Timer in your ondestryView() method
#Override
public void onDestroyView() {
super.onDestroyView();
if(swipeTimer != null) {
swipeTimer.cancel();
}
}

Related

setCustomView didnot work for tablayout in android studio

I have a tablayout with 5 tabs. Each tab has an icon and title. I want to change color of icon and title for tab that is selected and tab that is un-selected. For this i try using custom tabs but it didn't work. Here is my code for custom_tab.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<ImageView
android:layout_width="20dp"
android:layout_height="20dp"
android:layout_gravity="center"
android:id="#+id/tabIcon"/>
<com.prj.shopt.CustomTextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#C1C1C1"
android:gravity="center"
android:id="#+id/tabTitle"/>
</LinearLayout>
and my code in Home2Activity:
package com.prj.shopt;
import android.graphics.Typeface;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.AppCompatTextView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class Home2Activity extends AppCompatActivity implements TabLayout.OnTabSelectedListener {
private TabLayout tabs;
private ViewPager viewPager;
private HomeTabsAdapter tabsAdapter;
private int[] activeIcons={R.drawable.homeactive,R.drawable.category_highlighted,R.drawable.heart_highlighted,
R.drawable.basketactive,R.drawable.avatar_highlighted};
private int[] deactiveIcons={R.drawable.homedeactive,R.drawable.category_default,R.drawable.heart_default,
R.drawable.basketdeactive,R.drawable.avatar_default};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home2);
tabs=findViewById(R.id.homeTabs);
viewPager=findViewById(R.id.tabsViewPager);
setupViewPager();
tabs.setupWithViewPager(viewPager);
setupTabIcons();
tabs.addOnTabSelectedListener(this);
}
private void setupTabIcons(){
if(tabs.getTabCount()<5)
return;
int len=activeIcons.length;
for(int j=0;j<len;j++) {
//tabs.getTabAt(j).setIcon(deactiveIcons[j]);
tabs.getTabAt(j).setCustomView(HomeTabsAdapter.getTabView(deactiveIcons[j], R.color.tab_inactive, "test", Home2Activity.this,tabs));
}
tabs.getTabAt(0).setCustomView(HomeTabsAdapter.getTabView(activeIcons[0],R.color.tab_active,"test",Home2Activity.this,tabs));
}
private void setupViewPager(){
tabsAdapter=new HomeTabsAdapter(getSupportFragmentManager());
viewPager.setAdapter(tabsAdapter);
setupFragments();
}
private void setupFragments() {
for(int i=0;i<5;i++)
tabsAdapter.addFragment(new FavFragment(),getResources().getString(R.string.favTab));
}
#Override
public void onTabSelected(TabLayout.Tab tab) {
//tab.setIcon(activeIcons[tab.getPosition()]);
tab.setCustomView(HomeTabsAdapter.getTabView(activeIcons[tab.getPosition()],R.color.tab_active,"test",Home2Activity.this,tabs));
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
//tab.setIcon(deactiveIcons[tab.getPosition()]);
tab.setCustomView(HomeTabsAdapter.getTabView(deactiveIcons[tab.getPosition()],R.color.tab_inactive,"test",Home2Activity.this,tabs));
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
//tab.setIcon(activeIcons[tab.getPosition()]);
tab.setCustomView(HomeTabsAdapter.getTabView(activeIcons[tab.getPosition()],R.color.tab_active,"test",Home2Activity.this,tabs));
}
}
and Here is my adapter(HomeTabsAdapter.java):
import android.content.Context;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import org.w3c.dom.Text;
import java.util.ArrayList;
import java.util.List;
public class HomeTabsAdapter extends FragmentPagerAdapter {
List<Fragment> fragments;
List<String> tabTitles;
public HomeTabsAdapter(FragmentManager fm) {
super(fm);
fragments=new ArrayList<>();
tabTitles=new ArrayList<>();
}
#Override
public Fragment getItem(int position) {
return fragments.get(position);
}
#Override
public int getCount() {
return fragments.size();
}
public void addFragment(Fragment fragment,String title){
fragments.add(fragment);
tabTitles.add(title);
notifyDataSetChanged();
}
public static View getTabView(int imageId, int color, String title, Context context, TabLayout tabLayout){
View v= LayoutInflater.from(context).inflate(R.layout.custom_tab,tabLayout,false);
TextView tabTitle=v.findViewById(R.id.tabTitle);
tabTitle.setText(title);
tabTitle.setTextColor(color);
tabTitle.setTypeface(Utility.getFontTypeFace(context));
ImageView icon=(v.findViewById(R.id.tabIcon));
icon.setImageResource(0);
icon.setImageResource(imageId);
return v;
}
#Override
public CharSequence getPageTitle(int position) {
return tabTitles.get(position);
}
}
And the result is icons with fix color and also titles with fixed color. Nothing change with select and unselect the tabs.
Thanks for any help
Use this method:-
private void setCustomTab(TabLayout tabLayout, int index, String title) {
TextView tab_home = (TextView) LayoutInflater.from(getActivity()).inflate(R.layout.custome_tab, null);
tab_home.setText(title);
tabLayout.getTabAt(index).setCustomView(tab_home);
}
Use this above method like below:-
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
setCustomTab(tabLayout, 0, "Upcoming");
setCustomTab(tabLayout, 1, "Completed");

Android Picasso Fragment Pic from URL

I've got problem to load pic from URL do my fragment by Picasso.
When I start app it's start without any errors but pic is not loading.
My app has one MainActivity and three fragments. Below I paste xml of mainlayout and one fragment class. The best for me is this scenario:
when user click button on fragment three(red on image), pic will load from url to imageView which is located on fragment two (yellow on image) above of fragment three.
Please help
package testowy.com.testowyfragment2;
import android.app.Activity;
import android.app.Fragment;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import com.squareup.picasso.Picasso;
/**
* Created by Administrator on 2015-07-04.
*/
public class Klasadown extends Fragment {
private klasadownlistener listener;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragmentdown, container, false);
ImageView img = (ImageView) view.findViewById(R.id.imgVV);
Context c = getActivity().getApplicationContext();
Picasso.with(c).load("http://inthecheesefactory.com/uploads/source/glidepicasso/cover.jpg")
.fit().into(img);
View.OnClickListener clickListener = new View.OnClickListener() {
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnMenu:
updateText("Menu");
SetImage();
break;
case R.id.btnKontakt:
updateText("Kontakt");
break;
default:
break;
}
}
};
Button btnMenu = (Button) view.findViewById(R.id.btnMenu);
Button btnKontakt = (Button) view.findViewById(R.id.btnKontakt);
btnKontakt.setOnClickListener(clickListener);
btnMenu.setOnClickListener(clickListener);
return view;
}
public interface klasadownlistener {
public void onItemSelected(String txt);
}
private void updateText(String txt) {
listener.onItemSelected(txt);
}
public void SetImage() {
ImageView img = (ImageView) getView().findViewById(R.id.imgVV);
Picasso.with(getActivity().getApplicationContext()).load("http://inthecheesefactory.com/uploads/source/glidepicasso/cover.jpg").into(img);
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
if (activity instanceof klasadownlistener) {
listener = (klasadownlistener) activity;
} else {
throw new ClassCastException(activity.toString() + " musi implementowa� interfejs: OverviewFragment.OverviewFragmentActivityListener");
}
}
}
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity">
<fragment
android:id="#+id/fragmentup"
class="testowy.com.testowyfragment2.Klasaup"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="5">
</fragment>
<fragment
android:id="#+id/fragmentcenter"
class="testowy.com.testowyfragment2.Klasacenter"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="3">
</fragment>
<fragment
android:id="#+id/fragmetdown"
class="testowy.com.testowyfragment2.Klasadown"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="3">
</fragment>
</LinearLayout>
package testowy.com.testowyfragment2;
import android.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
/**
* Created by Administrator on 2015-07-04.
*/
public class Klasacenter extends Fragment {
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater
.inflate(R.layout.fragmentcenter, container, false);
return view;
}
public void SetText(String txt){
TextView view = (TextView) getView().findViewById(R.id.fragmentcenterText);
view.setText(txt);
}
}
package testowy.com.testowyfragment2;
import android.app.Activity;
import android.os.Bundle;
import android.widget.ImageView;
import com.squareup.picasso.Picasso;
public class MainActivity extends Activity implements Klasadown.klasadownlistener{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public void onItemSelected(String txt) {
Klasacenter fragment = (Klasacenter) getFragmentManager()
.findFragmentById(R.id.fragmentcenter);
// sprawdzamy czy fragment istnieje w tej aktywno�ci
if (fragment != null && fragment.isInLayout()) {
// ustawiamy teskt we fragmencie
fragment.SetText(txt);
ImageView img = (ImageView) findViewById(R.id.imgV);
Picasso.with(this).load("http://inthecheesefactory.com/uploads/source/glidepicasso/cover.jpg").fit().into(img);
}
}
}
It's stupid to say but I forget to add internet permission:)
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
now everything is ok!

Changing Gridview Size from Preferences when Implementing Fragments

I had a gridview activity where I was populating the gridview with a custom object (a picture with some custom methods and an onclick listener). I could change the gridview size from the preferences menu. Everything worked beautifully.
I have since added some complexity to the code. Instead of using the normal Activity class, I am now using the FragmentActivity class, a fragmentPageAdapter, and a fragment to which my gridview is bound. This is because eventually I want the app to allow the user "swipe" from fragment to fragment.
Since using the fragment in this way, I am noticing a repeatable bug whenever I try to resize the gridview from the preferences menu: some of the objects get resized properly, other elements do not resize. Instead, they keep the same size that they had prior to changing the preference. Here is a screenshot:
This only happens when I try resizing from the preferences menu. Other calls to my resize method, such as on a configuration change, resize all of the gridview elements correctly.
I would appreciate any suggestions!
Here is my Code:
MAIN ACTIVITY:
package com.KhalidSorensen.animalsounds;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.content.res.Configuration;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.GridView;
public class MainActivity extends FragmentActivity implements OnSharedPreferenceChangeListener{
private MyFragment m_myFragment = new MyFragment();
private ViewPager m_viewPager;
private static SharedPreferences m_prefs;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
m_prefs = PreferenceManager.getDefaultSharedPreferences(this);
m_prefs.registerOnSharedPreferenceChangeListener(this);
setContentView(R.layout.activity_main);
m_viewPager = (ViewPager) findViewById(R.id.pager);
m_viewPager.setAdapter(new MyAdapter(getSupportFragmentManager(), m_myFragment));
}
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
Log.i("Khalid","MainActivity: onSharedPreferenceChanged");
if (key.equals("key_prefs_enable_lscape")){
//do nothing for now
}else if (key.equals("key_prefs_picture_size")){
SetColumnWidth(m_myFragment.getM_gridView());
}
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
Log.i("Khalid","FragAnimalSounds: onConfigurationChanged");
SetColumnWidth(m_myFragment.getM_gridView());
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
Log.i("Khalid","MainActivity: onCreateOptionsMenu");
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.options_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.lbl_opt_menu_settings:
Intent i = new Intent("android.intent.action.PREFERENCES");
startActivity(i);
break;
case R.id.lbl_opt_menu_quit:
finish();
break;
default:
finish();
break;
}
return true;
}
public static void SetColumnWidth(GridView GV) {
Log.i("Khalid","MainActivity: SetColumnWidth");
int NumColumns, DesiredColumnWidth;
//Get the desired number of columns from the key prefs
NumColumns = Integer.parseInt(m_prefs.getString("key_prefs_picture_size","2"));
//Determine the desired column width
if (NumColumns == 1){
DesiredColumnWidth = 200;
}else if (NumColumns == 2){
DesiredColumnWidth = 100;
}else{
DesiredColumnWidth = 50;
}
//Set the desired column width
GV.setColumnWidth(DesiredColumnWidth);
}
}
class MyAdapter extends FragmentPagerAdapter{
Fragment m_frag_A = null;
public MyAdapter(FragmentManager fm, Fragment A) {
super(fm);
m_frag_A = A;
}
#Override
public Fragment getItem(int i) {
return m_frag_A; //only 1 item for now
}
#Override
public int getCount() {
return 1;
}
#Override
public CharSequence getPageTitle(int i) {
return "Title Frag A"; //only 1 item for now
}
}
MY FRAGMENT (THERE IS ONLY ONE FOR NOW):
package com.KhalidSorensen.animalsounds;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.GridView;
public class MyFragment extends Fragment {
private GridView m_gridView;
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
Log.i("Khalid","FragAnimalSounds: onCreateView");
View view = inflater.inflate(R.layout.activity_animal_sounds, container, false);
m_gridView = (GridView) view.findViewById(R.id.lbl_gridView);
m_gridView.setAdapter(new VivzAdapter(view.getContext()));
MainActivity.SetColumnWidth(m_gridView);
return view;
}
public GridView getM_gridView() {
return m_gridView;
}
}
MY GRIDVIEW ADAPTER:
package com.KhalidSorensen.animalsounds;
import java.util.ArrayList;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
public class VivzAdapter extends BaseAdapter {
private Context m_context;
private ArrayList<AnimalKind> m_list = new ArrayList<AnimalKind>();
VivzAdapter(Context ctx) {
m_context = ctx;
int[] animalphotos = { R.drawable.cat_1, R.drawable.cow_1,
R.drawable.dog_1, R.drawable.donkey_1, R.drawable.duck_1,
R.drawable.peacock_1, R.drawable.rooster_1, R.drawable.seal_1 };
for (int i = 0; i <= 7; i++) {
AnimalKind animalKind = new AnimalKind(m_context, animalphotos[i]);
m_list.add(animalKind);
}
}
#Override
public int getCount() {
return m_list.size();
}
#Override
public AnimalKind getItem(int position) {
return m_list.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int i, View v, ViewGroup vg) {
return m_list.get(i);
}
}
MY CUSTOM OBJECT CLASS. THESE OBJECTS ARE POPULATING THE GRIDVIEW:
package com.KhalidSorensen.animalsounds;
import android.content.Context;
import android.graphics.Color;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
public class AnimalKind extends ImageView implements OnClickListener{
private int m_imageId;
public AnimalKind(Context ctx, int imageId) {
super(ctx);
m_imageId = imageId;
super.setImageResource(imageId);
super.setAdjustViewBounds(true);
super.setScaleType(ImageView.ScaleType.FIT_XY);
super.setPadding(1, 1, 1, 1);
super.setBackgroundColor(Color.BLACK);
super.setOnClickListener(this);
}
//#Override
public void onClick(View v) {
//Do Something
}
#Override
public void setPressed(boolean pressed) {
//Do Something
}
public int getM_imageId() {
return m_imageId;
}
}
MY PREFERENCE ACTIVITY:
package com.KhalidSorensen.animalsounds;
import android.os.Bundle;
import android.preference.PreferenceActivity;
import android.util.Log;
public class Preferences extends PreferenceActivity {
#SuppressWarnings("deprecation")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
Log.i("Khalid", "Preferences: onCreate");
}
}
MY XML FOR MY MAIN ACTIVITY:
<android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<android.support.v4.view.PagerTitleStrip
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/lbl_title"
android:background="#33B5E5"
android:layout_gravity="top"
android:paddingTop="0dp"
android:paddingBottom="0dp"> "
</android.support.v4.view.PagerTitleStrip>
</android.support.v4.view.ViewPager>
AND FINALLY, MY XML FOR THE GRIDVIEW:
<?xml version="1.0" encoding="utf-8"?>
<GridView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/lbl_gridView"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_gravity="center_horizontal"
android:layout_margin="0px"
android:alwaysDrawnWithCache="false"
android:animateLayoutChanges="false"
android:background="#android:color/white"
android:columnWidth="130dp"
android:drawSelectorOnTop="true"
android:horizontalSpacing="#dimen/activity_horizontal_margin"
android:listSelector="#null"
android:numColumns="auto_fit"
android:padding="#dimen/activity_horizontal_margin"
android:scrollbarStyle="insideOverlay"
android:smoothScrollbar="true"
android:stretchMode="none"
android:verticalSpacing="#dimen/activity_vertical_margin" >
</GridView>
Use CENTER_INSIDE a scale type for your image view.
super.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
another thing that I would change is the way you handle the column width. I would remove the android:numColumns="auto_fit". On the other hand you know that the number of columns is the cealing of WidthViewGrid/desiderePicSize, where the most common case for WidthViewGrid is the screen's width. On then programmatically you can set number of columns of your GridView with setNumberOfColumns
I would say:
A. After calling setColumnWidth call the gridview.invalidate()
B. After returning from the change preference - call adapter's notifyDataSetChanged in order to make sure it re-creates the views in the adapter (i.e. getView will be called)

Image Buttons lose images on Orientation Change

i have a few pages realized with a PagerAdapter and one layout-file in the folder "res/layout" and one layout-file in "res/layout-land". Each Layout has two ImageButtons, where:
imageButton1 in portrait has the same ID as the imageButton1 in landscape.
imageButton2 in portrait has the same ID as the imageButton2 in landscape.
I have assigned an onClickListener to imageButton1 button which:
takes the images from the ImageButtons
rescales the Images to fit/fill the ImageButtons
and reassigns the rescaled pictures to the ImageButtons.
But whenever i change the orientation in my emulator the images/pictures in these buttons get lost, or change to the images specified in the layout-file originally and dont refresh to the pictures i assigned to the buttons programmatically.
PS (for example): i assigned in onCreate a listener to button1 and that listener works for this button both in portrait and also in landscape. So these are not seperated buttons!!!!!!
Question: how can i make it work that the images are not lost when changing orientation?
thx for any help in advance!
here is my code:
layout-portrait file:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:id="#+id/table1"
android:background="#drawable/shape"
android:gravity="center"
>
<!-- Row 1-->
<LinearLayout
android:layout_width="fill_parent"
android:orientation="horizontal"
android:layout_height="fill_parent"
android:layout_weight="1"
android:gravity="center">
<LinearLayout
android:id="#+id/layout11"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
android:background="#drawable/shape" >
<ImageButton
android:id="#+id/imageButton1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:src="#drawable/ic_launcher" />
</LinearLayout>
<LinearLayout
android:id="#+id/layout12"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
android:background="#drawable/shape" >
<ImageButton
android:id="#+id/imageButton2"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:src="#drawable/ic_launcher" />
</LinearLayout>
</LinearLayout>
layout-landscape file:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:id="#+id/table1"
android:background="#drawable/shape"
android:gravity="center"
>
<LinearLayout
android:layout_width="fill_parent"
android:orientation="horizontal"
android:layout_height="fill_parent"
android:layout_weight="1"
android:gravity="center">
<LinearLayout
android:id="#+id/layout11"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
android:background="#drawable/shape" >
<ImageButton
android:id="#+id/imageButton1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:src="#drawable/ic_launcher" />
</LinearLayout>
<LinearLayout
android:id="#+id/layout12"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
android:background="#drawable/shape" >
<ImageButton
android:id="#+id/imageButton2"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:src="#drawable/ic_launcher" />
</LinearLayout>
</LinearLayout>
MyPageAdapter-class:
package com.example.Pagercheck;
import java.util.List;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
public class MyPageAdapter extends PagerAdapter
{
List<View> pages = null;
public MyPageAdapter(List<View> pages)
{
this.pages = pages;
}
#Override
public int getCount()
{
return pages.size();
}
#Override
public boolean isViewFromObject(View view, Object object)
{
return view.equals(object);
}
#Override
public Object instantiateItem(View collection, int position)
{
View v = pages.get(position);
((ViewPager) collection).addView(v, 0);
return v;
}
#Override
public void destroyItem(View collection, int position, Object view)
{
((ViewPager) collection).removeView((View) view);
}
#Override
public void finishUpdate(View arg0) {
}
#Override
public void startUpdate(View arg0) {
}
}
My MainActivity-Class:
package com.example.Pagercheck;
import java.util.ArrayList;
import java.util.List;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.SimpleOnPageChangeListener;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.ViewGroup.MarginLayoutParams;
import android.view.ViewTreeObserver;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity implements OnClickListener
{
private List<View> pages;
private MyPageAdapter pagerAdapter;
private ViewPager viewPager;
private static Context context; //member zum speichern für context für andere Klassen
public static Context getContext(){ return context;} //context für andere Klassen zugänglich machen
//private Button btn1;
#Override
protected void onCreate(Bundle savedInstanceState)
{
context = this; //context in member speichern
LayoutInflater inflater = LayoutInflater.from(this);
pages = new ArrayList<View>();
View page = inflater.inflate(R.layout.page, null);
pages.add(page);
page = inflater.inflate(R.layout.page, null);
pages.add(page);
page = inflater.inflate(R.layout.page, null);
pages.add(page);
page = inflater.inflate(R.layout.page, null);
pages.add(page);
page = inflater.inflate(R.layout.page, null);
pages.add(page);
pagerAdapter = new MyPageAdapter(pages);
viewPager = new ViewPager(this);
viewPager.setAdapter(pagerAdapter);
viewPager.setCurrentItem(0);
setContentView(viewPager);
for (int i_page=0;i_page<pages.size();i_page++)
{
//Drag-Listener auf ImageButtons:
pages.get(i_page).findViewById(R.id.imageButton1).setOnLongClickListener(new MyLongClickListener());
pages.get(i_page).findViewById(R.id.imageButton1).setOnClickListener(this);
pages.get(i_page).findViewById(R.id.imageButton2).setOnLongClickListener(new MyLongClickListener());
//Drag-Listener auf LinearLayouts:
pages.get(i_page).findViewById(R.id.layout11).setOnDragListener(new MyDragListener());
pages.get(i_page).findViewById(R.id.layout12).setOnDragListener(new MyDragListener());
}
super.onCreate(savedInstanceState);
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public void onWindowFocusChanged(boolean hasFocus)
{
// TODO Auto-generated method stub
super.onWindowFocusChanged(hasFocus);
//NOTE FOR STACKOVERFLOW
//I COMMENTED THIS OUT SO THAT MY IMAGE BUTTONS DOESNT GET LOST AFTER PAGE 2 SO THAT I CAN TEST MY APP PROPERLY WITH ONCLICK:
// Bitmap bmp_stift=BitmapFactory.decodeResource(getContext().getResources(), R.drawable.stift);
//
// for (int i_page=0;i_page<pages.size();i_page++)
// {
//
// ((ImageButton)pages.get(i_page).findViewById(R.id.imageButton1)).setImageBitmap(bmp_stift);
// scalePictureToFitButtom((ImageButton)pages.get(i_page).findViewById(R.id.imageButton1));
// scalePictureToFitButtom((ImageButton)pages.get(i_page).findViewById(R.id.imageButton2));
//
//
// }
}
public void scalePictureToFitButtom(ImageButton img_btn)
{
int width=img_btn.getWidth();
int height=img_btn.getHeight();
BitmapDrawable draw=(BitmapDrawable)img_btn.getDrawable();
Bitmap bmp = ((BitmapDrawable)draw).getBitmap();
Bitmap resized = Bitmap.createScaledBitmap(bmp, width-40, height-40, true); //bissle schmaler und niedriger damit man noch den Klickeffekt sieht
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
params.width=width;
params.height=height;
img_btn.setImageBitmap(resized);
img_btn.setLayoutParams(params);
pagerAdapter.notifyDataSetChanged();
}
#Override
public void onClick(View view)
{
Bitmap bmp_stift=BitmapFactory.decodeResource(getContext().getResources(), R.drawable.stift);
for (int i_page=0;i_page<pages.size();i_page++)
{
((ImageButton)pages.get(i_page).findViewById(R.id.imageButton1)).setImageBitmap(bmp_stift);
scalePictureToFitButtom((ImageButton)pages.get(i_page).findViewById(R.id.imageButton1));
scalePictureToFitButtom((ImageButton)pages.get(i_page).findViewById(R.id.imageButton2));
}
Toast einToast = Toast.makeText(view.getContext(), "clicked", Toast.LENGTH_SHORT);
einToast.show();
}
}
UPDATE:
i did it like this now (example for saving and restoring Bitmap of imageButton1):
#Override
protected void onSaveInstanceState(Bundle outState)
{
// TODO Auto-generated method stub
super.onSaveInstanceState(outState);
BitmapDrawable draw=(BitmapDrawable)((ImageButton)pages.get(0).findViewById(R.id.imageButton1)).getDrawable();
Bitmap bmp = ((BitmapDrawable)draw).getBitmap();
outState.putParcelable("IMG_OF_BUTTON1", bmp);
super.onSaveInstanceState(outState);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState)
{
// TODO Auto-generated method stub
super.onRestoreInstanceState(savedInstanceState);
Bitmap bmp= savedInstanceState.getParcelable("IMG_OF_BUTTON1");
((ImageButton)pages.get(0).findViewById(R.id.imageButton1)).setImageBitmap(bmp);
}

ImageButtons on Pages-Problems (Android)

i have a few pages realized with a PagerAdapter and within that some LinearLayouts, which have some ImageButtons.
My Issue:
i want to get the imagebuttons from all the layouts from my pages on app-start, get the size of them and to resize the images to fill the imagebuttons. Gettting the images and rescaling them works fine, BUT if i do this at the function "onWindowFocusChanged" it only works on the first two pages. The ImageButtons on the third page until the last page are just gone. I assume the problem is that either these pages OR the linear-layouts OR the ImageButtons on these pages are not drawn yet so that it doesnt work.
To prove this i assigned a on-click listener to one of these buttons and do my calculation then and not already at onWindowFocusChanged. This has the same effect, BUT if i click the button after i have wiped over all pages it works on all pages.
Question: how can i make it work on startup for all pages OR without having to wipe over all pages first?
thx for any help in advance!
here is my code:
layout-portrait file:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:id="#+id/table1"
android:background="#drawable/shape"
android:gravity="center"
>
<!-- Row 1-->
<LinearLayout
android:layout_width="fill_parent"
android:orientation="horizontal"
android:layout_height="fill_parent"
android:layout_weight="1"
android:gravity="center">
<LinearLayout
android:id="#+id/layout11"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
android:background="#drawable/shape" >
<ImageButton
android:id="#+id/imageButton1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:src="#drawable/ic_launcher" />
</LinearLayout>
<LinearLayout
android:id="#+id/layout12"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
android:background="#drawable/shape" >
<ImageButton
android:id="#+id/imageButton2"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:src="#drawable/ic_launcher" />
</LinearLayout>
</LinearLayout>
layout-landscape file:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:id="#+id/table1"
android:background="#drawable/shape"
android:gravity="center"
>
<LinearLayout
android:layout_width="fill_parent"
android:orientation="horizontal"
android:layout_height="fill_parent"
android:layout_weight="1"
android:gravity="center">
<LinearLayout
android:id="#+id/layout11"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
android:background="#drawable/shape" >
<ImageButton
android:id="#+id/imageButton1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:src="#drawable/ic_launcher" />
</LinearLayout>
<LinearLayout
android:id="#+id/layout12"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
android:background="#drawable/shape" >
<ImageButton
android:id="#+id/imageButton2"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:src="#drawable/ic_launcher" />
</LinearLayout>
</LinearLayout>
MyPageAdapter-class:
package com.example.Pagercheck;
import java.util.List;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
public class MyPageAdapter extends PagerAdapter
{
List<View> pages = null;
public MyPageAdapter(List<View> pages)
{
this.pages = pages;
}
#Override
public int getCount()
{
return pages.size();
}
#Override
public boolean isViewFromObject(View view, Object object)
{
return view.equals(object);
}
#Override
public Object instantiateItem(View collection, int position)
{
View v = pages.get(position);
((ViewPager) collection).addView(v, 0);
return v;
}
#Override
public void destroyItem(View collection, int position, Object view)
{
((ViewPager) collection).removeView((View) view);
}
#Override
public void finishUpdate(View arg0) {
}
#Override
public void startUpdate(View arg0) {
}
}
My MainActivity-Class:
package com.example.Pagercheck;
import java.util.ArrayList;
import java.util.List;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.SimpleOnPageChangeListener;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.ViewGroup.MarginLayoutParams;
import android.view.ViewTreeObserver;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity implements OnClickListener
{
private List<View> pages;
private MyPageAdapter pagerAdapter;
private ViewPager viewPager;
private static Context context; //member zum speichern für context für andere Klassen
public static Context getContext(){ return context;} //context für andere Klassen zugänglich machen
//private Button btn1;
#Override
protected void onCreate(Bundle savedInstanceState)
{
context = this; //context in member speichern
LayoutInflater inflater = LayoutInflater.from(this);
pages = new ArrayList<View>();
View page = inflater.inflate(R.layout.page, null);
pages.add(page);
page = inflater.inflate(R.layout.page, null);
pages.add(page);
page = inflater.inflate(R.layout.page, null);
pages.add(page);
page = inflater.inflate(R.layout.page, null);
pages.add(page);
page = inflater.inflate(R.layout.page, null);
pages.add(page);
pagerAdapter = new MyPageAdapter(pages);
viewPager = new ViewPager(this);
viewPager.setAdapter(pagerAdapter);
viewPager.setCurrentItem(0);
setContentView(viewPager);
for (int i_page=0;i_page<pages.size();i_page++)
{
//Drag-Listener auf ImageButtons:
pages.get(i_page).findViewById(R.id.imageButton1).setOnLongClickListener(new MyLongClickListener());
pages.get(i_page).findViewById(R.id.imageButton1).setOnClickListener(this);
pages.get(i_page).findViewById(R.id.imageButton2).setOnLongClickListener(new MyLongClickListener());
//Drag-Listener auf LinearLayouts:
pages.get(i_page).findViewById(R.id.layout11).setOnDragListener(new MyDragListener());
pages.get(i_page).findViewById(R.id.layout12).setOnDragListener(new MyDragListener());
}
super.onCreate(savedInstanceState);
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public void onWindowFocusChanged(boolean hasFocus)
{
// TODO Auto-generated method stub
super.onWindowFocusChanged(hasFocus);
//NOTE FOR STACKOVERFLOW
//I COMMENTED THIS OUT SO THAT MY IMAGE BUTTONS DOESNT GET LOST AFTER PAGE 2 SO THAT I CAN TEST MY APP PROPERLY WITH ONCLICK:
// Bitmap bmp_stift=BitmapFactory.decodeResource(getContext().getResources(), R.drawable.stift);
//
// for (int i_page=0;i_page<pages.size();i_page++)
// {
//
// ((ImageButton)pages.get(i_page).findViewById(R.id.imageButton1)).setImageBitmap(bmp_stift);
// scalePictureToFitButtom((ImageButton)pages.get(i_page).findViewById(R.id.imageButton1));
// scalePictureToFitButtom((ImageButton)pages.get(i_page).findViewById(R.id.imageButton2));
//
//
// }
}
public void scalePictureToFitButtom(ImageButton img_btn)
{
int width=img_btn.getWidth();
int height=img_btn.getHeight();
BitmapDrawable draw=(BitmapDrawable)img_btn.getDrawable();
Bitmap bmp = ((BitmapDrawable)draw).getBitmap();
Bitmap resized = Bitmap.createScaledBitmap(bmp, width-40, height-40, true); //bissle schmaler und niedriger damit man noch den Klickeffekt sieht
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
params.width=width;
params.height=height;
img_btn.setImageBitmap(resized);
img_btn.setLayoutParams(params);
pagerAdapter.notifyDataSetChanged();
}
#Override
public void onClick(View view)
{
Bitmap bmp_stift=BitmapFactory.decodeResource(getContext().getResources(), R.drawable.stift);
for (int i_page=0;i_page<pages.size();i_page++)
{
((ImageButton)pages.get(i_page).findViewById(R.id.imageButton1)).setImageBitmap(bmp_stift);
scalePictureToFitButtom((ImageButton)pages.get(i_page).findViewById(R.id.imageButton1));
scalePictureToFitButtom((ImageButton)pages.get(i_page).findViewById(R.id.imageButton2));
}
Toast einToast = Toast.makeText(view.getContext(), "clicked", Toast.LENGTH_SHORT);
einToast.show();
}
}

Categories

Resources