How to handle scrolling of fragment's layout inside SlidingTabLayout - android-fragments

If i have to 2 tabs inside ViewPager.and each tab have it's own fragment associated with it.if the fragments of respective tabs have ScrollView as MainView .if i scrolldown the layout of first tab and move to second tab and again swipe back to first it is in same scrolled state as i left it.
So How can i get the scroll automaticaly to the top when i click or swipe to tab.
i have tried Scrollview.fullScroll(View.FOCUS_UP); and Scrollview.scrollTo(0,0);
ViewPagerAdapter.java
public class ViewPagerAdapter extends FragmentStatePagerAdapter {
private CharSequence Titles[]; // This will Store the Titles of the Tabs which are Going to be passed when ViewPagerAdapter is created
private int NumbOfTabs; // Store the number of tabs, this will also be passed when the ViewPagerAdapter is created
public ViewPagerAdapter (FragmentManager fm, CharSequence mTitles[], int mNumbOfTabsumb) {
super(fm);
this.Titles = mTitles;
this.NumbOfTabs = mNumbOfTabsumb;
}
#Override
public Fragment getItem(int position) {
if(position == 0) // if the position is 0 we are returning the First tab
{
Tab_1 tab1 = new Tab_1();
return tab1;
}
else // As we are having 2 tabs if the position is now 0 it must be 1 so we are returning second tab
{
Tab_2 tab2 = new Tab_2();
return tab2;
}
}
#Override
public CharSequence getPageTitle(int position)
{
return Titles[position];
}
#Override
public int getCount() {
return NumbOfTabs;
}}
SlidingTabLayout.java
public class SlidingTabLayout extends HorizontalScrollView {
public interface TabColorizer {
int getIndicatorColor(int position);
}
public interface TabIconProvider {
int getPageIconResId(int position);
}
private static final int TITLE_OFFSET_DIPS = 24;
private static final int TAB_VIEW_PADDING_DIPS = 16;
private static final int TAB_VIEW_TEXT_SIZE_SP = 12;
private int mTitleOffset;
private int mTabViewLayoutId;
private int mTabViewTextViewId;
private boolean mDistributeEvenly;
private ViewPager mViewPager;
private SparseArray<String> mContentDescriptions = new SparseArray<String>();
private ViewPager.OnPageChangeListener mViewPagerPageChangeListener;
private final SlidingTabStrip mTabStrip;
public SlidingTabLayout(Context context) {
this(context, null);
}
public SlidingTabLayout(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public SlidingTabLayout(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
// Disable the Scroll Bar
setHorizontalScrollBarEnabled(false);
// Make sure that the Tab Strips fills this View
setFillViewport(true);
mTitleOffset = (int) (TITLE_OFFSET_DIPS * getResources().getDisplayMetrics().density);
mTabStrip = new SlidingTabStrip(context);
addView(mTabStrip, LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
}
/**
* Set the custom {#link //com.google.samples.apps.iosched.ui.widget.SlidingTabLayout.TabColorizer} to be used.
*
* If you only require simple custmisation then you can use
* {#link #setSelectedIndicatorColors(int...)} to achieve
* similar effects.
*/
public void setCustomTabColorizer(TabColorizer tabColorizer) {
mTabStrip.setCustomTabColorizer(tabColorizer);
}
public void setDistributeEvenly(boolean distributeEvenly) {
mDistributeEvenly = distributeEvenly;
}
/**
* Sets the colors to be used for indicating the selected tab. These colors are treated as a
* circular array. Providing one color will mean that all tabs are indicated with the same color.
*/
public void setSelectedIndicatorColors(int... colors) {
mTabStrip.setSelectedIndicatorColors(colors);
}
public void setTitleTextColor(int color) {
for (int i = 0; i < mTabStrip.getChildCount(); i++) {
if (mTabStrip.getChildAt(i) != null && TextView.class.isInstance(mTabStrip.getChildAt(i))) {
((TextView) mTabStrip.getChildAt(i)).setTextColor(color);
}
}
}
/**
* Set the {#link ViewPager.OnPageChangeListener}. When using {#link //com.google.samples.apps.iosched.ui.widget.SlidingTabLayout} you are
* required to set any {#link ViewPager.OnPageChangeListener} through this method. This is so
* that the layout can update it's scroll position correctly.
*
* #see ViewPager#setOnPageChangeListener(ViewPager.OnPageChangeListener)
*/
public void setOnPageChangeListener(ViewPager.OnPageChangeListener listener) {
mViewPagerPageChangeListener = listener;
}
/**
* Set the custom layout to be inflated for the tab views.
*
* #param layoutResId Layout id to be inflated
* #param textViewId id of the {#link TextView} in the inflated view
*/
public void setCustomTabView(int layoutResId, int textViewId) {
mTabViewLayoutId = layoutResId;
mTabViewTextViewId = textViewId;
}
/**
* Sets the associated view pager. Note that the assumption here is that the pager content
* (number of tabs and tab titles) does not change after this call has been made.
*/
public void setViewPager(ViewPager viewPager) {
mTabStrip.removeAllViews();
mViewPager = viewPager;
if (viewPager != null) {
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
private int mScrollState;
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
int tabStripChildCount = mTabStrip.getChildCount();
if ((tabStripChildCount == 0) || (position < 0) || (position >= tabStripChildCount)) {
return;
}
mTabStrip.onViewPagerPageChanged(position, positionOffset);
View selectedTitle = mTabStrip.getChildAt(position);
int extraOffset = (selectedTitle != null)
? (int) (positionOffset * selectedTitle.getWidth())
: 0;
scrollToTab(position, extraOffset);
if (mViewPagerPageChangeListener != null) {
mViewPagerPageChangeListener.onPageScrolled(position, positionOffset,
positionOffsetPixels);
}
}
#Override
public void onPageSelected(int position) {
if (mScrollState == ViewPager.SCROLL_STATE_IDLE) {
mTabStrip.onViewPagerPageChanged(position, 0f);
scrollToTab(position, 0);
}
for (int i = 0; i < mTabStrip.getChildCount(); i++) {
mTabStrip.getChildAt(i).setSelected(position == i);
}
if (mViewPagerPageChangeListener != null) {
mViewPagerPageChangeListener.onPageSelected(position);
}
}
#Override
public void onPageScrollStateChanged(int state) {
mScrollState = state;
if (mViewPagerPageChangeListener != null) {
mViewPagerPageChangeListener.onPageScrollStateChanged(state);
}
}
});;
populateTabStrip();
}
}
/**
* Create a default view to be used for tabs. This is called if a custom tab view is not set via
* {#link #setCustomTabView(int, int)}.
*/
protected TextView createDefaultTabView(Context context) {
TextView textView = new TextView(context);
textView.setGravity(Gravity.CENTER);
textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, TAB_VIEW_TEXT_SIZE_SP);
textView.setTypeface(Typeface.DEFAULT_BOLD);
textView.setLayoutParams(new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
TypedValue outValue = new TypedValue();
getContext().getTheme().resolveAttribute(android.R.attr.selectableItemBackground,
outValue, true);
textView.setBackgroundResource(outValue.resourceId);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
textView.setAllCaps(true);
}
int padding = (int) (TAB_VIEW_PADDING_DIPS * getResources().getDisplayMetrics().density);
textView.setPadding(padding, padding, padding, padding);
return textView;
}
private void populateTabStrip()
{
final PagerAdapter adapter = mViewPager.getAdapter();
final OnClickListener tabClickListener = new TabClickListener();
for (int i = 0; i < adapter.getCount(); i++) {
View tabView = null;
TextView tabTitleView = null;
if (mTabViewLayoutId != 0) {
// If there is a custom tab view layout id set, try and inflate it
tabView = LayoutInflater.from(getContext()).inflate(mTabViewLayoutId, mTabStrip,
false);
tabTitleView = (TextView) tabView.findViewById(mTabViewTextViewId);
}
if (tabView == null) {
tabView = createDefaultTabView(getContext());
}
if (tabTitleView == null && TextView.class.isInstance(tabView)) {
tabTitleView = (TextView) tabView;
}
if (mDistributeEvenly) {
LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) tabView.getLayoutParams();
lp.width = 0;
lp.weight = 1;
}
tabTitleView.setText(adapter.getPageTitle(i));
tabView.setOnClickListener(tabClickListener);
String desc = mContentDescriptions.get(i, null);
if (desc != null) {
tabView.setContentDescription(desc);
}
mTabStrip.addView(tabView);
if (i == mViewPager.getCurrentItem()) {
tabView.setSelected(true);
}
tabTitleView.setTextColor(getResources().getColorStateList(R.color.colorAccent));
tabTitleView.setTextSize(14);
}
}
public void setContentDescription(int i, String desc) {
mContentDescriptions.put(i, desc);
}
#Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
if (mViewPager != null) {
scrollToTab(mViewPager.getCurrentItem(), 0);
}
}
private void scrollToTab(int tabIndex, int positionOffset) {
final int tabStripChildCount = mTabStrip.getChildCount();
if (tabStripChildCount == 0 || tabIndex < 0 || tabIndex >= tabStripChildCount) {
return;
}
View selectedChild = mTabStrip.getChildAt(tabIndex);
if (selectedChild != null) {
int targetScrollX = selectedChild.getLeft() + positionOffset;
if (tabIndex > 0 || positionOffset > 0) {
// If we're not at the first child and are mid-scroll, make sure we obey the offset
targetScrollX -= mTitleOffset;
}
scrollTo(targetScrollX, 0);
}
}
private class InternalViewPagerListener implements ViewPager.OnPageChangeListener {
private int mScrollState;
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
int tabStripChildCount = mTabStrip.getChildCount();
if ((tabStripChildCount == 0) || (position < 0) || (position >= tabStripChildCount)) {
return;
}
mTabStrip.onViewPagerPageChanged(position, positionOffset);
View selectedTitle = mTabStrip.getChildAt(position);
int extraOffset = (selectedTitle != null)
? (int) (positionOffset * selectedTitle.getWidth())
: 0;
scrollToTab(position, extraOffset);
if (mViewPagerPageChangeListener != null) {
mViewPagerPageChangeListener.onPageScrolled(position, positionOffset,
positionOffsetPixels);
}
}
#Override
public void onPageScrollStateChanged(int state) {
mScrollState = state;
if (mViewPagerPageChangeListener != null) {
mViewPagerPageChangeListener.onPageScrollStateChanged(state);
}
}
#Override
public void onPageSelected(int position) {
if (mScrollState == ViewPager.SCROLL_STATE_IDLE) {
mTabStrip.onViewPagerPageChanged(position, 0f);
scrollToTab(position, 0);
}
for (int i = 0; i < mTabStrip.getChildCount(); i++) {
mTabStrip.getChildAt(i).setSelected(position == i);
}
if (mViewPagerPageChangeListener != null) {
mViewPagerPageChangeListener.onPageSelected(position);
}
}
}
private class TabClickListener implements OnClickListener {
#Override
public void onClick(View v) {
for (int i = 0; i < mTabStrip.getChildCount(); i++) {
if (v == mTabStrip.getChildAt(i)) {
mViewPager.setCurrentItem(i);
return;
}
}
}
}
}
MainActivity.java
public class MainActivityextends AppCompatActivity {
private ViewPager pager;
private ViewPagerAdapter adapter;
private SlidingTabLayout tabs;
private CharSequence Titles[]={"Tab_1","Tab_2"};
private int Numboftabs =2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Creating The ViewPagerAdapter and Passing Fragment Manager, Titles fot the Tabs and Number Of Tabs.
adapter = new ViewPagerAdapter(getSupportFragmentManager(),Titles,Numboftabs);
// Assigning ViewPager View and setting the adapter
pager = (ViewPager) findViewById(R.id.pager);
pager.setAdapter(adapter);
// Assiging the Sliding Tab Layout View
tabs = (SlidingTabLayout) findViewById(R.id.tabs);
tabs.setDistributeEvenly(true); // To make the Tabs Fixed set this true, This makes the tabs Space Evenly in Available width
// Setting Custom Color for the Scroll bar indicator of the Tab View
tabs.setCustomTabColorizer(new SlidingTabLayout.TabColorizer() {
#Override
public int getIndicatorColor(int position) {
return getResources().getColor(R.color.tabsScrollColor);
}
});
// Setting the ViewPager For the SlidingTabsLayout
tabs.setViewPager(pager);
}}
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.AndroidApp.ActivityPackage.MainActivity">
<com.AndroidApp.SlidingTab.SlidingTabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/tabColor"
android:elevation="2dp" />
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_height="0dp"
android:layout_width="match_parent"
android:layout_weight="1" />
</LinearLayout>
tab_1.xml
<?xml version="1.0" encoding="utf-8"?>
<ScrollView
android:id="#+id/srlview"
android:layout_height="match_parent"
android:layout_width="match_parent">
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:orientation="vertical"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<EditText
android:id="#+id/edt_empnum"
android:inputType="number"
android:layout_gravity="center"
android:hint="Enter Employee Number"
style="#style/spinner_style"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:padding="5dp" />
<EditText
android:id="#+id/edt_empname"
style="#style/spinner_style"
android:layout_gravity="center"
android:hint="Enter Name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:padding="5dp" />
<EditText
android:id="#+id/edt_empdob"
android:inputType="date"
style="#style/spinner_style"
android:layout_gravity="center"
android:hint="Enter Birthdate"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:padding="5dp" />
<Spinner
android:id="#+id/spinner_empType"
android:layout_gravity="center"
style="#style/spinner_style"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:padding="5dp"/>
<EditText
android:id="#+id/edt_empQuery"
style="#style/spinner_style"
android:inputType="textMultiLine"
android:lines="3"
android:minLines="3"
android:maxLines="8"
android:gravity="top|start"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:hint="Enter Query"
android:scrollbars="vertical"
android:layout_margin="5dp"
android:padding="5dp"/>
<EditText
android:id="#+id/edt_empcontact"
style="#style/spinner_style"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:layout_gravity="center"
android:inputType="number"
android:hint="Enter Contact Number"
android:padding="5dp" />
<EditText
android:id="#+id/edt_empemailid"
style="#style/spinner_style"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:layout_gravity="center"
android:inputType="number"
android:hint="Enter Email Id"
android:padding="5dp" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:orientation="horizontal"
android:layout_gravity="center_horizontal"
android:padding="5dp"
android:gravity="center">
<Button android:id="#+id/btn__emp_postQuery"
style="?android:textAppearanceSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:text="SUBMIT"
android:textStyle="bold"
android:textColor="#FFFFFF"
android:background="#color/colorPrimary"
android:layout_marginRight="10dp" />
<Button android:id="#+id/btn_corpempquery_emp_resetQuery"
style="?android:textAppearanceSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:text="RESET"
android:textStyle="bold"
android:textColor="#FFFFFF"
android:background="#color/colorPrimary"
android:layout_marginLeft="10dp" />
</LinearLayout>
</LinearLayout>
</ScrollView>
Tab_1.java
public class Tab_1 extends Fragment {
private View rootView;
public Tab_1()
{
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#TargetApi(Build.VERSION_CODES.JELLY_BEAN)
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.tab_1,container,false);
return rootView;
}
}
Tab_2.java and tab_2.xml are quite same as that of Tab_1 and tab_1 respectively.
Please help. Thank you.

Related

How to add a icon in Picker dropdown popup list using xamarin forms

We are using picker control our app. I want to customize the picker while clicking the dropdown popup list will be shown. In that popup, I want to display the left side icon with the text. How could be achieve using xamarin forms picker android and ios platform?
You could use CustomRenderer to achieve this.
Here is a sample:
Create a custom picker:
public class MyPicker : Picker
{
}
For Android:
Create a custom renderer in Android:
public class CustomPicker : PickerRenderer
{
private Dialog dialog;
protected override void OnElementChanged(ElementChangedEventArgs<Picker> e)
{
base.OnElementChanged(e);
Control.Click += Control_Click1;
}
protected override void Dispose(bool disposing)
{
Control.Click -= Control_Click1;
base.Dispose(disposing);
}
private void Control_Click1(object sender, EventArgs e)
{
//throw new NotImplementedException();
Picker model = Element;
dialog = new Dialog(Forms.Context);
dialog.SetContentView(Resource.Layout.custom_picker_dialog);
Android.Widget.ListView listView = (Android.Widget.ListView)dialog.FindViewById(Resource.Id.listview);
//listView.Adapter = new CustomPickerAdapter(((List<PickerModel>)model.ItemsSource), model.SelectedIndex);
listView.Adapter = new MyAdaptr((List<string>)model.ItemsSource);
listView.ItemClick += (object sender1, ItemClickEventArgs e1) =>
{
Element.SelectedIndex = e1.Position;
dialog.Hide();
};
if (model.ItemsSource.Count > 3)
{
var height = Xamarin.Forms.Application.Current.MainPage.Height;
var width = Xamarin.Forms.Application.Current.MainPage.Width;
dialog.Window.SetLayout(700, 800);
}
dialog.Show();
}
class MyAdaptr : BaseAdapter
{
private IList<string> mList;
public MyAdaptr(IList<string> itemsSource)
{
mList = itemsSource;
}
public override int Count => mList.Count;
public override Java.Lang.Object GetItem(int position)
{
return mList[position];
}
public override long GetItemId(int position)
{
return position;
}
public override Android.Views.View GetView(int position, Android.Views.View convertView, ViewGroup parent)
{
Android.Views.View view = convertView;
convertView = LayoutInflater.From(parent.Context).Inflate(Resource.Layout.celllayout, null); //here is the style you want to achieve
TextView text = convertView.FindViewById<TextView>(Resource.Id.textview1);
text.Text = mList[position];
return convertView;
}
}
}
custom_picker_dialog.axml:
<?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:gravity="center"
>
<TextView
android:text="Select One Option"
android:layout_width="200dp"
android:layout_height="25dp"
android:paddingLeft="25dp"
android:paddingRight="25dp"/>
<ListView
android:id="#+id/listview"
android:layout_gravity="center"
android:background="#drawable/abc_list_pressed_holo_light"
android:layout_width="match_parent"
android:dividerHeight="3dp"
android:layout_height="0dp"
android:layout_weight="1">
</ListView>
</LinearLayout>
celllayout.axml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center">
<ImageView
android:id="#+id/img"
android:src="xxx"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TextView
android:id="#+id/textview1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
/>
</LinearLayout>
For ios:
Create a custom renderer in ios
public class CustomPicker : PickerRenderer
{
List<string> itemList;
protected override void OnElementChanged(ElementChangedEventArgs<Picker> e)
{
base.OnElementChanged(e);
Picker myPicker = Element;
itemList = myPicker.Items.ToList();
UITextField textField = Control;
UIPickerView pickerView = textField.InputView as UIPickerView;
pickerView.Delegate = new MyPickerViewDelegate(itemList,Control);
textField.InputView = pickerView;
var toolbar = new UIToolbar(new CoreGraphics.CGRect(0, 0, UIScreen.MainScreen.Bounds.Size.Width , 1)) { BarStyle = UIBarStyle.Default, Translucent = true };
textField.InputAccessoryView = toolbar;
}
}
internal class MyPickerViewDelegate : UIPickerViewDelegate
{
private List<string> itemList;
private UITextField textField;
public MyPickerViewDelegate(List<string> itemList, UITextField control)
{
this.itemList = itemList;
this.textField = control;
}
//Define the Font size or style
public override NSAttributedString GetAttributedTitle(UIPickerView pickerView, nint row, nint component)
{
var text = new NSAttributedString(
itemList[(int)row],
font: UIFont.SystemFontOfSize(24),
foregroundColor: UIColor.Red,
strokeWidth: 4
);
return text;
}
//Define the row height
public override nfloat GetRowHeight(UIPickerView pickerView, nint component)
{
return 45;
}
//define the itemview in your listview,you could add a UIImage here for your scene
public override UIView GetView(UIPickerView pickerView, nint row, nint component, UIView view)
{
UIView contentView = new UIView(new CoreGraphics.CGRect(0, 0, UIScreen.MainScreen.Bounds.Size.Width, 45));
UILabel label = new UILabel();
label.Frame = contentView.Bounds;
contentView.AddSubview(label);
label.Text = itemList[(int)row];
return contentView;
}
public override void Selected(UIPickerView pickerView, nint row, nint component)
{
//base.Selected(pickerView, row, component);
textField.Text = itemList[(int)row];
textField.ResignFirstResponder();
}
}
Finally you could use in your page.xaml like:
<local:MyPicker x:Name="picker" Title="Select An option" />

How to update my item in listview in the same activity where i add item into listview

I have 2 buttons, add and edit. The add button works and item is added to listview and store in sqlite database. But my edit button do not work, when i press edit, there is no update to my item in the listview. I search googled but all of the code uses 2 activity or dialogue, which is not what i want. I want to add and edit in one same main activity.
This is my sqlite database
public class GetFitHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "restaurantlist.db";
private static final int SCHEMA_VERSION = 1;
public GetFitHelper(Context context) {
super(context, DATABASE_NAME, null, SCHEMA_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
// Will be called once when the database is not created
db.execSQL("CREATE TABLE food_table ( _id INTEGER PRIMARY KEY
AUTOINCREMENT, addFood TEXT, addCalories TEXT);");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int
newVersion) {
// Will not be called until SCHEMA_VERSION increases
// Here we can upgrade the database e.g. add more tables
}
/* Read all records from food_table */
public Cursor getAll() {
return (getReadableDatabase().rawQuery(
"SELECT _id, addFood, addCalories FROM food_table ORDER
BY addFood", null));
}
/* Read a particular record from food_table with id provided */
public Cursor getById(String id) {
String[] args = {id};
return (getReadableDatabase().rawQuery(
"SELECT _id, addFood, addCalories FROM food_table WHERE
_ID = ?", args));
}
/* Write a record into food_table */
public void insert(String addFood, String addCalories) {
ContentValues cv = new ContentValues();
cv.put("addFood", addFood);
cv.put("addCalories", addCalories);
getWritableDatabase().insert("food_table", "addFood", cv);
}
/* Update a particular record in food_table with id provided */
public void update(String id,String addFood, String addCalories) {
ContentValues cv = new ContentValues();
String[] args = {id};
cv.put("addFood", addFood);
cv.put("addCalories", addCalories);
getWritableDatabase().update("food_table", cv, " _ID = ?", args);
}
/* Read a record id value from food_table */
public String getID(Cursor c) {
return (c.getString(0));
}
public String getAddFood(Cursor c) {
return (c.getString(1));
}
public String getAddCalories(Cursor c) {
return (c.getString(2));
}
}
This is my edit button code
private View.OnClickListener onEdit = new View.OnClickListener() {
#Override
public void onClick(View v) {
String foodStr = addFood.getText().toString();
String caloriesStr = addCalories.getText().toString();
helper.update(foodID,foodStr,caloriesStr);
}
};
Here's a working example based upon assumptions about your other code.
The layout for the ListView (mylistview_item.xml in the example):-
<TextView
android:id="#+id/editfood"
android:layout_width="0dp"
android:layout_weight="3"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/editcalories"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content" />
<Button
android:id="#+id/edit"
android:layout_width="0dp"
android:layout_weight="2"
android:layout_height="wrap_content"
android:text="UPDATE"
android:onClick="onclick"/>
<TextView
android:id="#+id/cheat"
android:layout_width="0dp"
android:layout_weight="0"
android:layout_height="wrap_content"
android:visibility="gone"/>
Note the TextView for the id (hidden) called cheat (not really a cheat but it's a work around using a CursorAdapter).
Note the onCLick="onclick" for the Button.
Otherwise it is assumed that this is similar to what you have.
GetFitHelper.java is unchanged.
The layout for the activity activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
<EditText
android:id="#+id/editfood"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="New Food Name"/>
<EditText
android:id="#+id/editcalories"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="number"/>
<ListView
android:id="#+id/mylistview"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</ListView>
</LinearLayout>
The invoking activity, in this case MainActivity.java
public class MainActivity extends AppCompatActivity {
GetFitHelper helper;
EditText addFood,addCalories;
ListView mylistview;
Cursor mCsr;
SimpleCursorAdapter mSCA;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addFood = this.findViewById(R.id.editfood);
addCalories = this.findViewById(R.id.editcalories);
mylistview = this.findViewById(R.id.mylistview);
helper = new GetFitHelper(this);
addSomeDataIfNone();
manageListView();
}
private void addSomeDataIfNone() {
if(DatabaseUtils.queryNumEntries(helper.getWritableDatabase(),"food_table") > 0) return;
helper.insert("Food1","100");
helper.insert("Food2","150");
helper.insert("Food2","300");
}
private void manageListView() {
mCsr = helper.getAll();
if (mSCA == null) {
mSCA = new SimpleCursorAdapter(
this,
R.layout.mylistview_item,mCsr,
new String[]{"addFood","addCalories","_id"},
new int[]{R.id.editfood,R.id.editcalories,R.id.cheat},
0
);
mylistview.setAdapter(mSCA);
} else {
mSCA.swapCursor(mCsr);
}
}
public void onclick(View v) {
String foodStr = addFood.getText().toString();
String caloriesStr = addCalories.getText().toString();
TextView editbtn = ((View) v.getParent()).findViewById(R.id.cheat);
String foodID = editbtn.getText().toString();
Log.d("ONCLCKUPDT","You clicked FoodID = " + String.valueOf(foodID) + "FoodStr = " + foodStr + " caloriesStr = " + caloriesStr);
helper.update(foodID,foodStr,caloriesStr);
}
}
The crux of the fix is the cheat TextView which has the _id column's value for the respective row. This being extracted from the TextView by getting the TextView from the parent View (The LinearLayout) using findViewById.
Result
When the App is first run then it is :-
After Entering MyNewFood2 and 1500 and then clicking button for Food2 then :-
The log includes the line :-
D/ONCLCKUPDT: You clicked FoodID = 2FoodStr = MyNewFood2 caloriesStr = 1500

Working with fragments - findViewById returns NULL on Button in Android

I've started dealing with Fragments in Android. I created Activity with NavigationView which has 3 items and worked with 3 simple fragments till now. NavigationHeader has 2 buttons - 1 starts LoginActivity and 2nd RegisterActivity. I remind that everything till niw worked fine. Today I've tried to create RecyclerView inside one of the fragments. Now when I try to run app, findViewById applied to those 2 NavigationHeader buttons returns NULL. I have no idea why.
Here is HomeActivity:
public class HomeActivity extends AppCompatActivity {
private static final String FRAGMENT_POSITION = "fragment_position"; // Fragment Position
private DrawerLayout mDrawerLayout; // NavigationDrawer Layout
private NavigationView nvDrawer; // NavigationView
private CoordinatorLayout homeCoordinatorLayout; // Coordinator Layout For Snackbar
private Toolbar toolbar; // Application Toolbar
private TextView navHeaderNamePlusSurname; // Name And Surname Navigation Header Text
private TextView navHeaderEmail; // E-mail Navigation Header Text
AppCompatButton navHeaderButtonLogin; // Login/Logout Button
AppCompatButton navHeaderButtonRegister; // Register Button
private ActionBarDrawerToggle mDrawerToggle; // ActionBar Drawer Toggle
private SQLiteHandler db; // SQLite Database Helper Class
private SessionManager session; // Session Manager
private int lastShownFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
// Setting Toolbar
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
// Setting Up DrawerLayout
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerToggle = setupDrawerToggle();
mDrawerLayout.setDrawerListener(mDrawerToggle);
// Navigation Header Logout Button
navHeaderButtonLogin = (AppCompatButton) findViewById(R.id.nav_header_btn_log_in_out);
navHeaderButtonRegister = (AppCompatButton) findViewById(R.id.nav_header_btn_register);
Log.d("czy_null", "navHeaderButtonLogin: " + navHeaderButtonLogin + ", navHeaderButtonRegister: " + navHeaderButtonRegister);
// Name, Surname And E-mail Texts
navHeaderNamePlusSurname = (TextView) findViewById(R.id.nav_header_name_plus_surname);
navHeaderEmail = (TextView) findViewById(R.id.nav_header_email);
// SQLite Database Handler
db = new SQLiteHandler(getApplicationContext());
// Session Manager
session = new SessionManager(getApplicationContext());
// Navigation Drawer
nvDrawer = (NavigationView) findViewById(R.id.navigation_view);
// Checking If User Is Logged In
if (!session.isLoggedIn()) {
hideNavigationViewGroup(nvDrawer); // Hiding NavigationView Group Depending
// If Not Logged
} else {
navHeaderButtonLogin.setText(getText(R.string.home_btn_log_out));
navHeaderButtonRegister.setVisibility(View.INVISIBLE);
// Fetching User Details From SQLite
HashMap<String, String> user = db.getUserDetails();
String name = user.get(SQLiteHandler.KEY_NAME);
String surname = user.get(SQLiteHandler.KEY_SURNAME);
String email = user.get(SQLiteHandler.KEY_EMAIL);
// Setting Navigation Header Texts
String nameSurname = name + " " + surname;
navHeaderNamePlusSurname.setText(nameSurname);
navHeaderEmail.setText(email);
}
// Setting Up CoordinatorLayout
homeCoordinatorLayout = (CoordinatorLayout) findViewById(R.id.home_coordinator_layout);
// Setting Listener To NavigationView
setupDrawerContent(nvDrawer);
// Setting Starting Fragment
if (savedInstanceState == null) {
setStartingFragment();
} else {
restoreOnInstanceState(savedInstanceState.getInt(FRAGMENT_POSITION));
}
// Applying Login/Logout Button Listener
setLoginButtonListener();
// Applying Register Button Listener
setRegisterButtonListener();
}
// Listener To Login/Register Button
private void setLoginButtonListener() {
navHeaderButtonLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!session.isLoggedIn()) {
mDrawerLayout.closeDrawers();
Intent intent = new Intent(getApplicationContext(), LoginActivity.class);
startActivity(intent);
} else {
mDrawerLayout.closeDrawers();
logoutUser();
navHeaderNamePlusSurname.setText(getString(R.string.nav_header_name_surname));
navHeaderEmail.setText(getString(R.string.nav_header_email));
hideNavigationViewGroup(nvDrawer);
navHeaderButtonLogin.setText(getString(R.string.home_btn_log_in));
navHeaderButtonRegister.setVisibility(View.VISIBLE);
showSnackbarInfo(getString(R.string.inf_logout_success),
R.color.snackbar_success_msg);
}
}
});
}
// Listener To Register Button
private void setRegisterButtonListener() {
navHeaderButtonRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mDrawerLayout.closeDrawers();
Intent intent = new Intent(getApplicationContext(), SignUpActivity.class);
startActivity(intent);
}
});
}
// Logging Out The User
private void logoutUser() {
session.setLogin(false);
db.deleteUsers();
}
// Setting Up DrawerToggle
private ActionBarDrawerToggle setupDrawerToggle() {
return new ActionBarDrawerToggle(this, mDrawerLayout, toolbar, R.string.drawer_open,
R.string.drawer_close);
}
// Setting Up Drawer Content
private void setupDrawerContent(NavigationView navigationView) {
navigationView.setNavigationItemSelectedListener(
new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
selectDrawerItem(menuItem);
return true;
}
});
}
// Replace Existing Fragment With a New One
public void selectDrawerItem(MenuItem menuItem) {
Fragment fragment = null;
Class fragmentClass = null;
switch(menuItem.getItemId()) {
case R.id.nav_top20_recipes: {
fragmentClass = Top20RecipesFragment.class;
lastShownFragment = 0;
break;
}
case R.id.nav_kitchen_type: {
fragmentClass = KitchenTypeFragment.class;
lastShownFragment = 1;
break;
}
case R.id.nav_meal_type: {
fragmentClass = MealTypeFragment.class;
lastShownFragment = 2;
break;
}
}
try {
fragment = (Fragment) fragmentClass.newInstance();
} catch (Exception e) {
e.printStackTrace();
}
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.frame_layout_content, fragment);
fragmentTransaction.commit();
menuItem.setChecked(true); // Highlight The Selected Item
setTitle(menuItem.getTitle()); // Updating Toolbar Title
mDrawerLayout.closeDrawers(); // Close The Drawer
}
// Function Setting First Fragment
private void setStartingFragment() {
Fragment fragment = null;
Class fragmentClass = Top20RecipesFragment.class;
try {
fragment = (Fragment) fragmentClass.newInstance();
} catch (Exception e) {
e.printStackTrace();
}
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.frame_layout_content, fragment);
fragmentTransaction.commit();
lastShownFragment = 0;
MenuItem menuItem = nvDrawer.getMenu().getItem(0);
menuItem.setChecked(true); // Highlight The Selected Item
setTitle(menuItem.getTitle()); // Updating Toolbar Title
}
// Saving Fragment Title State
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(FRAGMENT_POSITION, lastShownFragment);
}
// Restoring Fragment Title States
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
restoreOnInstanceState(savedInstanceState.getInt(FRAGMENT_POSITION));
}
// Restoring Selected Item On Screen Rotation Or App Minimalize
private void restoreOnInstanceState(int lastPosition) {
Fragment fragment = null;
Class fragmentClass = null;
switch (lastShownFragment) {
case 0: {
fragmentClass = Top20RecipesFragment.class;
break;
}
case 1: {
fragmentClass = KitchenTypeFragment.class;
break;
}
case 2: {
fragmentClass = MealTypeFragment.class;
break;
}
}
try {
fragment = (Fragment) fragmentClass.newInstance();
} catch (Exception e) {
e.printStackTrace();
}
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.frame_layout_content, fragment);
fragmentTransaction.commit();
lastShownFragment = lastPosition;
MenuItem menuItem = nvDrawer.getMenu().getItem(lastPosition);
menuItem.setChecked(true); // Highlight The Selected Item
setTitle(menuItem.getTitle());
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
// Function Hiding Items In NavigationView
private void hideNavigationViewGroup(NavigationView nvDrawer) {
nvDrawer.getMenu().setGroupVisible(R.id.nav_group_logged_user, false);
}
// Function Showing Snakcbar
private void showSnackbarInfo(String info, int textColor) {
Snackbar snackbar = Snackbar.make(homeCoordinatorLayout, info, Snackbar.LENGTH_LONG);
View sbView = snackbar.getView();
TextView sbText = (TextView) sbView.findViewById(android.support.design.R.id.snackbar_text);
sbText.setTextColor(ContextCompat.getColor(getApplicationContext(), textColor));
snackbar.show();
}
}
Here is my fragment which has to contain RacyclerView:
public class KitchenTypeFragment extends Fragment {
RecyclerView kitchenTypeRecycleView;
private ArrayList<KitchenTypeItem> kitchenTypeItems;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
kitchenTypeItems = new ArrayList<>();
fillKitchenTypeArray(kitchenTypeItems);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_kitchen_type, container, false);
return rootView;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
kitchenTypeRecycleView = (RecyclerView) view.findViewById(R.id.kitchen_type_recycle_view);
kitchenTypeRecycleView.setHasFixedSize(true);
kitchenTypeRecycleView.setAdapter(new KitchenTypeAdapter(kitchenTypeItems,
R.layout.kitchen_type_grid_item));
kitchenTypeRecycleView.setLayoutManager(new GridLayoutManager(getContext(), 2));
kitchenTypeRecycleView.setItemAnimator(new DefaultItemAnimator());
}
private void fillKitchenTypeArray( ArrayList<KitchenTypeItem> kitchenTypeItems) {
KitchenTypeItem kitchenItem;
// Currently 8 Kitchen Types
String[] itemNames = getResources().getStringArray(R.array.kitchen_types);
// Filling ArrayList
for(int i = 0; i < itemNames.length; i++) {
kitchenItem = new KitchenTypeItem(itemNames[i], R.drawable.example_kitchen_type);
kitchenTypeItems.add(kitchenItem);
}
}
}
Here is XML from HomeActivity:
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/home_coordinator_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".RegisterActivity">
<android.support.v4.widget.DrawerLayout
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/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context=".SignUpActivity">
<!-- This LinearLayout represents the contents of the screen -->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<!-- The ActionBar displayed at the top -->
<include
android:id="#+id/toolbar"
layout="#layout/tool_bar"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<!-- The main content view where fragments are loaded -->
<FrameLayout
android:id="#+id/frame_layout_content"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
<!-- The navigation drawer that comes from the left -->
<!-- Note that `android:layout_gravity` needs to be set to 'start' -->
<android.support.design.widget.NavigationView
android:id="#+id/navigation_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
app:menu="#menu/drawer_view"
app:headerLayout="#layout/nav_header" />
</android.support.v4.widget.DrawerLayout>
</android.support.design.widget.CoordinatorLayout>
Here is NavigationHeader XML with those 2 buttons:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
android:id="#+id/relative_nav_header"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="192dp"
android:background="#color/primary"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:paddingBottom="16dp"
android:paddingTop="40dp"
android:theme="#style/ThemeOverlay.AppCompat.Dark"
android:orientation="vertical">
<!-- Name + Surname, E-mail -->
<LinearLayout
android:id="#+id/nav_lin_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center|left"
android:orientation="vertical">
<!-- Name + Surname Text -->
<TextView
android:id="#+id/nav_header_name_plus_surname"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="sans-serif-medium"
android:textSize="17sp"
android:text="#string/nav_header_name_surname" />
<!-- E-mail Adress -->
<TextView
android:id="#+id/nav_header_email"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#color/accent"
android:fontFamily="sans-serif"
android:textSize="13sp"
android:text="#string/nav_header_email" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_marginTop="7dp"
android:gravity="center|left"
android:layout_below="#+id/nav_lin_layout">
<!-- Login/Logut Button -->
<android.support.v7.widget.AppCompatButton
android:id="#+id/nav_header_btn_log_in_out"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="12dp"
android:backgroundTint="#color/nav_header_login_color"
android:textColor="#color/text_icons"
android:stateListAnimator="#null"
android:text="#string/btn_log_in" />
<android.support.v7.widget.AppCompatButton
android:id="#+id/nav_header_btn_register"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="12dp"
android:backgroundTint="#color/nav_header_register_color"
android:stateListAnimator="#null"
android:textColor="#color/text_icons"
android:text="#string/btn_sign_up" />
</LinearLayout>
</RelativeLayout>
And here is finally XML from Fragment:
<FrameLayout
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:id="#+id/kitchen_type_fragment"
android:padding="16dp"
tools:context="com.example.nazwamarki.myapplication.fragments.KitchenTypeFragment">
<android.support.v7.widget.RecyclerView
android:id="#+id/kitchen_type_recycle_view"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</FrameLayout>
You should use findViewById on the headerView like this:
navigationView.getHeaderView(0).findViewById()

Replace one fragment to another fragment in the swipable TabHost

I have an activity extending fragment activity and swipable tab view. In tab view i have used fragment and Tabs pager adapter to call fragments according to the tab position.
Now i want to replace these fragment using on click items with another fragment and on back press i want the original fragment back...
But when i am clicking on the items..it do nothing...
What should i do..pls help me ...
Thanks in advance
here is my code-
This is my Homeactivity which has tab
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.home_screen);
ressources = getResources();
mViewPager = (ViewPager) findViewById(R.id.viewpager);
// Tab Initialization
initialiseTabHost();
mAdapter = new TabsPagerAdapter(getSupportFragmentManager());
// Fragments and ViewPager Initialization
mViewPager.setAdapter(mAdapter);
mViewPager.setOnPageChangeListener(HomeScreen.this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}
// Method to add a TabHost
private static void AddTab(HomeScreen activity, TabHost tabHost,
TabHost.TabSpec tabSpec) {
tabSpec.setContent(new MyTabFactory(activity));
tabHost.addTab(tabSpec);
}
// Manages the Tab changes, synchronizing it with Pages
public void onTabChanged(String tag) {
int pos = this.mTabHost.getCurrentTab();
this.mViewPager.setCurrentItem(pos);
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
// Manages the Page changes, synchronizing it with Tabs
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
int pos = this.mViewPager.getCurrentItem();
this.mTabHost.setCurrentTab(pos);
}
#Override
public void onPageSelected(int arg0) {
}
// Tabs Creation
private void initialiseTabHost() {
mTabHost = (TabHost) findViewById(android.R.id.tabhost);
mTabHost.setup();
// TODO Put here your Tabs
HomeScreen.AddTab(
this,
this.mTabHost,
this.mTabHost.newTabSpec(Button_tab).setIndicator("",
ressources.getDrawable(R.drawable.menu)));
HomeScreen.AddTab(this, this.mTabHost,
this.mTabHost.newTabSpec(Image_tab).setIndicator("",ressources.getDrawable(R.drawable.jobs)));
HomeScreen.AddTab(this, this.mTabHost,
this.mTabHost.newTabSpec(Text_tab).setIndicator("",ressources.getDrawable(R.drawable.people)));
HomeScreen.AddTab(this, this.mTabHost,
this.mTabHost.newTabSpec("line_tab").setIndicator("",ressources.getDrawable(R.drawable.calenders)));
mTabHost.setOnTabChangedListener(this);
}
#Override
public void onBackPressed() {
boolean isPopFragment = false;
String currentTabTag = mTabHost.getCurrentTabTag();
if (currentTabTag.equals(Button_tab)) {
isPopFragment = ((BaseContainerFragment)getSupportFragmentManager().findFragmentByTag(Button_tab)).popFragment();
} else if (currentTabTag.equals(Image_tab)) {
isPopFragment = ((BaseContainerFragment)getSupportFragmentManager().findFragmentByTag(Image_tab)).popFragment();
} else if (currentTabTag.equals(Text_tab)) {
isPopFragment = ((BaseContainerFragment)getSupportFragmentManager().findFragmentByTag(Text_tab)).popFragment();
} else if (currentTabTag.equals(line_tab)) {
isPopFragment = ((BaseContainerFragment)getSupportFragmentManager().findFragmentByTag(line_tab)).popFragment();
}
if (!isPopFragment) {
finish();
}
}
My XMl for HomeActivity:
<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=".HomeScreen" >
<RelativeLayout
android:id="#+id/header"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginTop="10dp"
android:orientation="horizontal" >
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:src="#drawable/krma" />
<Button
android:layout_width="30dp"
android:layout_marginTop="3dp"
android:layout_height="30dp"
android:layout_marginRight="10dp"
android:layout_alignParentRight="true"
android:background="#drawable/listmenu" />
</RelativeLayout>
<TabHost
android:id="#android:id/tabhost"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:orientation="vertical" >
<TabWidget
android:id="#android:id/tabs"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:layout_weight="0"
android:background="#FF7519"
android:orientation="horizontal" />
<FrameLayout
android:id="#android:id/tabcontent"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_weight="0" />
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom" />
</LinearLayout>
</TabHost>
</RelativeLayout>
My TabsPagerAdapter is :
public class TabsPagerAdapter extends FragmentPagerAdapter {
public TabsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int index) {
switch (index) {
case 0:
return new Menu();
case 1:
return new Jobs();
case 2:
return new Applicant();
case 3:
return new Admin();
}
return null;
}
#Override
public int getCount() {
// get item count - equal to number of tabs
return 4;
}
}
my Job fragment is :
public class Jobs extends BaseContainerFragment implements OnItemClickListener {
ListView listView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_job, container,
false);
listView = (ListView) rootView.findViewById(R.id.list);
SharedPreferences sharedpreferences = getActivity()
.getSharedPreferences(LoginScreen.MyPREFERENCES,
Context.MODE_PRIVATE);
String loggedInEmail = sharedpreferences.getString("nameKey", "");
// String loggedInEmail="aditya.pratap#krmaa.com";
RestClient client = new RestClient(
"http://122.180.4.83:8080/krmaa/krmaa/joblist/" + loggedInEmail
+ "/1234");
client.AddHeader("GData-Version", "2");
try {
client.Execute(RequestMethod.GET);
} catch (Exception e) {
e.printStackTrace();
}
String response = client.getResponse();
Gson gson = new Gson();
String convertedStr = response.replace("\\\"", "\"");
String finalJson = convertedStr.substring(1, convertedStr.length() - 2);
JobDTO[] jobDTOList = gson.fromJson(finalJson, JobDTO[].class);
ItemAdapter adapter = new ItemAdapter(getActivity()
.getApplicationContext(), jobDTOList);
// Attach the adapter to a ListView
ListView listView = (ListView) rootView.findViewById(R.id.list);
listView.setAdapter(adapter);
// return list of jobDTO and iterate in view page.
return rootView;
}
public class JobDTOList {
List<JobDTO> jobDTOList;
public List<JobDTO> getJobDTOList() {
return jobDTOList;
}
public void setJobDTOList(List<JobDTO> jobDTOList) {
this.jobDTOList = jobDTOList;
}
}
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// Here I want to switch from 1st Tab(Fragment1) to 2nd Tab(Fragment2)
// How can I switch from 1st tab to 2nd tab here???
// Below code is not worked for me.
fragment2 fr = new fragment2();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.replace(R.id.job,fr);
transaction.commit();
}
}
My xml for Job fragment is :
<?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:id="#+id/job"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_alignParentTop="true"
android:orientation="horizontal" >
<TextView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_weight="6"
android:background="#A3A385"
android:paddingBottom="10dp"
android:paddingLeft="10dp"
android:paddingTop="10dp"
android:text="Jobs"
android:textColor="#000000"
android:textSize="10pt" />
<Button
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_marginLeft="5dp"
android:layout_weight="1"
android:background="#A3A385"
android:text="Filter"`enter code here`
android:onClick="frag"
android:textSize="10pt" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >`enter code here`
<ListView`enter code here`
android:id="#+id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
>
</ListView>
</LinearLayout>
</LinearLayout>

Customizing the fonts?

How to customize the ttf fonts on tab fragments? I am using sherlockactionbar.
Here is my code,
<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:id="#+id/pager"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true" />
<FrameLayout
android:id="#+id/ptr_fragment"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</FrameLayout>
And in Main activity am using,
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/** to check whether user logged in or not */
session = new TwitterHomeActivity(getApplicationContext());
session.checklogin();
/** Getting a reference to action bar of this activity */
mActionBar = getSupportActionBar();
getSupportActionBar().setDisplayUseLogoEnabled(false);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
mActionBar.setDisplayOptions(0, ActionBar.DISPLAY_USE_LOGO);
/** Set tab navigation mode */
mActionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
/** Getting a reference to ViewPager from the layout */
mPager = (ViewPager) findViewById(R.id.pager);
/** Getting a reference to FragmentManager */
FragmentManager fm = getSupportFragmentManager();
/** Defining a listener for pageChange */
ViewPager.SimpleOnPageChangeListener pageChangeListener = new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
super.onPageSelected(position);
setTitle(getTitleFromPosition(position));
mActionBar.setSelectedNavigationItem(position);
// mActionBar.setBackgroundDrawable(R.drawable.ic_action_chance_icon);
}
private CharSequence getTitleFromPosition(int position) {
if (position == 0) {
title = "text";
} else if (position == 1) {
title = "text";
} else if (position == 2) {
title = "text";
} else if (position == 3) {
title = "text";
}
return title;
}
};
/** Setting the pageChange listner to the viewPager */
mPager.setOnPageChangeListener(pageChangeListener);
/** Creating an instance of FragmentPagerAdapter */
MyFragmentPagerAdapter fragmentPagerAdapter = new MyFragmentPagerAdapter(
fm);
/** Setting the FragmentPagerAdapter object to the viewPager object */
mPager.setAdapter(fragmentPagerAdapter);
mActionBar.setDisplayShowTitleEnabled(true);
/** Defining tab listener */
ActionBar.TabListener tabListener = new ActionBar.TabListener() {
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
mPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
}
};
/**/
Tab tab = mActionBar.newTab();
tab = mActionBar.newTab();
tab.setText(“text”);
tab.setTabListener(tabListener);
mActionBar.addTab(tab);
tab = mActionBar.newTab();
tab.setText(“ttext”);
tab.setTabListener(tabListener);
mActionBar.addTab(tab);
tab = mActionBar.newTab();
tab.setText(“text”);
tab.setTabListener(tabListener);
mActionBar.addTab(tab);
tab = mActionBar.newTab();
tab.setText(“text”);
tab.setTabListener(tabListener);
mActionBar.addTab(tab);
try {
ViewConfiguration config = ViewConfiguration.get(this);
Field menuKeyField = ViewConfiguration.class
.getDeclaredField("sHasPermanentMenuKey");
if (menuKeyField != null) {
menuKeyField.setAccessible(true);
menuKeyField.setBoolean(config, false);
}
} catch (Exception ex) {
// Ignore
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getSupportMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.camera:
startActivity(new Intent(MainActivity.this, Request_Broadcast.class));
overridePendingTransition(R.anim.right_slide_in,
R.anim.right_slide_out);
return true;
case R.id.find_people:
startActivity(new Intent(MainActivity.this, Find_people.class));
overridePendingTransition(R.anim.right_slide_in,
R.anim.right_slide_out);
return true;
case R.id.action_settings:
startActivity(new Intent(MainActivity.this, Pro_settings.class));
overridePendingTransition(R.anim.right_slide_in,
R.anim.right_slide_out);
return true;
}
return true;
}
#SuppressLint("NewApi")
public void setActionBarTitle(int feedPage) {
getActionBar().setTitle(feedPage);
}
#Override
public void onPageScrollStateChanged(int arg0) {
// TODO Auto-generated method stub
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
// TODO Auto-generated method stub
}
#Override
public void onPageSelected(int arg0) {
}
}
Now i want to customize the fonts on tab using typeface. How to do that and the text on tabs is displaying in uppercase letters. I want to display that in lowercase letters..
Here you have an efficent way to change the font for the entire application: Access a typeface once from asset and use it as a reference
EDIT
You can use the source code of the class I refer you to the link above. Now what you can do is change the font recursively starting from the parent layout and descending for each of their children. You should be aware that any view that can contain text is directly or indirectly a subclass of the TextView class (ie Button, EditText, CheckBox, CompoundButton, RadioButton, ToggleButton, etc). If you want to use different fonts in your application you can use for example the tag property of the view to define the font that will have that particular view. An example layout would look like this:
activity_main.xml
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:tag="title"
android:text="This is the title screen" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:tag="content"
android:text="This is the activity content." />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:tag="content"
android:text="This is a button" />
Below this is the recursive method through which you can change the font of all views of the activity. This method is an additional method defined in class FontUtils:
public static void setActivityTypeFace(Context context, ViewGroup viewGroup) {
Object tagAux;
for (int i = 0; i < viewGroup.getChildCount(); i++) {
View viewChild = viewGroup.getChildAt(i);
if (viewChild instanceof ViewGroup) {
setActivityTypeFace(context, (ViewGroup) viewChild);
} else if (viewChild instanceof TextView) {
tagAux = viewChild.getTag();
if (tagAux != null) {
if (((String) tagAux).compareTo("title") == 0)
{
((TextView) viewChild).setTypeface(getTypeface(context,
FontType.TITLE_FONT.toString()));
}
} else if (((String) tagAux).compareTo("content") == 0) {
((TextView) viewChild).setTypeface(getTypeface(context,
FontType.CONTENT_FONT.toString()));
}
}
}
}
MainActivity.java
public class MainActivity extends Activity
private ViewGroup mRootView;
...
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mRootView = (ViewGroup) findViewById(R.id.rootView);
...
FontUtil.setActivityTypeFace(this, mRootView);
}
}

Resources