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();
}
}
Related
I am just doing my Daily practice and I had a Problem. I've created Viewpager on Tab Layout but it not worked.
I don't know why, I am just doing like the tutorial on the internet and spend for this problem 2 days. :/
The Tablayout showing all tabs but not with the view (fragment tab).
I'll thank for any help from you all :))))))))
So, here's what I code,
content_home.xml:
<?xml version="1.0" encoding="utf-8"?>
<androidx.core.widget.NestedScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/content_home"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context=".ui.home.ViewPagerActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<com.google.android.material.tabs.TabLayout
android:id="#+id/content_home_tablayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabBackground="#color/colorPrimaryAlternate"
app:tabGravity="fill"
app:tabMode="fixed"
app:tabIndicatorColor="#color/colorPrimary"
app:tabSelectedTextColor="#color/colorPrimary"
app:tabTextColor="#color/colorPrimaryDarkAlternate"
app:tabIconTint="#color/tab_color_selector"
app:tabTextAppearance="#style/tabAllCaps">
<com.google.android.material.tabs.TabItem
android:id="#+id/tab1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:icon="#drawable/ic_waterpark"
android:text="#string/waterpark" />
<com.google.android.material.tabs.TabItem
android:id="#+id/tab2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:icon="#drawable/ic_home_black_24dp"
android:text="#string/drypark" />
<com.google.android.material.tabs.TabItem
android:id="#+id/tab3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:icon="#drawable/ic_human_male_female"
android:text="#string/facilities" />
</com.google.android.material.tabs.TabLayout>
<androidx.viewpager.widget.ViewPager
android:id="#+id/content_home_viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/content_home_tablayout"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
android:layout_alignParentBottom="true" />
</LinearLayout>
</androidx.core.widget.NestedScrollView>
ViewPagerActivity:
package com.ardityo.android.transeraapps.ui.home;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import androidx.viewpager.widget.ViewPager;
import com.ardityo.android.transeraapps.R;
import com.ardityo.android.transeraapps.ui.home.tabs.drypark.DryParkFragment;
import com.ardityo.android.transeraapps.ui.home.tabs.facilities.FacilitiesFragment;
import com.ardityo.android.transeraapps.ui.home.tabs.waterpark.WaterParkFragment;
import com.google.android.material.tabs.TabLayout;
public class ViewPagerActivity extends AppCompatActivity {
private TabLayout tabLayout;
private ViewPager viewPager;
ViewPagerAdapter adapter;
WaterParkFragment waterParkFragment;
DryParkFragment dryParkFragment;
FacilitiesFragment facilitiesFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content_home);
viewPager = (ViewPager) findViewById(R.id.content_home_viewpager);
viewPager.setOffscreenPageLimit(3);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.content_home_tablayout);
tabLayout.setupWithViewPager(viewPager);
}
private void setupViewPager(ViewPager viewPager)
{
adapter = new ViewPagerAdapter(getSupportFragmentManager());
// waterParkFragment=new WaterParkFragment();
// dryParkFragment=new DryParkFragment();
// facilitiesFragment=new FacilitiesFragment();
// adapter.addFragment(waterParkFragment,"WaterPark");
// adapter.addFragment(dryParkFragment,"DryPark");
// adapter.addFragment(facilitiesFragment.newInstance(),"Facilities");
adapter.addFragment(WaterParkFragment.newInstance(),"WaterPark");
adapter.addFragment(DryParkFragment.newInstance(),"DryPark");
adapter.addFragment(FacilitiesFragment.newInstance(),"Facilities");
viewPager.setAdapter(adapter);
}
}
DryParkFragment (Same with WaterParkFragment & FacilitiesFragment):
package com.ardityo.android.transeraapps.ui.home.tabs.drypark;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;
import com.ardityo.android.transeraapps.R;
import com.ardityo.android.transeraapps.ui.settings.SettingsViewModel;
public class DryParkFragment extends Fragment {
public DryParkFragment() {
// Required empty public constructor
}
public static DryParkFragment newInstance() {
Bundle args = new Bundle();
DryParkFragment fragment = new DryParkFragment();
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.content_home_2, container, false);
}
// #Override
// public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// inflater.inflate(R.menu.menu_calls_fragment, menu);
// super.onCreateOptionsMenu(menu, inflater);
// }
}
content_home_2.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context=".ui.home.tabs.drypark.DryParkFragment"
>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/mascot_head" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Test" />
</LinearLayout>
The problem comes from using ViewPager inside NestedScrollView . This may also happen when you use CoordinatorLayout . You have two options to achieve that .
1 . ViewPager2 :
The first option is to use ViewPager2 . Just take a look :
https://developer.android.com/jetpack/androidx/releases/viewpager2
2 . Use custom ViewPager :
Here is a class for you that can determine its height based on childs.
import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import androidx.viewpager.widget.ViewPager;
public class CustomViewPager extends ViewPager {
public CustomViewPager(Context context) {
super(context);
}
public CustomViewPager(Context context, AttributeSet attrs) {
super(context, attrs);
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int biggestHeightMeasureSpec = 0;
for(int i = 0 ; i < getChildCount() ; i++)
{
View child = getChildAt(i);
if (child != null) {
child.measure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
int h = child.getMeasuredHeight();
heightMeasureSpec = MeasureSpec.makeMeasureSpec(h, MeasureSpec.EXACTLY);
if(heightMeasureSpec > biggestHeightMeasureSpec)
biggestHeightMeasureSpec = heightMeasureSpec;
}
}
super.onMeasure(widthMeasureSpec, biggestHeightMeasureSpec);
}
}
Finally just use it in your XML layout :
<PATH.TO.YOUR.CustomViewPager
android:id="#+id/viewPager"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
Try using viewpager 2, dont forget to use newest library
-> https://developer.android.com/jetpack/androidx/releases/viewpager2?hl=id
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();
}
}
I'm trying to create a kind of game using Android Studio. Till now I have done a gridview wich shows players stored in a database. I have had some problems with gridView.setOnItemClickListener, I have had to do it by putting the code into gridView's Adparter.class so if you know how I can do that into gridView's activity please tell me.
My problem now is that when you click on a player a popup window appears in which you could change the player's name or his genre. When you click on Confirm's button the database will automatically been updated, but it doesn't works. I have try to do it step by step by using Toast in order to know if it run that part or not, the problem could be the context, but maybe I'm crazy.
I left you some pics and the code related to it.
Gridview's pic -> http://i.stack.imgur.com/GO4ms.png
PopUp windos's pic -> http://i.stack.imgur.com/aAvcm.png
gridView's adapter class
package es.fingerlabs.gamecohol;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
public class AdaptadorAmigos extends BaseAdapter {
private Context context;
private ArrayList<Amigo> misAmigos = new ArrayList<Amigo>();
public AdaptadorAmigos(ArrayList<Amigo> list, Context context) {
this.misAmigos = list;
this.context = context;
}
public View getView(final int position, View convertView, ViewGroup parent) {
View gridView = convertView;
if (gridView == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
gridView = inflater.inflate(R.layout.item_amigo, null);
}
TextView TextoNombreJugador = (TextView)gridView.findViewById(R.id.tvNombreAmigo);
TextoNombreJugador.setText(misAmigos.get(position).getNombre());
//Handle buttons and add onClickListeners
ImageButton deleteBtn = (ImageButton)gridView.findViewById(R.id.btEliminarAmigo);
deleteBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//do something
AmigosSQLiteHelper amigosdbh = new AmigosSQLiteHelper(context, "DBAmigos", null, 1);
SQLiteDatabase db = amigosdbh.getWritableDatabase();
db.delete("Amigos", "id_amigo="+misAmigos.get(position).getId(), null);
misAmigos.remove(position); //or some other task
//Eliminar de la base de datos **************
notifyDataSetChanged();
}
});
// ******* THIS IS WHAT I REFER TO PUT IT ON GRIDVIEW'S ACTIVITY *******
gridView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Toast.makeText(context,"Id "+misAmigos.get(position).getId()+" Vidas "+misAmigos.get(position).getVidas(), Toast.LENGTH_SHORT).show();
Intent intent = new Intent(context, VistaAmigo.class);
intent.putExtra("Id", (misAmigos.get(position).getId()));
intent.putExtra("Nombre", (misAmigos.get(position)).getNombre());
intent.putExtra("Genero", (misAmigos.get(position)).getGenero());
context.startActivity(intent);
}
});
return gridView;
}
#Override
public int getCount() {
return misAmigos.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
}
gridView's class
package es.fingerlabs.gamecohol;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
public class SeleccionarAmigos extends AppCompatActivity {
private ArrayList<Amigo> misAmigos;
private GridView gridView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_amigos);
gridView = (GridView) findViewById(R.id.gvAmigos);
refrescarLista();
/* IF I PUT THAT HERE IT DOES NOTHING
gridView.setOnItemClickListener(new OnItemClickListener() {
#Override public void onItemClick(AdapterView<?> arg0, View v, int position, long arg3) {
Toast.makeText(getApplicationContext(),misAmigos.get(position).getNombre(), Toast.LENGTH_SHORT).show();
}
});*/
/*gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// get the data to pass to the activity based on the position clicked
Intent intent = new Intent(SeleccionarAmigos.this, VistaAmigo.class);
intent.putExtra("Id", (misAmigos.get(position).getId()));
intent.putExtra("Nombre", (misAmigos.get(position)).getNombre());
intent.putExtra("Genero", (misAmigos.get(position)).getGenero());
startActivity(intent);
}
});*/
}
public void obtenerAmigos(){
misAmigos = new ArrayList<Amigo>();
AmigosSQLiteHelper amigosdbh = new AmigosSQLiteHelper(this, "DBAmigos", null, 1);
SQLiteDatabase db = amigosdbh.getReadableDatabase();
Cursor c = db.rawQuery(" SELECT Id_amigo,Nombre,Genero FROM Amigos ", null);
//Nos aseguramos de que existe al menos un registro
if (c.moveToFirst()) {
//Recorremos el cursor hasta que no haya más registros
do {
int id = c.getInt(0);
String nombre= c.getString(1);
String genero= c.getString(2);
Amigo nuevoAmigo = new Amigo(nombre,genero,null);
nuevoAmigo.setId(id);
this.misAmigos.add(nuevoAmigo);
} while(c.moveToNext());
}
db.close();
}
public void refrescarLista(){
obtenerAmigos();
AdaptadorAmigos adapter = new AdaptadorAmigos(misAmigos, this);
gridView.setAdapter(adapter);
}
}
PopUp window class
package es.fingerlabs.gamecohol;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.PopupWindow;
import android.widget.Toast;
public class VistaAmigo extends Activity {
private int id;
private String nombre;
private String genero;
private EditText etNombre;
private EditText etGenero;
private Button btConfirmar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_vistaamigo);
etNombre = (EditText) findViewById(R.id.etNombreVistaAmigo);
etGenero = (EditText) findViewById(R.id.etGeneroVistaAmigo);
btConfirmar = (Button) findViewById(R.id.btConfirmarAmigo);
Intent i = getIntent();
i.getIntExtra("Id", id);
nombre = i.getStringExtra("Nombre");
genero = i.getStringExtra("Genero");
etNombre.setHint(nombre);
etGenero.setHint(genero);
btConfirmar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AmigosSQLiteHelper amigosdbh = new AmigosSQLiteHelper(VistaAmigo.this, "DBAmigos", null, 1);
SQLiteDatabase db = amigosdbh.getWritableDatabase();
ContentValues valores = new ContentValues();
valores.put("nombre", etNombre.getText().toString());
valores.put("genero", etGenero.getText().toString());
db.update("Amigos", valores, "id_amigo="+id, null);
Toast.makeText(VistaAmigo.this.getBaseContext(),"Nombre: "+etNombre.getText().toString()+" Genero: "+etGenero.getText().toString()+
"Cambios realizados",Toast.LENGTH_LONG);
}
});
}
}
gridView's layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/fondogamecohol">
<GridView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/gvAmigos"
android:layout_gravity="center_horizontal"
android:numColumns="auto_fit"
android:layout_margin="10dp"
android:verticalSpacing="20dp"
android:horizontalSpacing="20dp" />
</LinearLayout>
Gridview's item layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/rounded_corners_white"
android:id="#+id/lyItemAmigo">
<ImageView
android:layout_width="124dp"
android:layout_height="95dp"
android:id="#+id/ivFotoAmigo"
android:background="#d8d8d8"
android:layout_marginTop="10dp"
android:layout_marginLeft="12dp"
android:layout_marginRight="12dp"
android:clickable="false"
android:src="#drawable/ic_tag_faces_white_36dp" />
<TextView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:text="Chrisitan"
android:id="#+id/tvNombreAmigo"
android:layout_gravity="center"
android:textColor="#333333"
android:textStyle="bold"
android:textSize="18dp"
android:layout_marginTop="5dp"
android:layout_marginRight="12dp"
android:clickable="false"
android:layout_marginLeft="14dp" />
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center_horizontal"
android:layout_marginBottom="10dp"
android:layout_marginLeft="10dp"
android:gravity="right"
android:id="#+id/lyBotonesAmigo"
android:layout_marginTop="5dp"
android:layout_marginRight="12dp">
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/btEditarAmigo"
android:clickable="false"
android:background="#drawable/ic_edit_black_18dp" />
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/btEliminarAmigo"
android:clickable="false"
android:background="#drawable/ic_delete_forever_black_18dp" />
</LinearLayout>
</LinearLayout>
PopUp window layout
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:theme="#style/PopUp1">
<LinearLayout
android:layout_width="300dp"
android:layout_height="300dp"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:background="#drawable/rounded_corners_white"
android:orientation="vertical">
<TextView
android:layout_width="fill_parent"
android:layout_height="40dp"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Modificar amigo"
android:id="#+id/tvModificarAmigo"
android:layout_gravity="center_horizontal"
android:background="#c9ed5a"
android:gravity="center_vertical|center_horizontal"
android:textStyle="bold"
android:textColor="#ffffff" />
<RelativeLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Nombre: "
android:id="#+id/tvNombreVistaAmigo"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:layout_marginStart="28dp"
android:layout_marginTop="51dp"
android:textStyle="bold"
android:textColor="#333333"
android:textSize="20dp" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/etNombreVistaAmigo"
android:layout_marginStart="10dp"
android:hint="Jugador 1"
android:textColorHint="#333333"
android:textColor="#333333"
android:textStyle="bold"
android:layout_alignParentTop="true"
android:layout_toEndOf="#+id/tvNombreVistaAmigo"
android:layout_toRightOf="#+id/tvNombreVistaAmigo"
android:layout_marginTop="41dp"
android:textSize="20dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Genero:"
android:id="#+id/tvGeneroVistaAmigo"
android:layout_centerVertical="true"
android:layout_alignStart="#+id/tvNombreVistaAmigo"
android:textColor="#333333"
android:textStyle="bold" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/etGeneroVistaAmigo"
android:hint="Hombre"
android:textColorHint="#333333"
android:textColor="#333333"
android:textStyle="bold"
android:layout_alignStart="#+id/etNombreVistaAmigo"
android:layout_below="#+id/etNombreVistaAmigo"
android:layout_marginTop="23dp"
android:textSize="20dp" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Confirmar"
android:id="#+id/btConfirmarAmigo"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:background="#drawable/rounded_corners_green"
android:layout_marginBottom="20dp"
android:textStyle="bold"
android:paddingLeft="20dp"
android:paddingRight="20dp"
android:textSize="20dp" />
</RelativeLayout>
</LinearLayout>
</RelativeLayout>
From what I´ve seen in your code is, that you try to get the id from an intent in your PopUp window class. You have made one thing wrong:
Intent i = getIntent();
i.getIntExtra("Id", id);
it must be:
Intent i = getIntent();
id = i.getIntExtra("Id", id); //forgott id = here
and you should give a default value to id for example id=-1 . The problem is, by updating your database, you give a non value integer and so it is not possible to update your table.
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);
}
I created a custom ListView with Custom list view adapter. I want to set current time in every list item in the list. Items in the list box must update the current time every second.
MainActivity.java
package com.example.examapp;
import java.sql.Time;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import com.example.exambp.*;
import android.R.string;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.LabeledIntent;
import android.content.res.Configuration;
import android.database.sqlite.SQLiteDatabase;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
public class MainActivity extends Activity {
ListView lv;
Activity act=this;
List<ListViewItem> items;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
items=new ArrayList<ListViewItem>();
lv=(ListView)findViewById(R.id.listView1);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
}
public void showData(View v)
{
IntentIntegrator i=new IntentIntegrator(this);
i.initiateScan();
}
String[] onedata;
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
IntentResult scanResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent);
if (scanResult != null) {
String x=scanResult.getContents();
EditText et=(EditText)findViewById(R.id.editText1);
et.setText(x);
addToList(x);
}
}
ListViewItem li;
CustomListViewAdapter adapter;
public void addToList(String str)
{
onedata=str.split("/");
li=new ListViewItem();
li.enrollId="EnrollmentID: "+onedata[0].toString();
li.ExamId="ExamID: "+onedata[1].toString();
li.UserId="UserId: "+onedata[2].toString();
li.StartedTime=onedata[3].toString();
li.Duration=onedata[4].toString();
li.AvailableTime="jiukjh";
items.add(li);
adapter=new CustomListViewAdapter(this, items);
lv.setAdapter(adapter);
}
}
activity_main.xml
<RelativeLayout 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"
tools:context=".MainActivity" >
<EditText
android:id="#+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_marginLeft="60dp"
android:ems="10"
android:inputType="text" >
<requestFocus />
</EditText>
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:onClick="showData"
android:text="#string/btn_val" />
<LinearLayout
android:id="#+id/linearLayout2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:orientation="vertical" >
</LinearLayout>
<ListView
android:id="#+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/textView9"
android:layout_toRightOf="#+id/linearLayout2" >
</ListView>
<TextView
android:id="#+id/textView9"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/button1"
android:text="Started Exams"
android:textAppearance="?android:attr/textAppearanceLarge" />
</RelativeLayout>
item_row.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="#+id/txtAvailability"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="TextView"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="#+id/txtEnrollmentId"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/txtAvailability"
android:text="TextView" />
<TextView
android:id="#+id/txtUserId"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/txtEnrollmentId"
android:layout_alignBottom="#+id/txtEnrollmentId"
android:layout_marginLeft="78dp"
android:layout_toRightOf="#+id/txtAvailability"
android:text="TextView" />
<TextView
android:id="#+id/txtExamId"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/txtEnrollmentId"
android:text="TextView" />
<TextView
android:id="#+id/txtStartTime"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/txtExamId"
android:layout_alignBottom="#+id/txtExamId"
android:layout_alignLeft="#+id/txtUserId"
android:text="TextView" />
</RelativeLayout>
CustomListViewAdapter.java
package com.example.examapp;
import java.util.Date;
import java.util.List;
import com.example.exambp.*;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
public class CustomListViewAdapter extends BaseAdapter
{
LayoutInflater inflater;
List<ListViewItem> items;
Activity act;
public CustomListViewAdapter(Activity context, List<ListViewItem> items) {
super();
this.items = items;
this.inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.act=context;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return items.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
View vi;
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ListViewItem item=items.get(position);
vi=convertView;
if(convertView==null)
vi = inflater.inflate(R.layout.item_row, null);
//ImageView imgThumbnail=(ImageView)vi.findViewById(R.id.imgThumbnail);
TextView txtAvailableTime1=(TextView)vi.findViewById(R.id.txtAvailability);
TextView txtEnrollmentId1=(TextView)vi.findViewById(R.id.txtEnrollmentId);
TextView txtUserId1=(TextView)vi.findViewById(R.id.txtUserId);
TextView txtExamId1=(TextView)vi.findViewById(R.id.txtExamId);
TextView txtStartedTime1=(TextView)vi.findViewById(R.id.txtStartTime);
//imgThumbnail.setImageResource(item.ThumbnailResource);
txtAvailableTime1.setText(item.AvailableTime.toString());
txtEnrollmentId1.setText(item.enrollId.toString());
txtUserId1.setText(item.UserId.toString());
txtExamId1.setText(item.ExamId.toString());
txtStartedTime1.setText(item.StartedTime.toString());
Thread myThread = null;
Runnable runnable = new CountDownRunner();
myThread= new Thread(runnable);
myThread.start();
return vi;
}
public void doWork() {
act.runOnUiThread(new Runnable() {
public void run() {
try{
TextView txtCurrentTime=(TextView)vi.findViewById(R.id.txtAvailability);
Date dt = new Date();
int hours = dt.getHours();
int minutes = dt.getMinutes();
int seconds = dt.getSeconds();
String curTime = hours + ":" + minutes + ":" + seconds;
txtCurrentTime.setText(curTime);
}catch (Exception e) {
//TextView txtCurrentTime=(TextView)vi.findViewById(R.id.txtAvailability);
//txtCurrentTime.setText(e.getMessage());
}
}
});
}
class CountDownRunner implements Runnable{
// #Override
public void run() {
while(true){
try {
doWork();
Thread.sleep(1000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}catch(Exception e){
}
}
}
}
}
This is only run in one time. I want to change current time in List Items continuously.
Every second you will have to loop through each item in your List<ListViewItem> items and then update each item's time. After that call listView.notifyDataSetChanged().