ActionBarSherlock fragment showing different data than passed - java

Hello and thank you for trying to help!
I'm trying to build an app with ActionBarSherlcok. When I click the tabs, I would like the same fragment to instantiate but with dynamic data based on the tab I clicked.
For some reason it keeps showing me the wrong data, though the correct parameter value is passed (I verified it using breakpoints and watches).
I've read about SimpleOnPageChangeListener, getCurrentItem and of course the Fragments Tutorial.
I relied on SwipeyTabs example to create this, and built a short demo to show my problem here:
This is my MainActivity.java
package il.co.gilead.testdynamicfragments;
import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
public class MainActivity extends SherlockFragmentActivity {
public static ViewPager mViewPager;
private TabsAdapter mTabsAdapter;
Integer intNumOfPages = 3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mViewPager = new ViewPager(this);
mViewPager.setId(R.id.pager);
setContentView(mViewPager);
final ActionBar bar = getSupportActionBar();
bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
mTabsAdapter = new TabsAdapter(this, mViewPager);
for (int i=1; i<=intNumOfPages; i++) {
mTabsAdapter.addTab(bar.newTab().setText("Fragment "+i),
TestFrag.class, null);
}
}
}
This is my TestFrag.java
package il.co.gilead.testdynamicfragments;
import com.actionbarsherlock.app.SherlockFragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class TestFrag extends SherlockFragment {
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.frag_test, container, false);
TextView tv = (TextView) v.findViewById(R.id.textView1);
Integer pos = (MainActivity.mViewPager.getCurrentItem() + 1);
tv.setText("Page " + pos.toString());
return v;
}
}
My 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" >
<android.support.v4.view.ViewPager
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/pager" />
</RelativeLayout>
and my test_frag.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView" />
</LinearLayout>
Finally my TabsAdapter
public class TabsAdapter extends FragmentPagerAdapter implements ActionBar.TabListener, ViewPager.OnPageChangeListener{
private final Context mContext;
private final ActionBar mActionBar;
private final ViewPager mViewPager;
private final ArrayList<TabInfo> mTabs = new ArrayList<TabInfo>();
static final class TabInfo{
private final Class<?> clss;
private final Bundle args;
TabInfo(Class<?> _class, Bundle _args){
clss = _class;
args = _args;
}
}
public TabsAdapter(SherlockFragmentActivity fa, ViewPager pager) {
super(fa.getSupportFragmentManager());
mContext = fa;
mActionBar = fa.getSupportActionBar();
mViewPager = pager;
mViewPager.setAdapter(this);
mViewPager.setOnPageChangeListener(this);
}
public void addTab(ActionBar.Tab tab, Class<?> clss, Bundle args){
TabInfo info = new TabInfo(clss, args);
tab.setTag(info);
tab.setTabListener(this);
mTabs.add(info);
mActionBar.addTab(tab);
notifyDataSetChanged();
}
#Override
public void onPageScrollStateChanged(int state) {
}
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
mActionBar.setSelectedNavigationItem(position);
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
mViewPager.setCurrentItem(tab.getPosition());
Object tag = tab.getTag();
for (int i = 0; i<mTabs.size(); i++){
if (mTabs.get(i) == tag){
mViewPager.setCurrentItem(i);
}
}
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
}
#Override
public Fragment getItem(int position) {
TabInfo info = mTabs.get(position);
return Fragment.instantiate(mContext, info.clss.getName(), info.args);
}
#Override
public int getCount() {
return mTabs.size();
}
}
If you'll play around with it, you'll see that clicking tab "Fragment 2" sometimes shows "Page 1" and sometimes shows "Page 3" and sometimes shows "Page 2".
I think it has something to do with pre-loading the fragments, or fragment refresh, but at this point I am clueless...
Thanks again for your help!

Try to change this:
Integer pos = (MainActivity.mViewPager.getCurrentItem() + 1);
To this:
Integer pos = (getActivity().mViewPager.getCurrentItem() + 1);

I found out what the problem was.
I browsed through ActionBarSherlock website and looked at the sample code. The implementation was different than mine, but one thing stood up.
Here are the code changes in MainActivity.java:
for (int i=1; i<=intNumOfPages; i++)
{
Bundle args = new Bundle();
args.putInt("num", i);
mTabsAdapter.addTab(bar.newTab().setText("Fragment "+i), TestFrag.class, args);
}
Here is the addition to TestFrag.java:
public class TestFrag extends SherlockFragment {
Integer intPageNum;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle args = getArguments();
if (args != null)
intPageNum = args.getInt("num");
else
intPageNum = 1;
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.frag_test, container, false);
TextView tv = (TextView) v.findViewById(R.id.textView1);
tv.setText("Page " + intPageNum.toString());
return v;
}
}
As you can see, I dropped the use of pos altogether.
Thank you all for trying to help!

Related

I want to show 3 different fragments for 3 different tabs in view-pager ,Tabbed activity Android

I am very new to android , this time i created a view-pager tabbed activity by looking a video tutorial. the problem or the need is to show 3 different fragments if the user slides the position like tab1(shows first fragment),tab2 (shows second fragment) tab3 (shows third fragment)
Now it is showing one and only fragment for all tabs
this is my adapter class named datafragment
package com.example.jaison.news;
public class datafragment extends Fragment {
View view;
ViewPager viewPager;
TabLayout tabLayout;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
view= inflater.inflate(R.layout.sample,container,false);
viewPager = (ViewPager) view.findViewById(R.id.viewpager);
viewPager.setAdapter(new sliderAdapter(getChildFragmentManager()));
tabLayout = (TabLayout) view.findViewById(R.id.sliding_tabs);
tabLayout.post(new Runnable() {
#Override
public void run() {
tabLayout.setupWithViewPager(viewPager);
}
});
return view;
}
private class sliderAdapter extends FragmentPagerAdapter{
final String tabs[]={"tab1", "tab2","tab3"};
public sliderAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
Fragment fragment = null;
return fragment;
}
#Override
public int getCount() {
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
return tabs[position];
}
}
}
for those who did not get my point , all i need is implement the code something just like this, but i am not sure about this..
switch (position) {
case 0:
//showing first fragment
case 1:
//showing second fragment
case 2:
//showing third fragment
default:
return new Fragment();
}
change your getItem method like this
#Override
public Fragment getItem(int position) {
Fragment fragment = null;
switch (position){
case 0:
fragment = new Tab1Fragment();
break;
case 1:
fragment = new Tab2Fragment();
break;
case 2:
fragment = new Tab3Fragment();
break;
}
return fragment;
}
You need to create an instance of your viewPagerAdapter and then add items to it.
Something like this:
ViewPagerAdapter viewpagerAdapter = new ViewPagerAdapter(getChildFragmentManager());
viewPager.setAdapter(viewpagerAdapter);
// then add items to it as you add items to a recyclerview adapter or to any list
viewpagerAdapter.addFragment(new Fragment1(), "title1");
And the custom code for the viewpager Adapter is:
public class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
Also since you are new to programming, would advice you to use proper nomenclature, for eg. names of classes always begin with initial letter Uppercase
class ClassName
void methodName
MainActivity
import android.os.Bundle;
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.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new OneFragment(), "ONE");
adapter.addFragment(new TwoFragment(), "TWO");
adapter.addFragment(new ThreeFragment(), "THREE");
viewPager.setAdapter(adapter);
}
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
}
OneFragment.java
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class OneFragment extends Fragment{
public OneFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_one, container, false);
}
}
fragment_one.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">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/one"
android:textSize="40dp"
android:textStyle="bold"
android:layout_centerInParent="true"/>
</RelativeLayout>
Likewise create few more fragment activities with same code we used for OneFragment.java.
See this simple complete example:
Here I used TabLayout also which is often used with ViewPager, so will be useful for you on next.
It requires API:
compile 'com.android.support:design:25.3.1'
You can ignore and remove all parts of TabLayout from xml and java files if want to go simpler at this instance.
1. activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v4.view.ViewPager
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/viewPager"/>
<android.support.design.widget.TabLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/colorPrimary"
app:tabIndicatorColor="#color/colorPrimaryDark"
app:layout_scrollFlags="scroll|enterAlways"
android:id="#+id/tabLayout"/>
</RelativeLayout>
2. Fragment Tab1.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:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="TAB 1"
android:id="#+id/textTab1"/>
</RelativeLayout>
3. Fragment Tab2.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:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="TAB 2"
android:id="#+id/textTab2"/>
</RelativeLayout>
4. Fragment Tab3.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:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="TAB 3"
android:id="#+id/textSpacerNoTitleab3"/>
</RelativeLayout>
5. MainActivity.java
public class MainActivity extends AppCompatActivity
implements TabLayout.OnTabSelectedListener, ViewPager.OnPageChangeListener{
ViewPager viewPager;
TabLayout tabLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewPager = (ViewPager) findViewById(R.id.viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabLayout);
tabLayout.addTab(tabLayout.newTab().setText("Page 1"));
tabLayout.addTab(tabLayout.newTab().setText("Page 2"));
tabLayout.addTab(tabLayout.newTab().setText("Page 3"));
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
tabLayout.addOnTabSelectedListener(this);
viewPager.setAdapter(new VPAdapter(getSupportFragmentManager()));
viewPager.addOnPageChangeListener(this);
}
#Override
public void onTabSelected(TabLayout.Tab tab) {
w("onTabSelected(): "+tab.getPosition());
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
w("onPageSelected(): "+position);
TabLayout.Tab tab = tabLayout.getTabAt(position);
if(tab!=null)tab.select();
}
#Override
public void onPageScrollStateChanged(int state) {
}
void w(String string){
Log.w("MKN",getClass().getSimpleName()+" "+string);
}
}
6. Fragment class Tab1.java
public class Tab1 extends Fragment {
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
return inflater.inflate(R.layout.tab1,container,false);
}
}
7. Fragment class Tab2.java
public class Tab2 extends Fragment {
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
return inflater.inflate(R.layout.tab2,container,false);
}
}
8. Fragment class Tab3.java
public class Tab3 extends Fragment {
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
return inflater.inflate(R.layout.tab3,container,false);
}
}
9. Adapter class VPAdapter.java
public class VPAdapter extends FragmentPagerAdapter {
public VPAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
if(position == 0) return new Tab1();
if(position == 1) return new Tab2();
if(position == 2) return new Tab3();
throw new IllegalStateException("Unexpected position " + position);
}
#Override
public int getCount() {
return 3;
}
}
Use this :
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
// adding the fragments here with titles
adapter.addFragment(new OneFragment(), "ONE");
adapter.addFragment(new TwoFragment(), "TWO");
adapter.addFragment(new ThreeFragment(), "THREE");
viewPager.setAdapter(adapter);
}
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
//return null;
}
}
then set it like this:
ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout) view.findViewById(R.id.sliding_tabs);
tabLayout.setupWithViewPager(viewPager);
hope it helps!!!

Dialog getActivity not working with Data Binding

I have implemented a ricyvlerview search, and i want to listen for clicks, but context is allways null, i even tryed to move the method to an activity and i got the same result
This is my first time messing arround with Data binding i searched alot here but i can't find what i am doing wrong
item_exemple.xml
<layout xmlns:android="http://schemas.android.com/apk/res/android">
<data>
<variable
name="model"
type="pt.condutorresponsavel.android.testescodigo.Search.models.ExampleModel"/>
<variable
name="handlers"
type="pt.condutorresponsavel.android.testescodigo.Study"/>
</data>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/selectableItemBackground"
android:clickable="true">
<TextView
android:onClick="#{(v) -> handlers.onCategoryClick(v,model)}"
android:ellipsize="end"
android:lines="1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="8dp"
android:text="#{model.text}"/>
<View
android:layout_marginTop="40dp"
android:layout_width="match_parent"
android:layout_height="2dp"
android:background="#color/colorPrimary"
android:alpha="0.17"/>
</FrameLayout>
ExampleViewHolder.java
public class ExampleViewHolder extends SortedListAdapter.ViewHolder<ExampleModel> {
private final ItemExampleBinding mBinding;
public ExampleViewHolder(ItemExampleBinding binding) {
super(binding.getRoot());
mBinding = binding;
}
#Override
protected void performBind(ExampleModel item) {
mBinding.setModel(item);
mBinding.setHandlers(new Study());
}
}
Study.java
public class Study extends Fragment {
public static Fragment fragment;
public static SearchView searchView;
Context context;
private final String[] pageNames = {"Favorites", ""};
ViewPager pager;
private OnFragmentInteractionListener mListener;
public Study() { }
public static Estudo newInstance(String param1, String param2) {
Estudo fragment = new Estudo();
Bundle args = new Bundle();
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_estudo, container, false);
fragment = this;
...
pager = (ViewPager) view.findViewById(R.id.pager);
pager.setAdapter(buildAdapter());
return view;
}
private PagerAdapter buildAdapter() {
return(new SampleAdapter(getActivity(), getChildFragmentManager()));
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
this.context = context;
}
public interface OnFragmentInteractionListener {
void onFragmentInteraction(Uri uri);
}
public class SampleAdapter extends FragmentPagerAdapter {
Context ctxt = null;
public SampleAdapter(Context ctxt, FragmentManager mgr) {
super(mgr);
this.ctxt = ctxt;
}
#Override
public int getCount() {
return (2);
}
#Override
public Fragment getItem(int position) {
if (position == 0) {
return Favorites.newInstance(position + 1);
}else{
return otherFragment.newInstance(position + 1);
}
}
#Override
public String getPageTitle ( int position){
return (String.valueOf(pageNames[position]));
}
}
public void onCategoryClick(View view, ExampleModel model) {
Log.d("mTag", "Index: " + model.getId());
Dialog dialog = new Dialog(getActivity()); //NullPointerException
dialog.setContentView(R.layout.dialog_pergunta);
dialog.show();
}
public static class Favorites extends Fragment{...} //RecyclerView is in here
public static class otherFragment extends Fragment{...}
}
Problem
public void onCategoryClick(View view, ExampleModel model) {
Log.d("mTag", "Index: " + model.getId());
Dialog dialog = new Dialog(getActivity()); //NullPointerException
dialog.setContentView(R.layout.dialog);
dialog.show();
}
i tried setting the context in onAttach and also tried to use
final Context contex = getActivity();
but nothing worked outside onCategoryClick the context is not null but inside onCategoryClick the context is null
how can i overcome this?
EDIT
if i don't declare my interface static i get this
NullPointerException: Attempt to invoke interface method 'void pt.condutorresponsavel.android.testescodigo.Study$OnItemClic‌​k.onClick(long)' on a null object reference at
pt.condutorresponsavel.android.testescodigo.Study.onCategory‌​Click(Study.java:303‌​)
I was able to fix this, there may be better options to achive the same result but since i am not a expert this was what i come up with.
I created a Interface, on my fragment when the onCategoryClick is called i call a my interface.
static OnItemClick onItemClick;
...
public void onCategoryClick(View view, ExampleModel model) {
onItemClick.onClick(model.getId());
}
public interface OnItemClick{
void onClick(long index);
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
onItemClick = new OnItemClick() {
#Override
public void onClick(long index) {
Log.d(TAG, "myIndex: " + index);
Dialog dialog = new Dialog(getActivity());
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
dialog.setContentView(R.layout.dialog);
}
}

Start Timer in GridView

I have a problem with the GridView.
I would like to have a Grid with pictures and under each of them should be a timer. When I click one of the images, there should start the timer bellow of it.
How can I adapt TextViews and Images to a Gridview and let the TextView change every second.
I changed my code now to this
MainActivity
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.Toast;
import java.util.ArrayList;
public class MainActivity extends Activity implements Runnable{
/** The Constant INTERVALL. */
private static final int INTERVALL = 1000;
private ImageAdapter mAdapter;
private ArrayList<String> listText;
private ArrayList<Integer> listImage;
private GridView gridView;
/** The handler. */
private Handler handler = new Handler();
public boolean timerRuns = false;
public int time ;
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.grid);
//GridView gridview = (GridView) findViewById(R.id.gridview);
//gridview.setAdapter(new ImageAdapter(this));
prepareList();
// prepared arraylist and passed it to the Adapter class
mAdapter = new ImageAdapter(this, listText, listImage);
// Set custom adapter to gridview
gridView = (GridView) findViewById(R.id.gridView);
gridView.setAdapter(mAdapter);
// Implement On Item click listener
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long arg3) {
Toast.makeText(MainActivity.this, mAdapter.getItem(position), Toast.LENGTH_SHORT).show();
}
});
}
#Override
public final void run() {
chronometer();
}
public void startTimer(View v) {
timerRuns = true;
time = 5*60;
update();
this.handler.postDelayed(this, INTERVALL);
}
public void stopTimer(View v) {
timerRuns = false;
handler.removeCallbacks(this);
}
public void chronometer(){
time = time -1;
update();
handler.postDelayed(this, INTERVALL);
}
private void update(){
updateScreen();
}
private void updateScreen(){
//TextView tvChronometer = (TextView)findViewById(R.id.tvChronometer);
//tvChronometer.setText(Integer.toString(time));
}
public void prepareList()
{
listText = new ArrayList<String>();
listText.add("Sample");
listText.add("Brazil");
listText.add("Canada");
listText.add("China");
listText.add("France");
listText.add("Germany");
listText.add("Iran");
listText.add("Italy");
listText.add("Japan");
listText.add("Korea");
listText.add("Mexico");
listText.add("Netherlands");
listText.add("Portugal");
listText.add("Russia");
listText.add("Saudi Arabia");
listText.add("Spain");
listText.add("Turkey");
listText.add("United Kingdom");
listText.add("United States");
listImage = new ArrayList<Integer>();
listImage.add(R.drawable.sample_0);
listImage.add(R.drawable.sample_3);
listImage.add(R.drawable.sample_3);
listImage.add(R.drawable.sample_7);
listImage.add(R.drawable.sample_1);
listImage.add(R.drawable.sample_6);
listImage.add(R.drawable.sample_2);
listImage.add(R.drawable.sample_7);
listImage.add(R.drawable.sample_4);
listImage.add(R.drawable.sample_5);
listImage.add(R.drawable.sample_0);
listImage.add(R.drawable.sample_5);
listImage.add(R.drawable.sample_0);
listImage.add(R.drawable.sample_2);
listImage.add(R.drawable.sample_1);
listImage.add(R.drawable.sample_4);
listImage.add(R.drawable.sample_3);
listImage.add(R.drawable.sample_1);
listImage.add(R.drawable.sample_6);
}
}
The ImageAdapter
`public class ImageAdapter extends BaseAdapter {
private ArrayList<String> listText;
private ArrayList<Integer> listImage;
private Activity activity;
public ImageAdapter(Activity activity,ArrayList<String> listText, ArrayList<Integer> listImage) {
super();
this.listText = listText;
this.listImage = listImage;
this.activity = activity;
}
#Override
public int getCount() {
return listText.size();
}
#Override
public String getItem(int position) {
return listText.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
public static class ViewHolder
{
public ImageView imgView;
public TextView txtView;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder view;
LayoutInflater inflator = activity.getLayoutInflater();
if(convertView==null)
{
view = new ViewHolder();
convertView = inflator.inflate(R.layout.element, null);
view.txtView = (TextView) convertView.findViewById(R.id.eText);
view.imgView = (ImageView) convertView.findViewById(R.id.eImage);
convertView.setTag(view);
}
else
{
view = (ViewHolder) convertView.getTag();
}
view.txtView.setText(listText.get(position));
view.imgView.setImageResource(listImage.get(position));
return convertView;
}
}`
my gridview
<?xml version="1.0" encoding="utf-8"?>
<GridView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/gridView"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:columnWidth="110dp"
android:numColumns="auto_fit"
android:verticalSpacing="10dp"
android:horizontalSpacing="10dp"
android:stretchMode="columnWidth"
android:gravity="center"
/>
and my element.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="5dp" >
<ImageView
android:id="#+id/eImage"
android:layout_width="120dp"
android:layout_height="120dp"
android:src="#color/Bisque" >
</ImageView>
<TextView
android:id="#+id/eText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:textSize="15sp" >
</TextView>
I hope you can help me.
1. Creating a gridview with text and image in each cell
Take a look at the documentation for GridView:
http://developer.android.com/guide/topics/ui/layout/gridview.html
The key method there is the public View getView(int position, View convertView, ViewGroup parent)
That method returns a view for each cell in the grid. You can create an XML layout that includes the TextView and ImageView. In the getView method for the adapter inflate the XML layout, attach an onClickListener so you can start the timer and return it as a view.
2. Updating the TextView from the grid
Keep in mind that a gridview contains contains multiple views, each of which can come from the same resource so this: TextView tvChronometer = (TextView)findViewById(R.id.tvChronometer); is not going to work in a gridview.
What you need to do is to get the specific view from the cell that you need (or iterate through all of them) and update the view. Something like this:
//First get the view for the cell assuming it's a composite view
View cellView = (TextView) gridview.getChildAt(position);
//Then get the actual TextView from that grid cell
TextView tvChronometer = cellView.findViewById(R.id.tvChronometer);
Although the best way in my opinion is to save a reference to the TextView when you a creating/instantiating it in the adapter.

Simple fragmented tabhost in android

I am trying to implement fragment-Tabhost in android
MainActivity.java
public class MainActivity extends Activity {
// Declare Tab Variable
ActionBar.Tab Tab1, Tab2;
Fragment fragmentTab2 = new FragmentTab2();
//Fragment fragmentTab3 = new FragmentTab3();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ActionBar actionBar = getActionBar();
// Hide Actionbar Icon
actionBar.setDisplayShowHomeEnabled(false);
// Hide Actionbar Title
actionBar.setDisplayShowTitleEnabled(false);
// Create Actionbar Tabs
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Set Tab Icon and Titles
Tab1 = actionBar.newTab().setText("Tab1");
//Tab2 = actionBar.newTab().setText("Tab2");
// Set Tab Listeners
Tab1.setTabListener(new TabListener(fragmentTab2));
//Tab2.setTabListener(new TabListener(fragmentTab3));
// Add tabs to actionbar
actionBar.addTab(Tab1);
//actionBar.addTab(Tab2);
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
FragmentTab2.java
public class FragmentTab2 extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragmenttab2, container, false);
return rootView;
}
}
FragmentTab3.java
public class FragmentTab3 extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragmenttab3, container, false);
return rootView;
}
}
At present just one tab with one activity is displaying
What i am trying to do ::
click on tab1(first time) - - - - > FragmentTab2.java must display
Click on tab1(second time) - - - - > FragmentTab3.java must display
click on tab1(third time)- - - - > FragmentTab2.java must display again
This cycle must keep on repeating itself
What code changes should i need to make ?
Any IDEAS ?
I got it to work, you still need to make some adjustments, but it will get you started.
import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.app.ActionBar.TabListener;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
public class MainActivity extends FragmentActivity implements Notify, TabListener {
ActionBar.Tab tab1;
ActionBar actionBar;
int count = 1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getFragmentManager().beginTransaction().replace(R.id.container, new FragmentTab2()).commit();
actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
tab1 = actionBar.newTab().setText("Tab1");
tab1.setTabListener(this);
actionBar.addTab(tab1);
}
//Callback
#Override
public void notifyTabListener() {
count++;
Tab tab = actionBar.newTab().setText("Tab" + count);
tab.setTabListener(this);
actionBar.addTab(tab);
}
//Tablistener
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
ft.replace(R.id.container, new FragmentTab2());
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
ft.add(new FragmentTab2(), "Tab" + count);
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
}
}
Notify callback:
public interface Notify {
public void notifyTabListener();
}
FragmentTab2:
public class FragmentTab2 extends Fragment implements OnClickListener {
Notify mCallback;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.f2, container, false);
LinearLayout layout = (LinearLayout) rootView.findViewById(R.id.layout2);
layout.setOnClickListener(this);
return rootView;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
mCallback = (MainActivity) activity;
}
#Override
public void onClick(View v) {
mCallback.notifyTabListener();
}
}
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/container"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
</RelativeLayout>
f2.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/layout2"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView android:text="Fragment2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
You need to implement TabListener and set to Tab1.setTabListener().
When onTabSelected(), repeating replace fragment1 or fragment2.

Android ImageAdapter with Gridview in Fragment

I have an adapter with gridview that works as an Activity. I am trying to place it in a Fragment now and converted things but it does not work. When I include the IconFragmentSystem in my Activity I get a force close when I try to open the Activity.
I know the Activity works because I can use other Fragments and everything is okay so I know my issue lies within this file.
package com.designrifts.ultimatethemeui;
import com.designrifts.ultimatethemeui.R;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;
import java.util.ArrayList;
public class IconFragmentSystem extends Fragment implements AdapterView.OnItemClickListener{
private static final String RESULT_OK = null;
public Uri CONTENT_URI;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.main, container, false);
super.onCreate(savedInstanceState);
int iconSize=getResources().getDimensionPixelSize(android.R.dimen.app_icon_size);
GridView gridview = (GridView) getActivity().findViewById(R.id.icon_grid);
gridview.setAdapter(new IconAdapter(this, iconSize));
gridview.setOnItemClickListener(this);
CONTENT_URI=Uri.parse("content://"+iconsProvider.class.getCanonicalName());
return view;
}
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
String icon=adapterView.getItemAtPosition(i).toString();
Intent result = new Intent(null, Uri.withAppendedPath(CONTENT_URI,icon));
setResult(RESULT_OK, result);
finish();
}
private void setResult(String resultOk, Intent result) {
// TODO Auto-generated method stub
}
private void finish() {
// TODO Auto-generated method stub
}
private class IconAdapter extends BaseAdapter{
private Context mContext;
private int mIconSize;
public IconAdapter(Context mContext, int iconsize) {
super();
this.mContext = mContext;
this.mIconSize = iconsize;
loadIcon();
}
public IconAdapter(IconFragmentSystem iconssystem, int iconSize) {
// TODO Auto-generated constructor stub
}
#Override
public int getCount() {
return mThumbs.size();
}
#Override
public Object getItem(int position) {
return mThumbs.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null) {
imageView = new ImageView(mContext);
imageView.setLayoutParams(new GridView.LayoutParams(mIconSize, mIconSize));
} else {
imageView = (ImageView) convertView;
}
imageView.setImageResource(mThumbs.get(position));
return imageView;
}
private ArrayList<Integer> mThumbs;
////////////////////////////////////////////////
private void loadIcon() {
mThumbs = new ArrayList<Integer>();
final Resources resources = getResources();
final String packageName = getActivity().getApplication().getPackageName();
addIcon(resources, packageName, R.array.systemicons);
}
private void addIcon(Resources resources, String packageName, int list) {
final String[] extras = resources.getStringArray(list);
for (String extra : extras) {
int res = resources.getIdentifier(extra, "drawable", packageName);
if (res != 0) {
final int thumbRes = resources.getIdentifier(extra,"drawable", packageName);
if (thumbRes != 0) {
mThumbs.add(thumbRes);
}
}
}
}
}
}
I have tried different ways to implement this but all have failed and I could really use help pointing me in the right direction.
This is my xml in layout
<RelativeLayout 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" >
<GridView
android:id="#+id/gridview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:columnWidth="90dp"
android:numColumns="auto_fit"
android:verticalSpacing="10dp"
android:horizontalSpacing="10dp"
android:stretchMode="columnWidth"
android:gravity="center"
/>
</RelativeLayout>
I was able to fix the issue
I changed
GridView gridview = (GridView) getActivity().findViewById(R.id.icon_grid);
to
GridView gridview = (GridView) view.findViewById(R.id.icon_grid);
and I also changed
gridview.setAdapter(new IconAdapter(this, iconSize));
to
gridview.setAdapter(new IconAdapter(getActivity(), iconSize));
Try this.
gridView = (GridView) rootView.findViewById(R.id.gridView);
gridView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view,int pos, long l) {
// do something...
}
});
For more info, see this link:
Android gridview in fragment adapter constructor missing
GridView gridview = (GridView) getActivity().findViewById(R.id.icon_grid);
should be
GridView gridview = (GridView) container.findViewById(R.id.icon_grid);
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.main, container, false);
int iconSize = getResources().getDimensionPixelSize(android.R.dimen.app_icon_size);
GridView gridview = (GridView) view.findViewById(R.id.icon_grid);
gridview.setAdapter(new IconAdapter(this, iconSize));
gridview.setOnItemClickListener(this);
CONTENT_URI = Uri.parse("content://"+iconsProvider.class.getCanonicalName());
return view;
}
Your going to want to remove the call to super, that is a leftover from you activity, the fragment does not call this method.

Categories