I have a tablayout with 5 tabs. Each tab has an icon and title. I want to change color of icon and title for tab that is selected and tab that is un-selected. For this i try using custom tabs but it didn't work. Here is my code for custom_tab.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<ImageView
android:layout_width="20dp"
android:layout_height="20dp"
android:layout_gravity="center"
android:id="#+id/tabIcon"/>
<com.prj.shopt.CustomTextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#C1C1C1"
android:gravity="center"
android:id="#+id/tabTitle"/>
</LinearLayout>
and my code in Home2Activity:
package com.prj.shopt;
import android.graphics.Typeface;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.AppCompatTextView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class Home2Activity extends AppCompatActivity implements TabLayout.OnTabSelectedListener {
private TabLayout tabs;
private ViewPager viewPager;
private HomeTabsAdapter tabsAdapter;
private int[] activeIcons={R.drawable.homeactive,R.drawable.category_highlighted,R.drawable.heart_highlighted,
R.drawable.basketactive,R.drawable.avatar_highlighted};
private int[] deactiveIcons={R.drawable.homedeactive,R.drawable.category_default,R.drawable.heart_default,
R.drawable.basketdeactive,R.drawable.avatar_default};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home2);
tabs=findViewById(R.id.homeTabs);
viewPager=findViewById(R.id.tabsViewPager);
setupViewPager();
tabs.setupWithViewPager(viewPager);
setupTabIcons();
tabs.addOnTabSelectedListener(this);
}
private void setupTabIcons(){
if(tabs.getTabCount()<5)
return;
int len=activeIcons.length;
for(int j=0;j<len;j++) {
//tabs.getTabAt(j).setIcon(deactiveIcons[j]);
tabs.getTabAt(j).setCustomView(HomeTabsAdapter.getTabView(deactiveIcons[j], R.color.tab_inactive, "test", Home2Activity.this,tabs));
}
tabs.getTabAt(0).setCustomView(HomeTabsAdapter.getTabView(activeIcons[0],R.color.tab_active,"test",Home2Activity.this,tabs));
}
private void setupViewPager(){
tabsAdapter=new HomeTabsAdapter(getSupportFragmentManager());
viewPager.setAdapter(tabsAdapter);
setupFragments();
}
private void setupFragments() {
for(int i=0;i<5;i++)
tabsAdapter.addFragment(new FavFragment(),getResources().getString(R.string.favTab));
}
#Override
public void onTabSelected(TabLayout.Tab tab) {
//tab.setIcon(activeIcons[tab.getPosition()]);
tab.setCustomView(HomeTabsAdapter.getTabView(activeIcons[tab.getPosition()],R.color.tab_active,"test",Home2Activity.this,tabs));
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
//tab.setIcon(deactiveIcons[tab.getPosition()]);
tab.setCustomView(HomeTabsAdapter.getTabView(deactiveIcons[tab.getPosition()],R.color.tab_inactive,"test",Home2Activity.this,tabs));
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
//tab.setIcon(activeIcons[tab.getPosition()]);
tab.setCustomView(HomeTabsAdapter.getTabView(activeIcons[tab.getPosition()],R.color.tab_active,"test",Home2Activity.this,tabs));
}
}
and Here is my adapter(HomeTabsAdapter.java):
import android.content.Context;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import org.w3c.dom.Text;
import java.util.ArrayList;
import java.util.List;
public class HomeTabsAdapter extends FragmentPagerAdapter {
List<Fragment> fragments;
List<String> tabTitles;
public HomeTabsAdapter(FragmentManager fm) {
super(fm);
fragments=new ArrayList<>();
tabTitles=new ArrayList<>();
}
#Override
public Fragment getItem(int position) {
return fragments.get(position);
}
#Override
public int getCount() {
return fragments.size();
}
public void addFragment(Fragment fragment,String title){
fragments.add(fragment);
tabTitles.add(title);
notifyDataSetChanged();
}
public static View getTabView(int imageId, int color, String title, Context context, TabLayout tabLayout){
View v= LayoutInflater.from(context).inflate(R.layout.custom_tab,tabLayout,false);
TextView tabTitle=v.findViewById(R.id.tabTitle);
tabTitle.setText(title);
tabTitle.setTextColor(color);
tabTitle.setTypeface(Utility.getFontTypeFace(context));
ImageView icon=(v.findViewById(R.id.tabIcon));
icon.setImageResource(0);
icon.setImageResource(imageId);
return v;
}
#Override
public CharSequence getPageTitle(int position) {
return tabTitles.get(position);
}
}
And the result is icons with fix color and also titles with fixed color. Nothing change with select and unselect the tabs.
Thanks for any help
Use this method:-
private void setCustomTab(TabLayout tabLayout, int index, String title) {
TextView tab_home = (TextView) LayoutInflater.from(getActivity()).inflate(R.layout.custome_tab, null);
tab_home.setText(title);
tabLayout.getTabAt(index).setCustomView(tab_home);
}
Use this above method like below:-
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
setCustomTab(tabLayout, 0, "Upcoming");
setCustomTab(tabLayout, 1, "Completed");
Related
I am using fragments to get the Tabs style on my app, like seen here:
Tabs
Already deducted that each tab is a fragment and each one has a layout, but i cant display on each one display what i want.
Before having the fragments i had a simple activity to display data from a database on a listview, but now i cant get it to work on one of the fragments, with the following code that i used:
dal = new DAL(TabListas.this);
dal.connect(DBAccessMode.READ);
Cursor cursor = dal.selectALLFromRegSintomas();
// Find ListView to populate
ListView lvItems = (ListView) findViewById(R.id.listv);
// Setup cursor adapter using cursor from last step
RegistosCursorAdapter todoAdapter = new RegistosCursorAdapter(TabListas.this, cursor, 0);
// Attach cursor adapter to the ListView
lvItems.setAdapter(todoAdapter);
How can i make a use the fragments to display data from db in a listview in one fragment ? What should i change ?
VerRegsSintomas.java (like mainactivity.java):
package com.example.bugdroid.menuexe.Activities;
import android.app.Activity;
import android.database.Cursor;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.widget.ListView;
import com.example.bugdroid.menuexe.CursorAdapter.RegistosCursorAdapter;
import com.example.bugdroid.menuexe.R;
import com.example.bugdroid.menuexe.TabFragments.PageAdapter;
import com.example.bugdroid.menuexe.database.DAL;
import com.example.bugdroid.menuexe.database.DBAccessMode;
public class VerRegsSintomas extends AppCompatActivity {
private ViewPager mViewPager;
private DAL dal;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ver_regs_sintomas);
android.support.v7.app.ActionBar actionBar = getSupportActionBar();
actionBar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#1a212c")));
TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
tabLayout.addTab(tabLayout.newTab().setText("Sintomas"));
tabLayout.addTab(tabLayout.newTab().setText("Listas"));
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
final ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
final PageAdapter adapter = new PageAdapter
(getSupportFragmentManager(), tabLayout.getTabCount());
viewPager.setAdapter(adapter);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
}
PageAdapter.java:
package com.example.bugdroid.menuexe.TabFragments;
/**
* Created by BugDroid on 07/06/2016.
*/
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
public class PageAdapter extends FragmentStatePagerAdapter {
int mNumOfTabs;
public PageAdapter(FragmentManager fm, int NumOfTabs) {
super(fm);
this.mNumOfTabs = NumOfTabs;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
TabSintomas tab1 = new TabSintomas();
return tab1;
case 1:
TabListas tab2 = new TabListas();
return tab2;
default:
return null;
}
}
#Override
public int getCount() {
return mNumOfTabs;
}
}
TabSintomas.java:
package com.example.bugdroid.menuexe.TabFragments;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.example.bugdroid.menuexe.R;
public class TabSintomas extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_tab_sintomas, container, false);
}
}
fragment_Tab_sintomas.xml
<?xml version="1.0" encoding="utf-8"?>
<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"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".Activities.VerRegistos">
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/listv"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true" />
</RelativeLayout>
Try this Example ,here you can find a TabLayout with the help of Viewpager and custom toolbar and along with this all you can find a navigation drawer over there.
I have a problem with android a ViewPager setup with FragmentPagerAdapter and TabLayout
TabLayout works fine. But, the code in all tabs run simultaneously. I want the code in the currently selected tab to run
This is my activity
package francesco.prisco.siamostudenti.ui;
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.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import java.util.ArrayList;
import java.util.List;
import francesco.prisco.siamostudenti.R;
import francesco.prisco.siamostudenti.ui.fragments.CalendarFragment;
import francesco.prisco.siamostudenti.ui.fragments.ChatFragment;
import francesco.prisco.siamostudenti.ui.fragments.EmailFragment;
import francesco.prisco.siamostudenti.ui.fragments.HomeFragment;
import francesco.prisco.siamostudenti.ui.fragments.ProfiloFragment;
public class HomeTabActivity extends AppCompatActivity {
// private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home_tab);
// 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);
setupTabIcons();
}
private void setupTabIcons() {
int[] tabIcons = {
R.drawable.ic_home,
R.drawable.ic_calendar,
R.drawable.ic_chat,
R.drawable.ic_email,
R.drawable.ic_profile
};
tabLayout.getTabAt(0).setIcon(tabIcons[0]);
tabLayout.getTabAt(1).setIcon(tabIcons[1]);
tabLayout.getTabAt(2).setIcon(tabIcons[2]);
tabLayout.getTabAt(3).setIcon(tabIcons[3]);
tabLayout.getTabAt(4).setIcon(tabIcons[4]);
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFrag(new HomeFragment(), "HOME");
adapter.addFrag(new CalendarFragment(), "CALENDAR");
adapter.addFrag(new ChatFragment(), "CHAT");
adapter.addFrag(new EmailFragment(), "EMAIL");
adapter.addFrag(new ProfiloFragment(), "PROFILO");
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 addFrag(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
// return null to display only the icon
return null;
}
}
}
And this is code of a fragment
package francesco.prisco.siamostudenti.ui.fragments;
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import francesco.prisco.siamostudenti.R;
import francesco.prisco.siamostudenti.ui.HomeTabActivity;
public class ProfiloFragment extends Fragment {
public ProfiloFragment() {}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_profilo, container, false);
return rootView;
}
}
Help me please
Like #Mrugesh Thaker says, all of the Fragment lifecycle functions - onCreateView(), etc. are executed every time the View of a Fragment is inflated.
Here, the View of each Fragment is inflated every time it becomes the adjacent Fragment of the current Fragment page.
So, you should move the 'code each Fragment needs to execute' when it becomes the currently selected Fragment page into an OnPageChangeListener
In your HomeTabActivity, when you set up the ViewPager, add an
OnPageChangeListener to yourViewPager
private void setupViewPager(ViewPager viewPager) {
.
.
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener(){
public void onPageScrollStateChanged (int state){
}
public void onPageSelected (int position){
/*
* Define the action to be performed for each page.
* Variable 'position' is the index of the page in the ViewPager
*/
}
public void onPageScrolled (int position, float positionOffset, int positionOffsetPixels){
}
});
}
Learning Resource
Actually, view pager works like that. The main aim of view pager is to enable a user to have smooth swipe , so what it does is , it will create all the fragments that you gave at a time to have smooth swiping flow. This is actually the limitation of it because all the methods of fragment lifecycle are called at a time.
I have an app with three tabs which I control with an FragmentPagerAdapter. Now I want to jump between those tabs when I click on a TextView of one fragment (the fragment with the TextView should be replaced with the destination fragment). And when i click on a Button another Fragment should be overlayed above this fragment with the Button.
I know that those are two different things but I also know that I have to use FragmentTransaction but I can't figure out how to do it.
Could you please help me?
Here is my MainActivy.java:
package letscho.workout;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
public class MainActivity extends AppCompatActivity {
Toolbar toolbar;
ViewPager viewPager;
TabLayout tabLayout;
FragmentManager fragmanager;
FragmentTransaction fragtrans;
Fragment1 fragment1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
viewPager = (ViewPager) findViewById(R.id.viewpager);
ViewPagerAdapter1 viewPagerAdapter1 = new ViewPagerAdapter1(getSupportFragmentManager());
viewPager.setAdapter(viewPagerAdapter1);
tabLayout = (TabLayout) findViewById(R.id.tablayout);
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
tabLayout.setupWithViewPager(viewPager);
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
public static void changefragmentOnBtnClick(){
fragmanager = getFragmentManager();
fragtrans = fragmanager.beginTransaction();
fragtrans.replace(R.id.viewpager, getActivity());
fragtrans.commit();
}
}
And the ViewPager:
package letscho.workout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
public class ViewPagerAdapter1 extends FragmentPagerAdapter {
String [] tabtitlearray = {"Übungen", "Push", "Pull"};
public ViewPagerAdapter1 (FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0: return new Fragment1();
case 1: return new Fragment2();
case 2: return new Fragment3();
}
return null;
}
#Override
public int getCount() {
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
return tabtitlearray[position];
}
}
And the Fragment where all should start:
package letscho.workout;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class Fragment2 extends Fragment {
View contentView2;
TextView textView;
Button btn1;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
contentView2 = inflater.inflate(R.layout.layout2_push, null);
return contentView2;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
textView = (TextView)contentView2.findViewById(R.id.push_text_eins);
textView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
MainActivity.changefragmentOnBtnClick();
}
});
btn1 = (Button) contentView2.findViewById(R.id.btn_timer1);
btn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
#Override
public void onStop() {
super.onStop();
}
}
I had a gridview activity where I was populating the gridview with a custom object (a picture with some custom methods and an onclick listener). I could change the gridview size from the preferences menu. Everything worked beautifully.
I have since added some complexity to the code. Instead of using the normal Activity class, I am now using the FragmentActivity class, a fragmentPageAdapter, and a fragment to which my gridview is bound. This is because eventually I want the app to allow the user "swipe" from fragment to fragment.
Since using the fragment in this way, I am noticing a repeatable bug whenever I try to resize the gridview from the preferences menu: some of the objects get resized properly, other elements do not resize. Instead, they keep the same size that they had prior to changing the preference. Here is a screenshot:
This only happens when I try resizing from the preferences menu. Other calls to my resize method, such as on a configuration change, resize all of the gridview elements correctly.
I would appreciate any suggestions!
Here is my Code:
MAIN ACTIVITY:
package com.KhalidSorensen.animalsounds;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.content.res.Configuration;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.GridView;
public class MainActivity extends FragmentActivity implements OnSharedPreferenceChangeListener{
private MyFragment m_myFragment = new MyFragment();
private ViewPager m_viewPager;
private static SharedPreferences m_prefs;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
m_prefs = PreferenceManager.getDefaultSharedPreferences(this);
m_prefs.registerOnSharedPreferenceChangeListener(this);
setContentView(R.layout.activity_main);
m_viewPager = (ViewPager) findViewById(R.id.pager);
m_viewPager.setAdapter(new MyAdapter(getSupportFragmentManager(), m_myFragment));
}
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
Log.i("Khalid","MainActivity: onSharedPreferenceChanged");
if (key.equals("key_prefs_enable_lscape")){
//do nothing for now
}else if (key.equals("key_prefs_picture_size")){
SetColumnWidth(m_myFragment.getM_gridView());
}
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
Log.i("Khalid","FragAnimalSounds: onConfigurationChanged");
SetColumnWidth(m_myFragment.getM_gridView());
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
Log.i("Khalid","MainActivity: onCreateOptionsMenu");
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.options_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.lbl_opt_menu_settings:
Intent i = new Intent("android.intent.action.PREFERENCES");
startActivity(i);
break;
case R.id.lbl_opt_menu_quit:
finish();
break;
default:
finish();
break;
}
return true;
}
public static void SetColumnWidth(GridView GV) {
Log.i("Khalid","MainActivity: SetColumnWidth");
int NumColumns, DesiredColumnWidth;
//Get the desired number of columns from the key prefs
NumColumns = Integer.parseInt(m_prefs.getString("key_prefs_picture_size","2"));
//Determine the desired column width
if (NumColumns == 1){
DesiredColumnWidth = 200;
}else if (NumColumns == 2){
DesiredColumnWidth = 100;
}else{
DesiredColumnWidth = 50;
}
//Set the desired column width
GV.setColumnWidth(DesiredColumnWidth);
}
}
class MyAdapter extends FragmentPagerAdapter{
Fragment m_frag_A = null;
public MyAdapter(FragmentManager fm, Fragment A) {
super(fm);
m_frag_A = A;
}
#Override
public Fragment getItem(int i) {
return m_frag_A; //only 1 item for now
}
#Override
public int getCount() {
return 1;
}
#Override
public CharSequence getPageTitle(int i) {
return "Title Frag A"; //only 1 item for now
}
}
MY FRAGMENT (THERE IS ONLY ONE FOR NOW):
package com.KhalidSorensen.animalsounds;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.GridView;
public class MyFragment extends Fragment {
private GridView m_gridView;
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
Log.i("Khalid","FragAnimalSounds: onCreateView");
View view = inflater.inflate(R.layout.activity_animal_sounds, container, false);
m_gridView = (GridView) view.findViewById(R.id.lbl_gridView);
m_gridView.setAdapter(new VivzAdapter(view.getContext()));
MainActivity.SetColumnWidth(m_gridView);
return view;
}
public GridView getM_gridView() {
return m_gridView;
}
}
MY GRIDVIEW ADAPTER:
package com.KhalidSorensen.animalsounds;
import java.util.ArrayList;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
public class VivzAdapter extends BaseAdapter {
private Context m_context;
private ArrayList<AnimalKind> m_list = new ArrayList<AnimalKind>();
VivzAdapter(Context ctx) {
m_context = ctx;
int[] animalphotos = { R.drawable.cat_1, R.drawable.cow_1,
R.drawable.dog_1, R.drawable.donkey_1, R.drawable.duck_1,
R.drawable.peacock_1, R.drawable.rooster_1, R.drawable.seal_1 };
for (int i = 0; i <= 7; i++) {
AnimalKind animalKind = new AnimalKind(m_context, animalphotos[i]);
m_list.add(animalKind);
}
}
#Override
public int getCount() {
return m_list.size();
}
#Override
public AnimalKind getItem(int position) {
return m_list.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int i, View v, ViewGroup vg) {
return m_list.get(i);
}
}
MY CUSTOM OBJECT CLASS. THESE OBJECTS ARE POPULATING THE GRIDVIEW:
package com.KhalidSorensen.animalsounds;
import android.content.Context;
import android.graphics.Color;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
public class AnimalKind extends ImageView implements OnClickListener{
private int m_imageId;
public AnimalKind(Context ctx, int imageId) {
super(ctx);
m_imageId = imageId;
super.setImageResource(imageId);
super.setAdjustViewBounds(true);
super.setScaleType(ImageView.ScaleType.FIT_XY);
super.setPadding(1, 1, 1, 1);
super.setBackgroundColor(Color.BLACK);
super.setOnClickListener(this);
}
//#Override
public void onClick(View v) {
//Do Something
}
#Override
public void setPressed(boolean pressed) {
//Do Something
}
public int getM_imageId() {
return m_imageId;
}
}
MY PREFERENCE ACTIVITY:
package com.KhalidSorensen.animalsounds;
import android.os.Bundle;
import android.preference.PreferenceActivity;
import android.util.Log;
public class Preferences extends PreferenceActivity {
#SuppressWarnings("deprecation")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
Log.i("Khalid", "Preferences: onCreate");
}
}
MY XML FOR MY MAIN ACTIVITY:
<android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<android.support.v4.view.PagerTitleStrip
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/lbl_title"
android:background="#33B5E5"
android:layout_gravity="top"
android:paddingTop="0dp"
android:paddingBottom="0dp"> "
</android.support.v4.view.PagerTitleStrip>
</android.support.v4.view.ViewPager>
AND FINALLY, MY XML FOR THE GRIDVIEW:
<?xml version="1.0" encoding="utf-8"?>
<GridView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/lbl_gridView"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_gravity="center_horizontal"
android:layout_margin="0px"
android:alwaysDrawnWithCache="false"
android:animateLayoutChanges="false"
android:background="#android:color/white"
android:columnWidth="130dp"
android:drawSelectorOnTop="true"
android:horizontalSpacing="#dimen/activity_horizontal_margin"
android:listSelector="#null"
android:numColumns="auto_fit"
android:padding="#dimen/activity_horizontal_margin"
android:scrollbarStyle="insideOverlay"
android:smoothScrollbar="true"
android:stretchMode="none"
android:verticalSpacing="#dimen/activity_vertical_margin" >
</GridView>
Use CENTER_INSIDE a scale type for your image view.
super.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
another thing that I would change is the way you handle the column width. I would remove the android:numColumns="auto_fit". On the other hand you know that the number of columns is the cealing of WidthViewGrid/desiderePicSize, where the most common case for WidthViewGrid is the screen's width. On then programmatically you can set number of columns of your GridView with setNumberOfColumns
I would say:
A. After calling setColumnWidth call the gridview.invalidate()
B. After returning from the change preference - call adapter's notifyDataSetChanged in order to make sure it re-creates the views in the adapter (i.e. getView will be called)
i use "Actionbarsherlock" in my project
First i import "Actionbarsherlock" in my project then delete folder "libs"
But my question is how can I change the code below؟
mainactivity
package info.androidhive.tabsswipe;
import info.androidhive.tabsswipe.adapter.TabsPagerAdapter;
import android.annotation.SuppressLint;
import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
#SuppressLint("NewApi")
public class MainActivity extends FragmentActivity implements
ActionBar.TabListener {
private ViewPager viewPager;
private TabsPagerAdapter mAdapter;
private ActionBar actionBar;
// Tab titles
private String[] tabs = { "water"," time" };
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Initilization
viewPager = (ViewPager) findViewById(R.id.pager);
actionBar = getActionBar();
mAdapter = new TabsPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(mAdapter);
actionBar.setHomeButtonEnabled(false);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Adding Tabs
for (String tab_name : tabs) {
actionBar.addTab(actionBar.newTab().setText(tab_name)
.setTabListener(this));
}
/**
* on swiping the viewpager make respective tab selected
* */
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
// on changing the page
// make respected tab selected
actionBar.setSelectedNavigationItem(position);
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
});
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
// on tab selected
// show respected fragment view
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
}}
MoviesFragment
package info.androidhive.tabsswipe;
import info.androidhive.tabsswipe.R;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class MoviesFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_movies,container,false);
return rootView;
}
}
GamesFragment
package info.androidhive.tabsswipe;
import info.androidhive.tabsswipe.R;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class GamesFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_games, container,false);
return rootView;
}}
TabsPagerAdapte
package info.androidhive.tabsswipe;
import info.androidhive.tabsswipe.GamesFragment;
import info.androidhive.tabsswipe.MoviesFragment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
public class TabsPagerAdapter extends FragmentPagerAdapter {
public TabsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int index) {
switch (index) {
case 0:
// Games fragment activity
return new GamesFragment();
case 1:
// Movies fragment activity
return new MoviesFragment();
}
return null;
}
#Override
public int getCount() {
// get item count - equal to number of tabs
return 2;
}}
Please help me to solve this problem
bro remove your email adress from the question.Now coming to your question your actionbar should be an object of supportActionbar.Change the getActionBar() to getSupportActionBar()l.And secondly,your main activity should extend sherlockActivity.Lastly,change the importation from the android actionbar to the sherlock actionbar