Close Soft Keyboard in Fragment - android-fragments

I have a fragment that has a SearchView. When I click in the search box the keyboard appears. I enter a search term and press "Enter" the keyboard disappears and I get my results page. When I choose an item in my list of results I am taken back to the search fragment and the keyboard reappears. How to I not have the keyboard reappear? Here is part of my code:
public class LocationFragment extends ListFragment implements OnItemLongClickListener, OnClickListener{
// ===========================================================
// Constants
// ===========================================================
private static final int BTN_ID = 0x5f000001;
private static final String DEBUG_TAG = "Tablet/LocationFragment";
// ===========================================================
// Fields
// ===========================================================
private int pos;
private int mPositionToDelete = 0;
private FragmentListener listener;
private Activity mActivity;
// ===========================================================
// Lifecycle
// ===========================================================
#Override
public void onAttach(Activity activity) {
mActivity = activity;
super.onAttach(activity);
try {
listener = (FragmentListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString() + " must implement Fragment");
}
}
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState){
View v = inflater.inflate(R.layout.locations_tile, null);
SearchManager sm = (SearchManager)getActivity().getSystemService(Context.SEARCH_SERVICE);
final SearchView sv = (SearchView)v.findViewById(R.id.search_view);
sv.setSearchableInfo(sm.getSearchableInfo(getActivity().getComponentName()));
sv.setSubmitButtonEnabled(true);
consumeKeyUp(sv);
return v;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
final ListView lv = getListView();
lv.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
lv.setItemChecked(pos, true);
lv.setSelector(R.xml.location_select_gradient);
lv.setCacheColorHint(0x00000000);
lv.setSelector(R.drawable.list_item_selector);
lv.setOnItemLongClickListener(this);
lv.setOnKeyListener(new OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
// TODO Auto-generated method stub
if (event.getAction() == KeyEvent.ACTION_DOWN) {
switch(keyCode) {
case KeyEvent.KEYCODE_DPAD_DOWN:
// Log.i(DEBUG_TAG, "onkeyDown");
return !(lv.getSelectedItemPosition() < lv.getCount() - 1);
case KeyEvent.KEYCODE_DPAD_UP:
// Log.i(DEBUG_TAG, "onkey up");
if(lv.getSelectedItemPosition() == 0) {
// Log.i(DEBUG_TAG, " requesting for search focused");
return LocationFragment.this.getView().findViewById(R.id.search_view).requestFocus();
} else return false;
case KeyEvent.KEYCODE_DPAD_RIGHT:
Log.i(DEBUG_TAG, "KEYCODE_DPAD_RIGHT");
return true;
}
return false;
}
return false;
}
});
ImageView closeBtn = (ImageView) getView().findViewById(R.id.locationsCloseButton);
closeBtn.setOnClickListener(this);
closeBtn.setFocusable(true);
closeBtn.setOnFocusChangeListener(new OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus) {
v.setOnKeyListener(new OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER) {
Log.i(DEBUG_TAG, "keypad Center");
return false;
}
if (event.getAction() == KeyEvent.ACTION_DOWN) {
return !(KeyEvent.KEYCODE_DPAD_DOWN == keyCode);
}
return false;
}
});
} else {
v.setOnKeyListener(null);
}
}
});
}

You could trying clearing the search view focus in your list click callback, e.g. sv.clearFocus()
I grab the search view to do this in OnCreateOptionsMenu using getActionView() on the MenuItem.
Incidentally I also call the following on my search view in onCreateOptionsMenu
final InputMethodManager imm = (InputMethodManager) getActivity().getSystemServiceContext.INPUT_METHOD_SERVICE);
imm.showSoftInput(searchView, InputMethodManager.SHOW_IMPLICIT);
To be honest though I find the whole are of soft input keyboards a bit of a black art

private SearchView mSearchView;
...
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.search_menu, menu);
// Associate search able configuration with the SearchView
android.app.SearchManager searchManager = (android.app.SearchManager) getSystemService(Context.SEARCH_SERVICE);
mSearchView = (SearchView) menu.findItem(R.id.action_search).getActionView();
mSearchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
mSearchView.setIconifiedByDefault(false);
return super.onCreateOptionsMenu(menu);
}
private result() {
mSearchView.clearFocus();
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(searchView.getWindowToken(), 0);
}
don't use startSearch or onSearchRequested

Related

Fragment in ViewPager shows nothing while returning from another fragment

I have a ViewPager in the fragment named FragmentHome, and the viewpager contains fragments. Am using FragmentStatePagerAdapter for this. When the fragmentHome loads first the fragments in Viewpager show perfectly. I have another fragment named FragmentCountryList to select a country, according to that country the fragments in the viewpager to be refreshed/updated. Now The problem is after selecting the country, the country fragment is popped and returns to the FragmentHome, but, there nothing is showing in the view pager, if we scrolls the second page(fragment) can be viewed then scrolls back the first page(fragment) can be viewed.
Am new with the FragmentStatePagerAdapter, so i couldn't rectify the reason for this problem. Please Help. The code i used gives below
public class FragmentHome extends WeGrabBaseFragment {
private static String TAG = "FragmentHome";
private HomeDealsDataClass homeDealsDataClass;//1, homeDealsDataClass2;
private ViewPager viewPagerHome;
private ImageView imgViewDealIndicator;
private OnCitySelectedListener onCitySelectedListener;
private FragPageAdapter fragAdapt;
private ArrayList<HomeDealsDataClass> arrayListHomeData;
private FragmentHomeDetails fragmentHomeDetails1,fragmentHomeDetails2;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Activity = (WeGrabBaseActivity) this.getActivity();
}
#Override
public void onResume() {
super.onResume();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater
.inflate(R.layout.fragment_home, container, false);
((WeGrabMainActivity) Activity).showBottomBar();
((WeGrabMainActivity) Activity).setShowActionBar();
((WeGrabMainActivity) Activity).setHeading(PrefUtil.getCityName(Activity));
((WeGrabMainActivity) Activity).defaultButtonState();
viewPagerHome = (ViewPager) v.findViewById(R.id.viewPagerHome);
viewPagerHome.setOffscreenPageLimit(2);
imgViewDealIndicator = (ImageView) v.findViewById(R.id.imgViewDealIndicator);
Picasso.with(Activity).load(R.drawable.deals1).into(imgViewDealIndicator);
viewPagerHome.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
if (position == 0) {
Picasso.with(Activity).load(R.drawable.deals1).into(imgViewDealIndicator);
} else if (position == 1) {
Picasso.with(Activity).load(R.drawable.deals2).into(imgViewDealIndicator);
}
}
#Override
public void onPageSelected(int position) {
fragAdapt.notifyDataSetChanged();
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
onCitySelectedListener = new OnCitySelectedListener() {
#Override
public void onCitySelected() {
fetchFromWeb();
}
};
fetchFromWeb();
return v;
}
private void fetchFromWeb() {
if (Activity.isNetworkAvailable()) {
if (VolleyUtils.volleyEnabled) {
Activity.startSpinwheel(false, true);
JSONObject jsonObject = new JSONObject();
try {
if (!PrefUtil.isGPSLocation(Activity)) {
jsonObject.putOpt(AppConstants.COUNTRY_ID, PrefUtil.getCountryCode(Activity));
jsonObject.putOpt(AppConstants.CITY_ID, PrefUtil.getCityCode(Activity));
Log.e(TAG, "Not GPS Home : " + jsonObject.toString());
CommandFactory commandFactory = new CommandFactory();
commandFactory.sendPostCommand(
AppConstants.WEGRAB_HOME_URL, jsonObject);
} else {
/*jsonObject.putOpt(AppConstants.COUNTRY_NAME, PrefUtil.getCountryName(Activity));
jsonObject.putOpt(AppConstants.CITY_NAME, PrefUtil.getCityName(Activity));*/
jsonObject.putOpt(AppConstants.COUNTRY_ID, "112");
jsonObject.putOpt(AppConstants.CITY_ID, "6");
CommandFactory commandFactory = new CommandFactory();
Log.e(TAG, "In GPS Home : " + jsonObject.toString());
/*commandFactory.sendPostCommand(
AppConstants.WEGRAB_HOME_URL_GPS, jsonObject);*/
commandFactory.sendPostCommand(
AppConstants.WEGRAB_HOME_URL, jsonObject);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
#Override
public void onHomeDetailsPageDataLoadedSuccessfully(JSONObject jsonObject) {
super.onHomeDetailsPageDataLoadedSuccessfully(jsonObject);
Activity.stopSpinWheel();
try {
if (jsonObject != null) {
if (jsonObject != null) {
fragAdapt = new FragPageAdapter(getFragmentManager());
viewPagerHome.setAdapter(fragAdapt);
JSONArray jsonArray = jsonObject.getJSONArray(AppConstants.DEALS);
arrayListHomeData = new ArrayList<HomeDealsDataClass>();
if(jsonArray.length() > 0) {
viewPagerHome.setVisibility(View.VISIBLE);
for (int i = 0; i < jsonArray.length(); i++) {
arrayListHomeData.add(new HomeDealsDataClass(jsonArray.getJSONObject(i)));
}
fragAdapt.notifyDataSetChanged();
}else{
viewPagerHome.setVisibility(View.GONE);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onHomeDetailsPageDataLoadedFailed(JSONObject jsonObject) {
super.onHomeDetailsPageDataLoadedFailed(jsonObject);
Activity.stopSpinWheel();
}
private class FragPageAdapter extends FragmentStatePagerAdapter {
FragPageAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int pos) {
switch (pos) {
case 0:
Log.e(TAG,"Returns Fragment Home deals 1");
fragmentHomeDetails1 = FragmentHomeDetails.newInstance(arrayListHomeData.get(0));
return fragmentHomeDetails1;
case 1:
Log.e(TAG,"Returns Fragment Home deals 2");
fragmentHomeDetails2 = FragmentHomeDetails.newInstance(arrayListHomeData.get(1));
return fragmentHomeDetails2;
default:
return null;
}
}
#Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
#Override
public int getCount() {
if(arrayListHomeData != null)
return arrayListHomeData.size();
else
return 0;
}
}
}
I had this problem too before, after searching through SO answers, this helped me.
Basically try changing your PagerAdapter to extend FragmentStatePagerAdapter from FragmentPagerAdapter

How to load Different adapters on same listview on Button Click-[Android]?

My requirement is to load different adapters on same listview using buttons to switch between adapters.
I've tried this
public class MainActivity extends ActionBarActivity implements View.OnClickListener {
ImageButton fo,fl,ci,ani;
ListView l;
String flo[],foo[],cit[],an[];
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String flo[] = {"Rose","Lily","SunFlower","Lotus","Tulips"};
String foo[] = {"Maggie","Manchurian","Pizza","Burger","French Fries"};
String cit[] = {"New York","Los Angeles","Las Vegas","Texas","Manhattan"};
String an[] = {"Lion","Tiger","Penguins","Panda","Elephant"};
fo = (ImageButton)findViewById(R.id.imageButton2);
fl = (ImageButton)findViewById(R.id.imageButton);
ci = (ImageButton)findViewById(R.id.imageButton3);
ani = (ImageButton)findViewById(R.id.imageButton4);
l =(ListView)findViewById(R.id.listView);
fo.setOnClickListener(this);
fl.setOnClickListener(this);
ci.setOnClickListener(this);
ani.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if (v.getId()==R.id.imageButton2)
{
food f = new food(this,foo);
l.setAdapter(f);
}
}
}
And I'm getting the following Error:
FATAL EXCEPTION: main
Process: com.example.nike.assignmentadapter, PID: 2565
java.lang.NullPointerException: Attempt to get length of null array
at com.example.nike.assignmentadapter.food.getCount(food.java:41)
at android.widget.ListView.setAdapter(ListView.java:487)
at com.example.nike.assignmentadapter.MainActivity.onClick(MainActivity.java:74)
at android.view.View.performClick(View.java:4756)
at android.view.View$PerformClick.run(View.java:19749)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Food class
public class food extends BaseAdapter implements View.OnClickListener {
String s[];
Context c;
Button li;
Button sh ;
int a[] = {R.drawable.fl1,R.drawable.fl2,R.drawable.fl3,R.drawable.fl4,R.drawable.fl5};
public food(Context context, String[] xperia) {
s = xperia;
c = context;
}
#Override
public int getCount() {
return s.length;
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return s.length;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater ln = (LayoutInflater) c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = ln.inflate(R.layout.food, null);
TextView t= (TextView)v.findViewById(R.id.textView4);
ImageView i = (ImageView)v.findViewById(R.id.imageView4);
li = (Button)v.findViewById(R.id.like4);
sh = (Button)v.findViewById(R.id.share4);
String s1=s[position];
t.setText(s1);
i.setImageResource(a[position]);
li.setOnClickListener(this);
sh.setOnClickListener(this);
return v;
}
#Override
public void onClick(View v) {
if(v.getId()==R.id.like4)
{
AlertDialog.Builder builder= new AlertDialog.Builder(c);
builder.setTitle("Thanks Note");
builder.setMessage("Thank you for Liking ");
builder.setIcon(R.drawable.foo_t);
builder.setPositiveButton("To Share", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User clicked OK button
Uri webpage = Uri.parse("http://www.sonymobile.com");
Intent webIntent = new Intent(Intent.ACTION_VIEW, webpage);
c.startActivity(webIntent);
}
});
builder.show();
}
else
{
AlertDialog.Builder builder= new AlertDialog.Builder(c);
builder.setTitle("Thanks Note");
builder.setMessage("Thank you for Sharing on Your Facebook");
builder.setIcon(R.drawable.foo_t);
builder.setPositiveButton("To Facebook", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User clicked OK button
Uri webpage = Uri.parse("https://www.facebook.com");
Intent webIntent = new Intent(Intent.ACTION_VIEW, webpage);
c.startActivity(webIntent);
}
});
builder.show();
}
}
}
public class MainActivity extends ActionBarActivity implements OnClickListener {
ImageButton fo,fl,ci,ani;
ListView l;
String flo[],foo[],cit[],an[];
// these are your global variables available to access
// in any part of the coding. Currently they have no
// data assigned to them in other words they are null
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// here we have assigned data to the global variables declared
// outside of the OnCreate function and available to the onClick
// call.
// Using String flo[] = {John, Doe} means you are creating
// new local versions of the String arrays that are not available
// globally. Instead of assigning the data to the variables
// available globally, and to the onClick call, the data is given
// to the local variables only accessible in the OnCreate function
// function and available until OnCreate finishes.
flo = new String[]{"Rose","Lily","SunFlower","Lotus","Tulips"};
foo = new String[]{"Maggie","Manchurian","Pizza","Burger","French Fries"};
cit = new String[]{"New York","Los Angeles","Las Vegas","Texas","Manhattan"};
an = new String[]{"Lion","Tiger","Penguins","Panda","Elephant"};
fo = (ImageButton)findViewById(R.id.imageButton1);
l =(ListView)findViewById(R.id.listView1);
fo.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if (v.getId()==R.id.imageButton1)
{
System.out.println("foo: " + foo);
food f = new food(this,foo);
l.setAdapter(f);
}
}
#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;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}

Android annotations #afterviews called multiple times when fragment added

I have a fragment that whenever it is added to the layout #afterviews is called.
So for example in the parent activity I check if the fragment has been created, if not inflate it. Then I check if the fragment is added to the layout, if not add it and show the new fragment
#Click(R.id.tvActionFriends)
void friendsClicked() {
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
if (friendsFragment == null) {
friendsFragment = new FriendsFragment_();
}
if (!friendsFragment.isAdded()) {
app.log("not added adding fragment");
fragmentTransaction.add(R.id.layoutMainContainer, friendsFragment);
}
fragmentTransaction.show(friendsFragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
The first time its clickd it goes through the lifecycle normally.
So now the user has pressed the back button I can see the teardown onPause() onDestroy() and onDetach()
So now the friendsFragment is removed from the layout but the class still exists.
Now the user clicks on a button again to show the friendsFragment, in the host activity. This time the fragment already exists but is not in layout so it is re added and transaction commits
now the fragment goes through the lifecycle of creation but #afterviews method is triggered twice, if a user hits back again and clicks the button a third time #afterviews will be triggered 3 times etc...
Here is the friendsFragment
#EFragment(R.layout.fragment_friends)
public class FriendsFragment extends BaseFragment {
ArrayList<String> numbers, facebookIds, emails;
ArrayList<Friend> friends;
#Bean
FriendsAdapter friendsAdapter;
#ViewById(R.id.lvFriends)
CustomListView lvFriends;
boolean gettingFriends = false;
#AfterInject
void initInject() {
super.baseInject();
numbers = new ArrayList<String>();
facebookIds = new ArrayList<String>();
friends = new ArrayList<Friend>();
friendsAdapter.setItems(friends);
}
#AfterViews
void initViews() {
super.baseViews();
lvFriends.setAdapter(friendsAdapter);
Cursor phones = getActivity().getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null, null, null, null);
while (phones.moveToNext()) {
String name = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String phoneNumber = phones.getString(phones
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NORMALIZED_NUMBER));
if (phoneNumber != null) {
phoneNumber = phoneNumber.replace("+", "");
numbers.add(phoneNumber);
}
}
phones.close();
getFriends();
}
OnFriendsListener onFriendsListener = new OnFriendsListener() {
#Override
public void onComplete(List<Profile> friends) {
for (Profile p : friends) {
app.log(p.getName());
}
}
#Override
public void onException(Throwable throwable) {
app.log(throwable.getMessage());
};
#Override
public void onFail(String reason) {
app.log(reason);
}
};
#Background
void getFriends() {
if (gettingFriends == true)
return;
gettingFriends = true;
friends.clear();
MultiValueMap<String, String> data = new LinkedMultiValueMap<String, String>();
data.add("numbers", numbers.toString());
data.add("facebook_ids", facebookIds.toString());
ArrayList<Friend> resp = snapClient.recommendFriends(data);
friendsCallback(resp);
}
#UiThread
void friendsCallback(ArrayList<Friend> resp) {
if (resp != null)
friends.addAll(resp);
friendsAdapter.notifyDataSetChanged();
gettingFriends = false;
}
}
As you can see the fragment extends a basefragment and calls the parent super.baseInject() and super.baseViews() to handle common class fields across all fragments
the base fragment looks like this, it basically just injects a few classes and logs the activity lifecycle of the fragment
#EFragment
public class BaseFragment extends Fragment {
#App
MyApp app;
#SystemService
LayoutInflater layoutInflater;
#Bean
VideoCache videoCache;
#RestService
CloudClient cloudClient;
#Bean
MyResources myResources;
#ViewById(R.id.tvActionExtra)
TextView tvActionExtra;
SnapClient snapClient;
FragmentManager fragmentManager;
SimpleFacebook simpleFacebook;
void baseInject() {
app.log("init inject " + this.getClass().getCanonicalName());
app.currentContext = getActivity();
snapClient = app.snapClient;
}
void baseViews() {
app.log("init views " + this.getClass().getCanonicalName());
}
#Override
public void onAttach(Activity activity) {
Log.d(MyApp.TAG,"attach " + this.getClass().getCanonicalName());
super.onAttach(activity);
if (activity instanceof MainActivity) {
try {
MainActivity a = (MainActivity) activity;
simpleFacebook = a.simpleFacebook;
}
catch (Exception e) {
e.printStackTrace();
}
}
}
void toast(String message) {
app.toast(message);
}
AlertDialog simpleAlert(String title, String message) {
return MyApp.simpleAlert(getActivity(), title, message);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(MyApp.TAG,"create " + this.getClass().getCanonicalName());
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
Log.d(MyApp.TAG,"create view " + this.getClass().getCanonicalName());
return super.onCreateView(inflater, container, savedInstanceState);
}
#Override
public void onPause() {
Log.d(MyApp.TAG,"pause" + this.getClass().getCanonicalName());;
super.onPause();
}
#Override
public void onResume() {
Log.d(MyApp.TAG,"resume " + this.getClass().getCanonicalName());
super.onResume();
}
#Override
public void onDetach() {
Log.d(MyApp.TAG,"detach " + this.getClass().getCanonicalName());
super.onDetach();
}
#Override
public void onDestroy() {
Log.d(MyApp.TAG,"destroy " + this.getClass().getCanonicalName());
super.onDestroy();
}
}
I dont' know if its an android annotation thing im messing up or something with the fragments, any help is appreciated.
It looks like this may be fixed in AndroidAnnotations 3.3?
There was a pull request at https://github.com/excilys/androidannotations/pull/1275, based on an issue at https://github.com/excilys/androidannotations/issues/1264.

Trying to implement swipe movement

public class CoursesActivity extends SherlockFragmentActivity {
ArrayList<CourseData> mCoursesList = new ArrayList<CourseData>();
public CoursesListAdapter coursesListAdapter;
public ListView mList;
public AlertDialog.Builder dlgAlert;
public Dialog loginDialog;
public Dialog loginDialogOverflow;
LinearLayout progressBar;
static SQLiteWebcourse dbHelper;
private GestureDetectorCompat mDetector;
public final static String EXTRA_MESSAGE = "com.technion.coolie.webcourse.MESSAGE";
public CoursesActivity() {
dbHelper = new SQLiteWebcourse(this, "WebcoureDB", null, 1);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Create list of courses
mCoursesList = new ArrayList<CourseData>();
setContentView(R.layout.web_activity_courses);
mList = (ListView) findViewById(R.id.courses_list);
dlgAlert = new AlertDialog.Builder(getApplicationContext());
if (!CoolieAccount.WEBCOURSE.isAlreadyLoggedIn()) {
loginDialog = CoolieAccount.WEBCOURSE.openSigninDialog(this);
OnDismissListener dismissListener = new OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialog) {
// Check if connection success
if (CoolieAccount.WEBCOURSE.isAlreadyLoggedIn()) {
// Connection SUCCESS
progressBar = (LinearLayout) findViewById(R.id.progressBarLayout_courses);
progressBar.setVisibility(View.VISIBLE);
asyncParse<CourseData> a = new asyncParse<CourseData>() {
#Override
protected List<CourseData> doInBackground(
String... params) {
// TODO Auto-generated method stub
try {
courseList crL = new courseList(
getApplicationContext());
crL.getCourses(CoolieAccount.WEBCOURSE
.getUsername(),
CoolieAccount.WEBCOURSE
.getPassword());
mCoursesList = dbHelper
.getAllCourses(CoolieAccount.WEBCOURSE
.getUsername());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return super.doInBackground(params);
}
#Override
protected void onPostExecute(List<CourseData> result) {
// TODO Auto-generated method stub
CoursesListAdapter coursesListAdapter = new CoursesListAdapter(
getApplicationContext(), mCoursesList);
mList.setAdapter(coursesListAdapter);
mList.setBackgroundColor(0xFFF0F0F0);
progressBar.setVisibility(View.INVISIBLE);
super.onPostExecute(result);
}
};
a.execute("");
} else {
// Connection FAILED
Log.v("dbAss", "Second Time");
}
}
};
loginDialog.setOnDismissListener(dismissListener);
} else {
mCoursesList = dbHelper.getAllCourses(CoolieAccount.WEBCOURSE
.getUsername());
CoursesListAdapter coursesListAdapter = new CoursesListAdapter(
getApplicationContext(), mCoursesList);
mList.setAdapter(coursesListAdapter);
mList.setBackgroundColor(0xFFF0F0F0);
}
Log.v("Gestures", "OnTouchEvent#!$#%##%^&^$%");
// OnItemClickListener itemClicked = new OnItemClickListener() {
//
// #Override
// public void onItemClick(AdapterView<?> list, View view,
// int position, long id) {
// // TODO Auto-generated method stub
// loadCourseInformationActivity(((CourseData) mList
// .getItemAtPosition(position)).CourseDescription);
// }
// };
// mList.setOnItemClickListener(itemClicked);
mDetector = new GestureDetectorCompat(this, new MyGestureListener());
}
#Override
public boolean onTouchEvent(MotionEvent event) {
Log.v("Gestures", "OnTouchEvent#!$#%##%^&^$%");
this.mDetector.onTouchEvent(event);
// Be sure to call the superclass implementation
return super.onTouchEvent(event);
}
class MyGestureListener extends GestureDetector.SimpleOnGestureListener {
private static final String DEBUG_TAG = "Gestures";
#Override
public boolean onFling(MotionEvent event1, MotionEvent event2,
float velocityX, float velocityY) {
Log.v(DEBUG_TAG,
"onFling: " + event1.toString() + event2.toString());
Toast.makeText(getApplicationContext(), "SWIPED", Toast.LENGTH_LONG)
.show();
if (event2.getX() - event1.getX() > SWIPE_MIN_DISTANCE
&& Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY)
Toast.makeText(getApplicationContext(), "SWIPED",
Toast.LENGTH_LONG).show();
// if (showDeleteButton(e1))
// return true;
return super.onFling(event1, event2, velocityX, velocityY);
}
}
}
Hey fellas, i'm trying to implement swipe detection I went through android lesson and did exactly what is written there: http://developer.android.com/training/gestures/detector.html
For some reason when I touch the screen it doesnt go to onTouchEvent. What seems to be the problem?
You haven't set the touch listener to your ListView.
listView.setOnTouchListener(this);

Saving GridView state in a Fragment (Android) on Back Button

In my android application, I am switching between the two set of images-(Set1, Set2) displayed in a GridView-A inside a Fragment-A.I am doing this on a button press using a boolean variable. Clicking on any GridView icon leads to another Fragment-B. The problem is when I press back button on Fragment-B , the Fragment-A is always loaded with the images of Set1 by default. I want the same set of images (Set1 or Set2 ) to be loaded on FramentA that were displayed before going to FragmentB.
EDITED:
Fragment Code
public class GridViewFragment extends Fragment {
Context context;
GridView GridMenu;
GridViewAdapter ga;
Button Btn_Settings;
Button Btn_lang_Ch;
Button favoriteDuas;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//fragment = new GridViewFragment();
if (view == null) {
context = inflater.getContext();
view = inflater.inflate(R.layout.fragment_gridview, container, false);
ga = new GridViewAdapter(context);
Btn_lang_Ch = (Button) view.findViewById(R.id.lng_ch);
Btn_Settings = (Button) view.findViewById(R.id.button_settings);
favoriteDuas = (Button) view.findViewById(R.id.btn_favorite_duas);
GridMenu = (GridView) view.findViewById(R.id.gridView1);
GridMenu.setAdapter(ga);
} else {
// remove view from previously attached ViewGroup
ViewGroup parent = (ViewGroup) view.getParent();
parent.removeView(view);
}
return view;
}
#Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setRetainInstance(true);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
Btn_lang_Ch.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
ga.changeImages(!ga.imageSetChange);
ga.Lang_Status();
}
});
GridMenu.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View view, int position, long id) {
((MainActivity) context).loadSingleDuaFragment();
}
});
super.onActivityCreated(savedInstanceState);
}
}
GridView Adapter
public class GridViewAdapter extends BaseAdapter {
public boolean imageSetChange = false;
public static boolean curr_lang = false;//english
public Integer[] mThumbIds = {
R.drawable.eng_pic1, R.drawable.eng_pic2,
R.drawable.eng_pic3, R.drawable.eng_pic4,
R.drawable.eng_pic5, R.drawable.eng_pic6,
R.drawable.eng_pic7, R.drawable.eng_pic8,
R.drawable.eng_pic9, R.drawable.eng_pic10,
R.drawable.eng_pic11, R.drawable.eng_pic12,
R.drawable.eng_pic13, R.drawable.eng_pic14,
R.drawable.eng_pic15, R.drawable.eng_pic16,
R.drawable.eng_pic17, R.drawable.eng_pic18,
R.drawable.eng_pic19, R.drawable.eng_pic20,
R.drawable.eng_pic21
};
public Integer[] mThumbIds1 = {
R.drawable.urdu_dua1, R.drawable.urdu_dua2,
R.drawable.urdu_dua3, R.drawable.urdu_dua4,
R.drawable.urdu_dua5, R.drawable.urdu_dua6,
R.drawable.urdu_dua7, R.drawable.urdu_dua8,
R.drawable.urdu_dua9, R.drawable.urdu_dua10,
R.drawable.urdu_dua11, R.drawable.urdu_dua12,
R.drawable.urdu_dua13, R.drawable.urdu_dua14,
R.drawable.urdu_dua15, R.drawable.urdu_dua16,
R.drawable.urdu_dua17, R.drawable.urdu_dua18,
R.drawable.urdu_dua19, R.drawable.urdu_dua20,
R.drawable.urdu_dua21
};
private Context mContext;
public GridViewAdapter(Context c) {
mContext = c;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return mThumbIds.length;
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return mThumbIds[position];
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View MyView;
if (convertView == null) {
LayoutInflater li = ((Activity) mContext).getLayoutInflater();
MyView = li.inflate(R.layout.menuitem, parent, false);
} else {
MyView = (View) convertView;
}
ImageView iv = (ImageView) MyView.findViewById(R.id.image);
if (imageSetChange) {
iv.setImageResource(mThumbIds1[position]);
} else {
iv.setImageResource(mThumbIds[position]);
}
return MyView;
}
public void changeImages(boolean change) {
this.imageSetChange = change;
notifyDataSetChanged();
// gf.Lang_Status();
}
public void Lang_Status() {
// if curr_eng
if (!curr_lang)
this.curr_lang = true; // change to urdu
// if curr_urdu
else
this.curr_lang = false; // change to english
}
}
EDIT:
MainActivity
public void loadGridViewFragment() {
if (activityActive) {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
if(getSupportFragmentManager().findFragmentByTag(GridViewFragment.TAG)!=null){
ft.replace(R.id.fl_view, frag,GridViewFragment.TAG);
}
else
{
frag = new GridViewFragment();
ft.replace(R.id.fl_view, frag,GridViewFragment.TAG);
}
ft.commit();
}
}
So, can anybody help me out regarding what should be done to load the previous set of images on coming back to gridview fragment instead of having the default images of Set1.

Resources