Android Fragments showing irregular behavior - android

I have multiple fragments in my Activity. It should initiate only first fragment at start up. It initializes the second one also. More over I move from one fragment to the other though a swipe action. When I swipe from first fragment to the next, third in the row is also initiated.
I have to get data from the server and then populate that fragment. Network request is sent but not for the one for which I am sending but for the fragment next to it.
Please suggest me where I am mistaken...
Thanks in advance.
Following is the code:
Note: Sample code is being used, Please consider the other fragments and their layouts as the same as that for Fragment1.
Main Activity
package com.example.fragments;
import java.util.List;
import java.util.Vector;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.HorizontalScrollView;
import android.widget.TableLayout;
import android.widget.TextView;
public class MainActivity extends FragmentActivity implements OnClickListener {
/**
* Constants for tabs
*/
public static final int TAB_SCORES = 0;
public static final int TAB_PAVILION = 1;
public static final int TAB_FRIENDS = 2;
public static final int TAB_OTHER = 3;
public static final int TAB_CROWD = 4;
public static final int TAB_SOCIAL = 5;
private List<Fragment> fragments=null;
private FragmentsAdaptor _adapter;
/** The context object. */
public static Object contextObject = null;
private TableLayout scoresTab, socialTab, pavilionTab, friendsTab, othersTab, crowdTab;
private TextView mScoresTv, mPavilionTv, mFriendsTv, mOtherTv, mCrowdTv, mSocialTv;
private HorizontalScrollView tabsLayout;
private int fragmentPosition;
public ViewPager mViewPager;
private int moveRight = 100;
#Override
protected void onStart() {
super.onStart();
}
/**
/* (non-Javadoc)
* #see android.app.Activity#onCreate(android.os.Bundle)
*/
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.activity_main);
this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
mViewPager = (ViewPager)findViewById(R.id.viewPager);
setViews();
addListeners();
setTab();
addFragments();
}
private void setViews() {
scoresTab = (TableLayout)findViewById(R.id.scores_tab);
pavilionTab = (TableLayout)findViewById(R.id.pavilion_tab);
friendsTab = (TableLayout)findViewById(R.id.friends_tab);
othersTab = (TableLayout)findViewById(R.id.others_tab);
crowdTab = ((TableLayout)findViewById(R.id.crowd_tab));
socialTab = (TableLayout)findViewById(R.id.social_tab);
tabsLayout = (HorizontalScrollView)findViewById(R.id.tabs_layout);
mScoresTv = (TextView)findViewById(R.id.scores);
mPavilionTv = (TextView)findViewById(R.id.pavilion);
mFriendsTv = (TextView)findViewById(R.id.friends);
mOtherTv = (TextView)findViewById(R.id.other);
mCrowdTv = (TextView)findViewById(R.id.crowd);
mSocialTv = (TextView)findViewById(R.id.social);
}
private void addListeners() {
mScoresTv.setOnClickListener(MainActivity.this);
mPavilionTv.setOnClickListener(MainActivity.this);
mFriendsTv.setOnClickListener(MainActivity.this);
mOtherTv.setOnClickListener(MainActivity.this);
mCrowdTv.setOnClickListener(MainActivity.this);
mSocialTv.setOnClickListener(MainActivity.this);
}
private void addFragments(){
fragments = new Vector<Fragment>();
fragments.add(new Fragment1(this));
fragments.add(new Fragment2(this));
fragments.add(new Fragment3(this));
fragments.add(new Fragment4(this));
fragments.add(new Fragment5(this));
fragments.add(new Fragment6(this));
this._adapter = new FragmentsAdaptor(super.getSupportFragmentManager(), fragments);
mViewPager.setAdapter(this._adapter);
}
#Override
public void onClick(View v){
onTabsClick(v);
}
public void onTabsClick(View v) {
//reset layout of all the text views
resetlayouts();
if(v == mScoresTv) {
if(mViewPager.getCurrentItem() != TAB_SCORES) {
changeTab(TAB_SCORES);
scoresTab.setBackgroundColor(getResources().getColor(android.R.color.black));
mScoresTv.setTextColor(getResources().getColor(android.R.color.white));
}
} else if(v == mCrowdTv) {
if(mViewPager.getCurrentItem() != TAB_CROWD) {
changeTab(TAB_CROWD);
crowdTab.setBackgroundColor(getResources().getColor(android.R.color.black));
mCrowdTv.setTextColor(getResources().getColor(android.R.color.white));
}
} else if(v == mFriendsTv) {
if(mViewPager.getCurrentItem() != TAB_FRIENDS) {
changeTab(TAB_FRIENDS);
friendsTab.setBackgroundColor(getResources().getColor(android.R.color.black));
mFriendsTv.setTextColor(getResources().getColor(android.R.color.white));
}
} else if(v == mOtherTv) {
if(mViewPager.getCurrentItem() != TAB_OTHER) {
changeTab(TAB_OTHER);
othersTab.setBackgroundColor(getResources().getColor(android.R.color.black));
mOtherTv.setTextColor(getResources().getColor(android.R.color.white));
}
} else if(v == mPavilionTv) {
if(mViewPager.getCurrentItem() != TAB_PAVILION) {
changeTab(TAB_PAVILION);
pavilionTab.setBackgroundColor(getResources().getColor(android.R.color.black));
mPavilionTv.setTextColor(getResources().getColor(android.R.color.white));
}
} else if(v == mSocialTv) {
if(mViewPager.getCurrentItem() != TAB_SOCIAL) {
changeTab(TAB_SOCIAL);
socialTab.setBackgroundColor(getResources().getColor(android.R.color.black));
mSocialTv.setTextColor(getResources().getColor(android.R.color.white));
}
}
}
private void changeTab(int tabType) {
mViewPager.setCurrentItem(tabType);
System.out.println("tab to change to: " + tabType);
}
private void resetlayouts(){
scoresTab.setBackgroundColor(getResources().getColor(android.R.color.transparent));
pavilionTab.setBackgroundColor(getResources().getColor(android.R.color.transparent));
friendsTab.setBackgroundColor(getResources().getColor(android.R.color.transparent));
othersTab.setBackgroundColor(getResources().getColor(android.R.color.transparent));
crowdTab.setBackgroundColor(getResources().getColor(android.R.color.transparent));
socialTab.setBackgroundColor(getResources().getColor(android.R.color.transparent));
mScoresTv.setTextColor(getResources().getColor(android.R.color.black));
mPavilionTv.setTextColor(getResources().getColor(android.R.color.black));
mFriendsTv.setTextColor(getResources().getColor(android.R.color.black));
mOtherTv.setTextColor(getResources().getColor(android.R.color.black));
mCrowdTv.setTextColor(getResources().getColor(android.R.color.black));
mSocialTv.setTextColor(getResources().getColor(android.R.color.black));
}
private void setTab() {
mViewPager.setOnPageChangeListener(new OnPageChangeListener() {
#Override
public void onPageScrollStateChanged(int position) { }
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) { }
#Override
public void onPageSelected(int position) {
System.out.println("setTab:::::::::::::::::::::::::::::::::::" + position);
int previousFragment = fragmentPosition;
if(previousFragment < position ) {
tabsLayout.scrollTo(tabsLayout.getScrollX() + moveRight*fragmentPosition, tabsLayout.getScrollY());
tabsLayout.requestLayout();
}
if(previousFragment > position ) {
tabsLayout.scrollTo(tabsLayout.getScrollX() - moveRight*fragmentPosition, tabsLayout.getScrollY());
tabsLayout.requestLayout();
}
fragmentPosition = position;
resetlayouts();
System.out.println("In on tab change listener!");
switch(position) {
case TAB_SCORES:
System.out.println("scores");
scoresTab.setBackgroundColor(getResources().getColor(android.R.color.black));
mScoresTv.setTextColor(getResources().getColor(android.R.color.white));
//give a call to netmanager and repaint livescorescreen on the basis of selected fragment
break;
case TAB_PAVILION:{
System.out.println("pavilion");
pavilionTab.setBackgroundColor(getResources().getColor(android.R.color.black));
mPavilionTv.setTextColor(getResources().getColor(android.R.color.white));
//give a call to netmanager and repaint livescorescreen on the basis of selected fragment
break;
}
case TAB_FRIENDS:{
System.out.println("friends");
friendsTab.setBackgroundColor(getResources().getColor(android.R.color.black));
mFriendsTv.setTextColor(getResources().getColor(android.R.color.white));
//give a call to netmanager and repaint livescorescreen on the basis of selected fragment
break;
}
case TAB_OTHER:{
System.out.println("others");
othersTab.setBackgroundColor(getResources().getColor(android.R.color.black));
mOtherTv.setTextColor(getResources().getColor(android.R.color.white));
//give a call to netmanager and repaint livescorescreen on the basis of selected fragment
break;
}
case TAB_CROWD:{
System.out.println("crowd");
crowdTab.setBackgroundColor(getResources().getColor(android.R.color.black));
mCrowdTv.setTextColor(getResources().getColor(android.R.color.white));
//give a call to netmanager and repaint livescorescreen on the basis of selected fragment
break;
}
case TAB_SOCIAL:{
System.out.println("social");
socialTab.setBackgroundColor(getResources().getColor(android.R.color.black));
mSocialTv.setTextColor(getResources().getColor(android.R.color.white));
//give a call to netmanager and repaint livescorescreen on the basis of selected fragment
break;
}
}
Fragment fragment = _adapter.getFragment(previousFragment);
if(fragment != null)
fragment.onPause();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
FragmentsAdapter
package com.example.fragments;
import java.util.List;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
public class FragmentsAdaptor extends FragmentPagerAdapter {
private List<Fragment> fragments;
/**
* #param fm
* #param fragments
*/
public FragmentsAdaptor(FragmentManager fm, List<Fragment> fragments) {
super(fm);
this.fragments = fragments;
}
/* (non-Javadoc)
* #see android.support.v4.app.FragmentPagerAdapter#getItem(int)
*/
#Override
public Fragment getItem(int position) {
return this.fragments.get(position);
}
/* (non-Javadoc)
* #see android.support.v4.view.PagerAdapter#getCount()
*/
#Override
public int getCount() {
return this.fragments.size();
}
public Fragment getFragment(int position) {
return this.fragments.get(position);
}
}
Fragment1
package com.example.fragments;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
public class Fragment1 extends Fragment implements OnClickListener {
private Context context;
public Fragment1() {}
public Fragment1(Context contex) {
this.context=contex;
}
#Override
public void onClick(View arg0) {
}
#Override
public void onInflate(Activity activity, AttributeSet attrs, Bundle savedInstanceState) {
super.onInflate(activity, attrs, savedInstanceState);
System.out.println("Fragment1.onInflate() called................");
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
System.out.println("Fragment1.onAttach() called................");
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
System.out.println("Fragment1.onCreate() called................");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
System.out.println("Fragment1.onCreateView() called................");
View root = (View) inflater.inflate(R.layout.fragment1_screen, null);
updateArticleView(root);
return root;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
System.out.println("Fragment1.onActivityCreated() called................");
}
#Override
public void onStart() {
super.onStart();
System.out.println("Fragment1.onStart() called................");
}
#Override
public void onResume() {
super.onResume();
System.out.println("Fragment1.onResume() called................");
}
#Override
public void onPause() {
super.onPause();
System.out.println("Fragment1.onPause() called................");
onDestroyView();
}
#Override
public void onDestroyView() {
super.onDestroyView();
System.out.println("Fragment1.onDestroyView() called................");
onDestroy();
}
#Override
public void onDestroy() {
super.onDestroy();
System.out.println("Fragment1.onDestroy() called................");
onDetach();
}
#Override
public void onDetach() {
super.onDetach();
System.out.println("Fragment1.onDetach() called................");
}
public void updateArticleView(View view) {
}
}
Main Activity Layout
<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" >
<HorizontalScrollView
android:id="#+id/tabs_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#android:color/transparent"
android:paddingLeft="2dp"
android:paddingRight="2dp" >
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#android:color/transparent"
android:orientation="horizontal" >
<!-- First Tab -->
<TableLayout
android:id="#+id/scores_tab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#android:color/black" >
<TableRow
android:id="#+id/tableRow1"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:gravity="center_vertical" >
<TextView
android:id="#+id/scores"
android:layout_width="fill_parent"
android:layout_height="30dp"
android:gravity="center_vertical"
android:paddingLeft="30dp"
android:paddingRight="30dp"
android:text="Scores"
android:textColor="#android:color/white"
android:textSize="11sp" />
<TextView
android:layout_width="1px"
android:layout_height="fill_parent"
android:text=""
android:textColor="#android:color/black" />
</TableRow>
</TableLayout>
<!-- Second Tab -->
<TableLayout
android:id="#+id/pavilion_tab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#android:color/transparent" >
<TableRow
android:id="#+id/tableRow2"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:gravity="center_vertical" >
<TextView
android:id="#+id/pavilion"
android:layout_width="fill_parent"
android:layout_height="30dp"
android:gravity="center_vertical"
android:paddingLeft="30dp"
android:paddingRight="25dp"
android:text="Pavilion"
android:textColor="#android:color/black"
android:textSize="11sp" />
<TextView
android:layout_width="1px"
android:layout_height="fill_parent"
android:text=""
android:textColor="#android:color/black" />
</TableRow>
</TableLayout>
<!-- Third Tab -->
<TableLayout
android:id="#+id/friends_tab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#android:color/transparent" >
<TableRow
android:id="#+id/tableRow3"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:gravity="center_vertical" >
<TextView
android:id="#+id/friends"
android:layout_width="fill_parent"
android:layout_height="30dp"
android:gravity="center_vertical"
android:paddingLeft="30dp"
android:paddingRight="30dp"
android:text="Friends"
android:textColor="#android:color/black"
android:textSize="11sp" />
<TextView
android:layout_width="1px"
android:layout_height="fill_parent"
android:text=""
android:textColor="#android:color/black" />
</TableRow>
</TableLayout>
<!-- Fourth Tab -->
<TableLayout
android:id="#+id/others_tab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#android:color/transparent" >
<TableRow
android:id="#+id/tableRow4"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:gravity="center_vertical" >
<TextView
android:id="#+id/other"
android:layout_width="fill_parent"
android:layout_height="30dp"
android:gravity="center_vertical"
android:paddingLeft="30dp"
android:paddingRight="30dp"
android:text="Other"
android:textColor="#android:color/black"
android:textSize="11sp" />
<TextView
android:layout_width="1px"
android:layout_height="fill_parent"
android:text=""
android:textColor="#android:color/black" />
</TableRow>
</TableLayout>
<!-- Fifth Tab -->
<TableLayout
android:id="#+id/crowd_tab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#android:color/transparent" >
<TableRow
android:id="#+id/tableRow5"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:gravity="center_vertical" >
<TextView
android:id="#+id/crowd"
android:layout_width="fill_parent"
android:layout_height="30dp"
android:gravity="center_vertical"
android:paddingLeft="30dp"
android:paddingRight="30dp"
android:text="Crowd"
android:textColor="#android:color/black"
android:textSize="11sp" />
<TextView
android:layout_width="0px"
android:layout_height="fill_parent"
android:text=""
android:textColor="#android:color/black" />
</TableRow>
</TableLayout>
<!-- Sixth Tab -->
<TableLayout
android:id="#+id/social_tab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:textColor="#android:color/transparent" >
<TableRow
android:id="#+id/tableRow6"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:gravity="center_vertical" >
<TextView
android:id="#+id/social"
android:layout_width="fill_parent"
android:layout_height="30dp"
android:gravity="center_vertical"
android:paddingLeft="30dp"
android:paddingRight="30dp"
android:text="Social"
android:textColor="#android:color/black"
android:textSize="12sp" />
</TableRow>
</TableLayout>
</LinearLayout>
</HorizontalScrollView>
<android.support.v4.view.ViewPager
android:id="#+id/viewPager"
android:layout_width="match_parent"
android:layout_height="300dp"
android:layout_below="#id/tabs_layout"
android:layout_marginBottom="10dp"
android:layout_marginTop="10dp" >
</android.support.v4.view.ViewPager>
Fragment layout
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/relLay"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="#+id/text1"
android:text="Fragment1 Text"
android:textColor="#android:color/black"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>

I achieved it by placing the following code at the end of OnPageChangeListener.onPageSelected()
Fragment fragment = _adapter.getFragment(previousFragment);
if(fragment != null) {
fragment.onPause();
}
I am using onPause() in the following way
public void onPause(){
super.onPause();
onDestroyView();
}
public void onDestroyView() {
super.onDestroyView();
onDestroy();
}
public void onDestroy() {
super.onDestroy();
onDetach();
}
public void onDetach() {
super.onDetach();
}

this is a known issue, that ViewPager(FragmentAdapter(Fragements)) created and destroyed according to the actual page.
I also came across with this situation, furthermore the data (Object) not referenced, because of a destroy will be collected by the GC so this is difficult.
I would use a static object at the main Activity and with the onRetainNonConfigurationInstance method I would save and load Fragment state.
Also found another solution which concentrated on the passed data between the Fragments (A,B and passed String data) here.
I hope one of these solutions are suitable for you!

Just call setOffscreenPageLimit() in onCreate() (after initializing ViewPager). The OffscreenPageLimit sets the number of pages that should be retained to either side of the current page. Set the minimum number of fragments you want to initiate either side.

Related

How to animate overlay an edit-box on tab-layout on android?

I wanted to achieve this animation, which is the search edit box overlays the tab-layout, I must tell that I tried this code on the parent layout android:animateLayoutChanges="true" and set the tab-layout visibility to View.GONE but it just animates the tab moving up, not the search box overlays tab-layout.
I have made a quick dummy app that looks like yours, and tried to achieve what you have shown in your animation. See the effect below (you can make it more smooth and elegant) :
Its a bit tricky way of doing, the way I have done. I post my whole code here :
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.pabhinav.testapp3">
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity
android:name=".MainActivity"
android:label="#string/app_name"
android:screenOrientation="portrait"
android:theme="#style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
MainActivity.java
package com.pabhinav.testapp3;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.LinearInterpolator;
import android.view.animation.ScaleAnimation;
import android.view.animation.TranslateAnimation;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import static com.pabhinav.testapp3.R.id.container;
public class MainActivity extends AppCompatActivity implements PlaceholderFragment.OnSearchBoxClick{
/**
* The {#link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a
* {#link FragmentPagerAdapter} derivative, which will keep every
* loaded fragment in memory. If this becomes too memory intensive, it
* may be best to switch to a
* {#link android.support.v4.app.FragmentStatePagerAdapter}.
*/
private SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {#link ViewPager} that will host the section contents.
*/
private ViewPager mViewPager;
/**
* Search Box in activity.
*/
private RelativeLayout dummySearchBox;
private LinearLayout topSearchBox;
/**
* Overlay View appears when search box is clicked.
*/
private View overlay;
/**
* Back button image view for top search box
*/
private ImageView backButtonSearchBox;
/**
* PlaceHolderFragment saved only for second tab,
* which has search box.
*/
private PlaceholderFragment placeholderFragment;
private float xDelta, yDelta;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
getWindow().setStatusBarColor(getResources().getColor(R.color.colorPrimaryDark));
overlay = findViewById(R.id.overlay_whole_page);
backButtonSearchBox = (ImageView)findViewById(R.id.search_icon);
// Consume touch event, so that it does not pass to parent views.
// This is done to block swipe events of tab layout, once search
// box is clicked.
overlay.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
return true;
}
});
// TabLayout and ViewPager.
final TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
mViewPager = (ViewPager) findViewById(container);
dummySearchBox = (RelativeLayout)findViewById(R.id.dummy_search_box);
topSearchBox = (LinearLayout)findViewById(R.id.top_search_box);
// Set up the ViewPager with the sections adapter.
mViewPager.setAdapter(mSectionsPagerAdapter);
mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {}
#Override
public void onPageSelected(int position) {
for (int i = 0; i < tabLayout.getTabCount(); i++) {
if(i == position){
tabLayout.getTabAt(i).setIcon(getTabIconHighlighted(i));
} else {
tabLayout.getTabAt(i).setIcon(getTabIconUnhighlighted(i));
}
}
}
#Override
public void onPageScrollStateChanged(int state) {}
});
// Setup viewpager with tablayout and also set up icons of each tabs :
tabLayout.setupWithViewPager(mViewPager);
for(int i = 0; i<tabLayout.getTabCount(); i++){
// Set first tab highlighted :
if(i == 0){
tabLayout.getTabAt(i).setIcon(getTabIconHighlighted(i));
} else {
tabLayout.getTabAt(i).setIcon(getTabIconUnhighlighted(i));
}
}
// Back Button in top search box clicked.
backButtonSearchBox.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
overlay.setVisibility(View.INVISIBLE);
dummySearchBox.setVisibility(View.VISIBLE);
topSearchBox.setVisibility(View.INVISIBLE);
AnimationSet animSet = new AnimationSet(true);
animSet.setFillAfter(false);
animSet.setDuration(150);
animSet.setInterpolator(new LinearInterpolator());
TranslateAnimation translate = new TranslateAnimation(-xDelta, 0, -yDelta, 0);
animSet.addAnimation(translate);
ScaleAnimation scale = new ScaleAnimation(1.2f, 1f, 1.2f, 1f);
animSet.addAnimation(scale);
dummySearchBox.startAnimation(animSet);
animSet.setAnimationListener(new Animation.AnimationListener() {
#Override
public void onAnimationStart(Animation animation) {
}
#Override
public void onAnimationEnd(Animation animation) {
placeholderFragment.showSearchLayout();
dummySearchBox.setVisibility(View.INVISIBLE);
}
#Override
public void onAnimationRepeat(Animation animation) {
}
});
}
});
}
private int getTabIconUnhighlighted(int position){
switch (position){
case 0 : return R.drawable.ic_home_black_24dp;
case 1 : return R.drawable.ic_search_black_24dp;
case 2 : return R.drawable.ic_heart_black_24dp;
case 3 : return R.drawable.ic_view_headline_black_24dp;
}
return -1;
}
private int getTabIconHighlighted(int position){
switch(position){
case 0 : return R.drawable.ic_home_highlighted_24dp;
case 1 : return R.drawable.ic_search_highlighted_24dp;
case 2 : return R.drawable.ic_heart_highlighted_24dp;
case 3 : return R.drawable.ic_view_headline_highlighted_24dp;
}
return -1;
}
/**
* This event is when search box from fragment is clicked,
* need to animate the search box present in activity
* to reach the top of activity display.
*/
#Override
public void onClick() {
dummySearchBox.setVisibility(View.VISIBLE);
dummySearchBox.clearFocus();
((EditText)findViewById(R.id.search_edit_text)).clearFocus();
performAnimation(dummySearchBox);
}
public void performAnimation(final RelativeLayout dummySearchBox){
if(xDelta == 0 && yDelta == 0){
DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
int[] originalPos = new int[2];
dummySearchBox.getLocationOnScreen(originalPos);
xDelta = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 18, getResources().getDisplayMetrics());
yDelta = originalPos[1] - TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 12, getResources().getDisplayMetrics());;
}
AnimationSet animSet = new AnimationSet(true);
animSet.setFillAfter(false);
animSet.setDuration(200);
animSet.setInterpolator(new LinearInterpolator());
TranslateAnimation translate = new TranslateAnimation( 0, -1*xDelta, 0, -1*yDelta);
animSet.addAnimation(translate);
ScaleAnimation scale = new ScaleAnimation(1f, 1.15f, 1f, 1.15f);
animSet.addAnimation(scale);
dummySearchBox.startAnimation(animSet);
animSet.setAnimationListener(new Animation.AnimationListener() {
#Override
public void onAnimationStart(Animation animation) {
}
#Override
public void onAnimationEnd(Animation animation) {
topSearchBox.setVisibility(View.VISIBLE);
dummySearchBox.setVisibility(View.INVISIBLE);
overlay.setVisibility(View.VISIBLE);
}
#Override
public void onAnimationRepeat(Animation animation) {
}
});
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
/**
* The fragment argument representing the section number for this
* fragment.
*/
public static final String ARG_SECTION_NUMBER = "section_number";
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a PlaceholderFragment.
PlaceholderFragment placeholderFragment = new PlaceholderFragment();
placeholderFragment.setOnSearchBoxClick(MainActivity.this);
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, position + 1);
placeholderFragment.setArguments(args);
if(position == 1){
MainActivity.this.placeholderFragment = placeholderFragment;
}
return placeholderFragment;
}
#Override
public int getCount() {
// Show 4 total pages.
return 4;
}
}
}
PlaceholderFragment.java
package com.pabhinav.testapp3;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
/**
* #author pabhinav
*/
public class PlaceholderFragment extends Fragment {
private LinearLayout searchLayout;
public PlaceholderFragment() {
}
private OnSearchBoxClick onSearchBoxClick;
public void setOnSearchBoxClick(OnSearchBoxClick onSearchBoxClick){
this.onSearchBoxClick = onSearchBoxClick;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
int sectionNumber = getArguments().getInt(MainActivity.SectionsPagerAdapter.ARG_SECTION_NUMBER);
View rootView = inflater.inflate((sectionNumber == 2) ? R.layout.fragment_search : R.layout.fragment_main, container, false);
if(sectionNumber != 2) {
TextView textView = (TextView) rootView.findViewById(R.id.section_label);
textView.setText(getString(R.string.section_format, sectionNumber));
} else {
// Its the fragment with search box :
TextView searchText = (TextView) rootView.findViewById(R.id.search_text);
ImageView searchIcon = (ImageView)rootView.findViewById(R.id.search_icon);
searchLayout = (LinearLayout)rootView.findViewById(R.id.search_linear_layout);
// Need to do transition when clicked on any of the search box elements :
View.OnClickListener clickListener = new View.OnClickListener(){
#Override
public void onClick(View v) {
searchLayout.setVisibility(View.INVISIBLE);
if(onSearchBoxClick != null)
onSearchBoxClick.onClick();
}
};
searchText.setOnClickListener(clickListener);
searchLayout.setOnClickListener(clickListener);
searchIcon.setOnClickListener(clickListener);
}
return rootView;
}
public void showSearchLayout(){
searchLayout.setVisibility(View.VISIBLE);
}
public interface OnSearchBoxClick{
public void onClick();
}
}
activity_main.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:id="#+id/main_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context="com.pabhinav.testapp3.MainActivity">
<android.support.design.widget.TabLayout
android:layout_marginTop="8dp"
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<!-- Top Search Box -->
<!-- Only appears when search box is clicked -->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="56dp"
android:id="#+id/top_search_box"
android:visibility="invisible"
android:orientation="horizontal">
<RelativeLayout
android:layout_gravity="center"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#android:color/white">
<ImageView
android:gravity = "center"
android:layout_width="52dp"
android:paddingLeft="24dp"
android:paddingRight="8dp"
android:id="#+id/search_icon"
android:layout_height="match_parent"
android:src="#drawable/ic_arrow_back_black_24dp"/>
<EditText
android:layout_toEndOf="#+id/search_icon"
android:hint="#string/search_soundcloud"
android:textSize="18sp"
android:background="#android:color/transparent"
android:textColorHint="#B3B3B3"
android:layout_margin="4dp"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
</LinearLayout>
<!-- Dummy container for search box -->
<!-- This will do transition from its location to top_search_box location -->
<RelativeLayout
android:id="#+id/dummy_search_box"
android:layout_width="match_parent"
android:layout_below="#+id/tabs"
android:visibility="invisible"
android:layout_height="wrap_content"
android:padding="16dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="56dp"
android:id="#+id/search_linear_layout_dummy"
android:orientation="horizontal">
<RelativeLayout
android:layout_gravity="center"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="5dp"
android:background="#android:color/white"
android:elevation="2dp"
android:translationZ="2dp">
<ImageView
android:gravity = "center"
android:layout_width="20dp"
android:layout_marginStart="16dp"
android:id="#+id/search_icon_dummy"
android:layout_height="match_parent"
android:src="#drawable/ic_search_light_black_24dp"/>
<EditText
android:id="#+id/search_edit_text"
android:layout_toEndOf="#+id/search_icon_dummy"
android:hint="#string/search_soundcloud"
android:textSize="16sp"
android:background="#android:color/transparent"
android:textColorHint="#B3B3B3"
android:layout_margin="4dp"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
</LinearLayout>
</RelativeLayout>
<android.support.v4.view.ViewPager
android:layout_below="#+id/tabs"
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<!-- Dummy overlay over whole page, More things can be added like listview
which displays result of searched text -->
<View
android:id="#+id/overlay_whole_page"
android:layout_below="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:visibility="gone"
android:background="#72000000" />
<!-- Dummy shadow below tablayout -->
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:layout_below="#+id/tabs"
android:background="#42000000" />
</RelativeLayout>
fragment_search.xml
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
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="com.pabhinav.testapp3.MainActivity$PlaceholderFragment">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="56dp"
android:id="#+id/search_linear_layout"
android:orientation="horizontal">
<RelativeLayout
android:layout_gravity="center"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="5dp"
android:background="#android:color/white"
android:elevation="2dp"
android:translationZ="2dp">
<ImageView
android:gravity = "center"
android:layout_width="20dp"
android:layout_marginStart="16dp"
android:id="#+id/search_icon"
android:layout_height="match_parent"
android:src="#drawable/ic_search_light_black_24dp"/>
<TextView
android:id="#+id/search_text"
android:layout_toEndOf="#+id/search_icon"
android:text="#string/search_soundcloud"
android:gravity="center_vertical"
android:textColor="#B3B3B3"
android:textSize="16sp"
android:layout_margin="4dp"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
</LinearLayout>
<TextView
android:id="#+id/suggested_stations"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="56dp"
android:textSize="18sp"
android:layout_below="#+id/search_linear_layout"
android:text = "#string/suggested_stations"/>
<LinearLayout
android:layout_below="#+id/suggested_stations"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<ImageView
android:layout_width="0dp"
android:layout_height="240dp"
android:src="#drawable/image_1"
android:layout_weight="1"/>
<ImageView
android:layout_marginStart="16dp"
android:layout_width="0dp"
android:layout_height="240dp"
android:src="#drawable/image_2"
android:layout_weight="1"/>
</LinearLayout>
</RelativeLayout>
Download the whole project from here : https://drive.google.com/file/d/0B_Mi44NWLWmyNFNkeHJ6cVBLTTg/view?usp=sharing
Hope it helps !

How to create a stack view in this swipe card?

I have used the following code to create a swipe view. This is my java code
package com.lorentzos.swipecards;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.FrameLayout;
import android.widget.Toast;
import com.lorentzos.flingswipe.SwipeFlingAdapterView;
import java.util.ArrayList;
import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;
public class MyActivity extends Activity {
private ArrayList<String> al;
private ArrayAdapter<String> arrayAdapter;
FrameLayout.LayoutParams params;
View v;
#InjectView(R.id.frame) SwipeFlingAdapterView flingContainer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
/*frameLayout=(FrameLayout)v.findViewById(R.id.frame_layout);*/
v=findViewById(R.id.frame_layout);
ButterKnife.inject(this);
/*al.add("c");
al.add("python");
al.add("java");
al.add("html");
al.add("c++");
al.add("css");
al.add("javascript");*/
int height=500;
int width=500;
params = new FrameLayout.LayoutParams(width, height);
/*params.gravity= Gravity.CENTER;*/
al = new ArrayList<>();
for(int i=0; i<=7; i++) {
al.add("php");
arrayAdapter = new ArrayAdapter<>(this, R.layout.item, R.id.helloText, al);
flingContainer.setMaxVisible(4);
/*v.setLayoutParams(params);*/
flingContainer.setAdapter(arrayAdapter);
height=height-20;
}
flingContainer.setFlingListener(new SwipeFlingAdapterView.onFlingListener() {
#Override
public void removeFirstObjectInAdapter() {
// this is the simplest way to delete an object from the Adapter (/AdapterView)
Log.d("LIST", "removed object!");
al.remove(0);
arrayAdapter.notifyDataSetChanged();
}
#Override
public void onLeftCardExit(Object dataObject) {
//Do something on the left!
//You also have access to the original object.
//If you want to use it just cast it (String) dataObject
makeToast(MyActivity.this, "Left!");
}
#Override
public void onRightCardExit(Object dataObject) {
makeToast(MyActivity.this, "Right!");
}
#Override
public void onAdapterAboutToEmpty(int itemsInAdapter) {
// Ask for more data here
/*al.add("XML ".concat(String.valueOf(i)));
arrayAdapter.notifyDataSetChanged();
Log.d("LIST", "notified");
i++;*/
}
#Override
public void onScroll(float scrollProgressPercent) {
View view = flingContainer.getSelectedView();
view.findViewById(R.id.item_swipe_right_indicator).setAlpha(scrollProgressPercent < 0 ? -scrollProgressPercent : 0);
view.findViewById(R.id.item_swipe_left_indicator).setAlpha(scrollProgressPercent > 0 ? scrollProgressPercent : 0);
}
});
// Optionally add an OnItemClickListener
flingContainer.setOnItemClickListener(new SwipeFlingAdapterView.OnItemClickListener() {
#Override
public void onItemClicked(int itemPosition, Object dataObject) {
makeToast(MyActivity.this, "Clicked!");
}
});
}
static void makeToast(Context ctx, String s){
Toast.makeText(ctx, s, Toast.LENGTH_SHORT).show();
}
#OnClick(R.id.right)
public void right() {
/**
* Trigger the right event manually.
*/
flingContainer.getTopCardListener().selectRight();
}
#OnClick(R.id.left)
public void left() {
flingContainer.getTopCardListener().selectLeft();
}
}
Below are the xml files
activity_my.xml
<merge
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"
>
<com.lorentzos.flingswipe.SwipeFlingAdapterView
android:id="#+id/frame"
android:background="#ffeee9e2"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:rotation_degrees="15.5"
app:min_adapter_stack="6"
tools:context=".MyActivity" />
<include layout="#layout/buttons" />
</merge>
item.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/frame_layout"
android:layout_gravity="center"
android:layout_width="200dp"
android:layout_height="200dp">
<TextView
android:id="#+id/helloText"
android:textSize="40sp"
android:textColor="#android:color/white"
android:background="#A5F"
android:gravity="center"
tools:text="#string/hello_world"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<View
android:id="#+id/item_swipe_left_indicator"
android:alpha="0"
android:layout_width="20dp"
android:layout_height="20dp"
android:layout_margin="10dp"
android:background="#A5F" />
<View
android:id="#+id/item_swipe_right_indicator"
android:alpha="0"
android:layout_width="20dp"
android:layout_height="20dp"
android:layout_margin="10dp"
android:layout_gravity="right"
android:background="#5AF" />
</FrameLayout>
buttons.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_gravity="center_horizontal|bottom"
android:layout_marginBottom="20dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<Button
android:id="#+id/left"
android:layout_margin="10dp"
android:text="Left"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:id="#+id/right"
android:layout_margin="10dp"
android:text="Right"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
Refer the attached screenshots.
[![enter image description here][2]][2]
But i want the images to come like a stack.. Not exactly overlapped. Refer this
Can anyone help me achieve this?
This is a link with your solution https://github.com/Diolor/Swipecards
Incase you use custom ArrayAdaper on inflating layout this is the code that worked for me
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.swipe_item, parent, false);

Same Navigation Drawer in different activities with different views

I have many activities which share the same navigation drawer. How do I write different views for all the activities with same navigation drawer. The xml and Java files can be found below.
navigation_drawer.xml
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent">
</FrameLayout>
<LinearLayout
android:id="#+id/navigationLinearLayout"
android:layout_width="200dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:orientation="vertical" >
<ListView
android:id="#+id/navList_one"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="left|start"
android:choiceMode="singleChoice"
android:listSelector="#color/notificationarea_background"
android:background="#color/navigation_background"/>
<View
android:layout_width="match_parent"
android:layout_height="3dp"
android:background="#color/notificationarea_background"/>
<ListView
android:id="#+id/navList_two"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="left|start"
android:background="#color/navigation_background"/>
</LinearLayout>
</android.support.v4.widget.DrawerLayout>
MainActivity.java
import android.os.Bundle;
public class MainActivity extends NavigationDrawer {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getLayoutInflater().inflate(R.layout.navigation_drawer, frameLayout);
}
}
Login.java
import android.os.Bundle;
public class Login extends NavigationDrawer {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getLayoutInflater().inflate(R.layout.navigation_drawer, frameLayout);
}
}
navigation_drawer_text.xml
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/tv"
android:textColor="#color/navigation_text"
android:padding="18dp"
android:layout_width="fill_parent"
android:background="#drawable/navigation_selector"
android:singleLine="true"
android:gravity="left"
android:layout_height="fill_parent"/>
NavigationDrawer.java
public class NavigationDrawer extends AppCompatActivity {
protected FrameLayout frameLayout;
public ListView mDrawerList_one, mDrawerList_two;
private ArrayAdapter<String> mAdapter_one, mAdapter_two;
private ActionBarDrawerToggle mDrawerToggle;
private DrawerLayout mDrawerLayout;
private String mActivityTitle;
//Just the sample links.
String[] Links1 = { "Login1", "Login2", "MainActivity1" };
String[] Links2 = { "Login3", "Login4", "MainActivity2" };
protected int position_itemSelected; //Position of item selected in ListView
private static boolean isLaunch = true;
SharedPreferences itemSelected_shared;
SharedPreferences.Editor itemSelected_editor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.navigation_drawer);
frameLayout = (FrameLayout)findViewById(R.id.content_frame);
mDrawerList_one = (ListView)findViewById(R.id.navList_one);
mDrawerList_two = (ListView)findViewById(R.id.navList_two);
mDrawerLayout = (DrawerLayout)findViewById(R.id.drawer_layout);
itemSelected_shared = getApplicationContext().getSharedPreferences("Item Selected in Navigation Drawer", 0);
itemSelected_editor = itemSelected_shared.edit();
Window window = this.getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
window.setStatusBarColor(this.getResources().getColor(R.color.notificationarea_background));
addDrawerItems();
setupDrawer();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
}
private void addDrawerItems() {
mAdapter_one = new ArrayAdapter<String>(this, R.layout.navigation_drawer_text, Links);
mDrawerList_one.setDivider(null);
mDrawerList_one.setAdapter(mAdapter_one);
if(itemSelected_shared.getInt("Item Selected", 0) == 1) {
mDrawerList_one.post(new Runnable() {
#Override
public void run() {
mDrawerList_one.setSelected(true);
mDrawerList_one.getChildAt(itemSelected_shared.getInt("Item Selected One", 0)).setBackgroundColor(getResources().getColor(R.color.notificationarea_background));
}
});
}
mAdapter_two = new ArrayAdapter<String>(this, R.layout.navigation_drawer_text, Links);
mDrawerList_two.setDivider(null);
mDrawerList_two.setAdapter(mAdapter_two);
if(itemSelected_shared.getInt("Item Selected", 0) == 2) {
mDrawerList_two.post(new Runnable() {
#Override
public void run() {
mDrawerList_two.setSelected(true);
mDrawerList_two.getChildAt(itemSelected_shared.getInt("Item Selected Two", 0)).setBackgroundColor(getResources().getColor(R.color.notificationarea_background));
}
});
}
mDrawerList_one.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
itemSelected_editor.putInt("Item Selected", 1);
itemSelected_editor.putInt("Item Selected One", position);
itemSelected_editor.commit();
}
});
mDrawerList_two.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
itemSelected_editor.putInt("Item Selected", 2);
itemSelected_editor.putInt("Item Selected Two", position);
itemSelected_editor.commit();
if (isLaunch) {
switch (position) {
case 0:
//Intent, which is working fine.
case 1:
//Intent, which is working fine.
}
}
}
});
}
private void setupDrawer() {
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.string.drawer_open, R.string.drawer_close) {
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
invalidateOptionsMenu();
}
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
invalidateOptionsMenu();
}
};
mDrawerToggle.setDrawerIndicatorEnabled(true);
mDrawerLayout.setDrawerListener(mDrawerToggle);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
}
I am extending NavigationDrawer in my other activities(MainActivity and Login).
I want MainActivity and Login to have navigation drawer as well as their own xml views/xml files. If I put some content in navigation_drawer.xml, then it would come in all activities. I want different contents for MainActivity and Login with same navigation drawer.
Thank you.
Try this way to create sliding drawer,it will help
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:gravity="center_horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<balaji.slidingdrawer_tb.Transparent
android:id="#+id/popup_window"
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="left"
android:padding="30px">
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#000000"
android:textSize="20dp"
android:paddingTop="20dp"
android:paddingBottom="20dp"
android:text="Top to Bottom Sliding" />
<CheckBox
android:id="#+id/checkBox1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="17dp"
android:text="Jelly Bean" />
<CheckBox
android:id="#+id/checkBox2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="17dp"
android:text="Ice Cream Sandwich" />
<CheckBox
android:id="#+id/checkBox3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="17dp"
android:text="HoneyComb" />
</balaji.slidingdrawer_tb.Transparent>
<Button
android:id="#+id/handle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Handle"/>
</LinearLayout>
MainActivity.java
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
public class MainActivity extends Activity {
/** Called when the activity is first created. */
CheckBox cb1,cb2,cb3;
int key=0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Transparent popup = (Transparent) findViewById(R.id.popup_window);
popup.setVisibility(View.GONE);
final Button btn=(Button)findViewById(R.id.handle);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
if(key==0){
key=1;
popup.setVisibility(View.VISIBLE);
// btn.setBackgroundResource(R.drawable.ic_launcher);
}
else if(key==1){
key=0;
popup.setVisibility(View.GONE);
// btn.setBackgroundResource(R.drawable.ic_action_search);
}
}
});
}
}
See here for more detail
Each Activity has to have his one fragment layout and inflate it from there. Take a look at this tutorial, it's really good:

Why text in TextView doesn't update when button pressed on fragment?

I created my app with the Tabbed Activity. I created some fragments and simple UI. Swipe and tabs work. I want to make really simple calculator-like app but I can't even change the text.
I tried so many solutions found on the Internet, but nothing works. I'm a beginner in Android development and now my code is a real mess.
What change to make it work? I just want to change some TextView's texts after clicking calculate button.
SingleLeg.java
package com.mycompany.hoptestcalculator;
import android.app.Activity;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
//import android.text.Editable;
//import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
//import android.widget.ImageView;
import android.widget.TextView;
import android.view.View.OnClickListener;
/**
* A simple {#link Fragment} subclass.
* Activities that contain this fragment must implement the
* {#link SingleLeg.OnFragmentInteractionListener} interface
* to handle interaction events.
* Use the {#link SingleLeg#newInstance} factory method to
* create an instance of this fragment.
*/
public class SingleLeg extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment SingleLeg.
*/
// TODO: Rename and change types and number of parameters
public static SingleLeg newInstance(String param1, String param2) {
SingleLeg fragment = new SingleLeg();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
public SingleLeg() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
// ImageButton calculate = (ImageButton) getView().findViewById(R.id.calculate);
//
//
// calculate.setOnClickListener(this);
}
// #Override
// public void onClick(View v) {
// int id = v.getId();
//
//
// left1 = (EditText) getView().findViewById(R.id.LeftTr1);
// right1 = (EditText) getView().findViewById(R.id.RightTr1);
// left2 = (EditText) getView().findViewById(R.id.LeftTr2);
// right2 = (EditText) getView().findViewById(R.id.RightTr2);
//
// if(id == R.id.calculate && (!left1.getText().equals("")) ) {
// avgL.setText("2");
// }
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
//return inflater.inflate(R.layout.fragment_single_leg, container, false);
View v = inflater.inflate(R.layout.fragment_single_leg,
container, false);
Button calculate = (Button) getView().findViewById(R.id.calculate);
final TextView textView = (TextView) getView().findViewById(R.id.avgLeft);
calculate.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
textView.setText("abc");
}
});
return v;
}
//
// EditText left1 = (EditText) getView().findViewById(R.id.LeftTr1);
// EditText right1 = (EditText) getView().findViewById(R.id.RightTr1);
// EditText left2 = (EditText) getView().findViewById(R.id.LeftTr2);
// EditText right2 = (EditText) getView().findViewById(R.id.RightTr2);
// TextView avgL; //= (TextView) getView().findViewById(R.id.avgLeft);
// TextView avgR = (TextView) getView().findViewById(R.id.avgRight);
// TextView leftOfRight = (TextView) getView().findViewById(R.id.Left_Right);
// TextView rightOfLeft = (TextView) getView().findViewById(R.id.Right_Left);
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (OnFragmentInteractionListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p/>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
public void onFragmentInteraction(Uri uri);
}
// //Declaration
// private class GenericTextWatcher implements TextWatcher{
//
// private View view;
// private GenericTextWatcher(View view) {
// this.view = view;
// }
//
// public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {}
// public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {}
//
// public void afterTextChanged(Editable editable) {
// String text = editable.toString();
// switch(view.getId()){
// case R.id.LeftTr1:
// text.setName(text);
// break;
// case R.id.RightTr1:
// model.setEmail(text);
// break;
// case R.id.LeftTr2:
// model.setPhone(text);
// break;
// }
// }
// }
// left1.addTextChangedListener(new TextWatcher() {
// #Override
// public void afterTextChanged(Editable arg0) {
// enableSubmitIfReady();
// }
//
// #Override
// public void beforeTextChanged(CharSequence s, int start, int count, int after) {
// }
//
// #Override
// public void onTextChanged(CharSequence s, int start, int before, int count) {
// }
// });
public void updateTextView(String toThis) {
TextView avg = (TextView) getView().findViewById(R.id.avgLeft);
avg.setText("567");
return;
}
}
fragment_single_leg.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:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:orientation="vertical"
tools:context="com.mycompany.hoptestcalculator.SingleLeg"
android:id="#+id/container"
>
<LinearLayout
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
>
<View
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="50dp"/>
<TextView
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="#string/left_leg"
android:id="#+id/textView"
android:background="#drawable/back"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:paddingTop="5dp"
android:paddingBottom="5dp" />
<View
android:layout_weight="0.05"
android:layout_width="0dp"
android:layout_height="50dp"/>
<TextView
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="#string/right_leg"
android:id="#+id/textView2"
android:background="#drawable/back"
android:paddingLeft="10dp"
android:paddingTop="5dp"
android:paddingBottom="5dp"
android:paddingRight="10dp" />
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="#string/trial_1"
android:id="#+id/trial1" />
<EditText
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:inputType="number"
android:ems="10"
android:id="#+id/LeftTr1"
android:layout_gravity="center_horizontal" />
<View
android:layout_weight="0.05"
android:layout_width="0dp"
android:layout_height="50dp"/>
<EditText
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:inputType="number"
android:ems="10"
android:id="#+id/RightTr1"
android:layout_gravity="center_horizontal" />
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="#string/trial_2"
android:id="#+id/trial2" />
<EditText
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:inputType="number"
android:ems="10"
android:id="#+id/LeftTr2"
android:layout_gravity="center_horizontal" />
<View
android:layout_weight="0.05"
android:layout_width="0dp"
android:layout_height="50dp"/>
<EditText
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:inputType="number"
android:ems="10"
android:id="#+id/RightTr2"
android:layout_gravity="center_horizontal" />
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="#string/average"
android:id="#+id/avg" />
<TextView
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="match_parent"
android:id="#+id/avgLeft"
android:textAppearance="?android:attr/textAppearanceLarge"
android:background="#drawable/bg_avg"
android:text="rgrrgrgrg"
android:enabled="true"
android:editable="false" />
<View
android:layout_weight="0.05"
android:layout_width="0dp"
android:layout_height="50dp"/>
<TextView
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="match_parent"
android:id="#+id/avgRight"
android:textAppearance="?android:attr/textAppearanceLarge"
android:background="#drawable/bg_avg" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="50dp"></LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="#string/left_of_right"
android:id="#+id/lofR"
android:layout_gravity="center_vertical"/>
<TextView
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="50dp"
android:id="#+id/Left_Right"
android:textAppearance="?android:attr/textAppearanceLarge"
android:background="#drawable/bg_avg" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="10dp"></LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="#string/right_of_left"
android:id="#+id/RofL"
android:layout_gravity="center_vertical"/>
<TextView
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="50dp"
android:id="#+id/Right_Left"
android:textAppearance="?android:attr/textAppearanceLarge"
android:background="#drawable/bg_avg" />
</LinearLayout>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Calculate"
android:id="#+id/calculate"
android:layout_gravity="center_horizontal"
android:layout_marginTop="50dp"
android:textSize="35dp" />
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.mycompany.hoptestcalculator" >
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/app_name"
android:screenOrientation="portrait">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Inside onCreateView() of the fragment :
Button calculate = (Button) convertView.findViewById(R.id.calculate);
final TextView textView = (TextView) convertView.findViewById(R.id.textViewId);
Then set a click listener on the button. :
calculate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
textView.setText("Here goes sample text");
}
});

Using getFragmentManager on a ListActivity

I just want to know if this is possible since first. I have created a custom listView based on the tutorial I read from Sai Geetha. Well it works perfectly on my app except that it needs to extend ListActivity instead of FragmentActivity. Now I'm having a hard time configuring and adding a dialog for this since I need to apply a fragment dialog and I can't use the getFragmentManager() since I'm not working with the FragmentActivity. Is there's another way I can do to work on this without sacrificing the ListActivity? Thanks!
Here's my code so far
XML:
conversation_list_view
<?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">
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#id/android:list"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginBottom="5dp"
android:layout_marginTop="20dp"/>
</LinearLayout>
group_screen
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/white">
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="48dp"
android:background="#drawable/action_bar_separator"
android:id="#+id/relativeLayout">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Group Name"
android:id="#+id/txt_group_name"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:textColor="#color/dark_gray"
android:shadowColor="#color/dark_shadow"
android:shadowRadius="1"
android:shadowDy="1"/>
<Button
android:layout_width="32dp"
android:layout_height="32dp"
android:id="#+id/btn_back"
android:background="#drawable/btn_navigate_back"
android:layout_centerVertical="true"
android:layout_alignParentLeft="true"/>
<Button
android:layout_width="32dp"
android:layout_height="32dp"
android:id="#+id/btn_information"
android:background="#drawable/btn_information"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"
android:layout_marginTop="10dp"
android:layout_marginRight="10dp"/>
</RelativeLayout>
<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Conversations"
android:id="#+id/textView2"
android:textColor="#color/holo_light_blue"
android:layout_marginLeft="15dp"
android:layout_marginTop="10dp"/>
<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="340dp"
>
<fragment
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:name="com.mark.exercise.ListViewFragment"
android:id="#+id/fragment"/>
</LinearLayout>
<Button
android:layout_width="match_parent"
android:layout_height="42dp"
android:text="Ask something"
android:id="#+id/btn_ask_question"
android:layout_marginRight="10dp"
android:layout_marginLeft="10dp"
android:textSize="15dp"/>
</LinearLayout>
</LinearLayout>
Java
package com.mark.exercise;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
/**
* Created by pc on 9/24/13.
*/
public class GroupActivity extends FragmentActivity {
Button information, back, new_topic;
ListView conversations;
TextView group_name;
String name, group_description, group_administrator,image_id;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.group_screen);
Intent intent = getIntent();
name = intent.getStringExtra("group_name");
group_description = intent.getStringExtra("group_description");
group_administrator = intent.getStringExtra("group_administrator");
image_id = intent.getStringExtra("image_id");
information = (Button)findViewById(R.id.btn_information);
back = (Button)findViewById(R.id.btn_back);
new_topic = (Button)findViewById(R.id.btn_ask_question);
group_name = (TextView)findViewById(R.id.txt_group_name);
group_name.setText(name);
information.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(GroupActivity.this, GroupInformationActivity.class);
intent.putExtra("group_name",name);
intent.putExtra("group_description",group_description);
intent.putExtra("group_administrator",group_administrator);
intent.putExtra("image_id",image_id);
startActivity(intent);
GroupActivity.this.overridePendingTransition(R.anim.in_from_left, R.anim.out_to_right);
}
});
new_topic.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showCreateNewTopicDialog();
}
});
back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onBackPressed();
}
});
}
private void showCreateNewTopicDialog() {
FragmentManager fm = getSupportFragmentManager();
DialogFragmentCreateGroup createGroup = new DialogFragmentCreateGroup();
createGroup.show(fm, "create_group");
}
#Override
public void onBackPressed(){
super.onBackPressed();
overridePendingTransition(R.anim.in_from_right,R.anim.out_to_left);
}
}
List Fragment
package com.mark.exercise;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Random;
/**
* Created by pc on 9/27/13.
*/
public class ListViewFragment extends ListFragment {
final ArrayList<HashMap<String,String>> list = new ArrayList<HashMap<String,String>>();
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.conversations_list_view,
container, false);
setListView set_list = new setListView();
set_list.start();
return view;
}
public void onListItemClick(ListView l, View v, int position, long id) {
//super.onListItemClick(l, v, position, id);
Intent intent = new Intent(getActivity(), ConversationActivity.class);
startActivity(intent);
getActivity().overridePendingTransition(R.anim.in_from_left, R.anim.out_to_right);
}
private class setListView extends Thread {
public void run() {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
setConversations();
}
});
}
}
private void setConversations(){
list.clear();
SimpleAdapter adapter = new SimpleAdapter(
getActivity(),
list,
R.layout.custom_list_main_conversations,
new String[] {"message","date", "reply_count", "stars_count"},
new int[] {R.id.txt_conversation_message,R.id.txt_topic_date, R.id.txt_no_of_reply, R.id.txt_no_of_stars}
);
for(int ctr=0;ctr<=5;ctr++){
Random randomGenerator = new Random();
HashMap<String,String> item_list = new HashMap<String,String>();
item_list.put("message", "This is the conversation number "+(ctr+1)+" and this topic is just a dummy data.");
item_list.put("date", "0"+(ctr+1)+"/0"+(ctr+2)+"/2013 "+(ctr+1)+":00:am");
item_list.put("reply_count", String.valueOf(ctr+randomGenerator.nextInt(10)));
item_list.put("stars_count", String.valueOf(ctr+randomGenerator.nextInt(10)));
list.add(item_list);
}
android.app.ListFragment lf = new android.app.ListFragment();
lf.setListAdapter(adapter);
}
}
You can use ListFragment inside FragmentActivity instead of using a ListActivity.

Categories

Resources