I'm trying to set the initial scroll position in a ListFragment, with no success. I'm trying to do the following:
public abstract class AbstractDiaListFragment extends ListFragment implements LoaderManager.LoaderCallbacks<Cursor> {
(...)
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
ListView mList = this.getListView();
mList.setSelection(position)
}
I've already tried using smoothScrollToPosition, and tried using onViewCreated() instead of onActivityCreated. Am I missing something?
Thanks!
Try using:
mList.post(new Runnable() {
#Override
public void run() {
mList.setSelection(position);
}
});
Related
I have to pass the recycler view item I get from my database to another fragment.
public class FragLoad extends Fragment {
EditText g_type;
EditText l_capacity, date, quotation;
Button search;
RecyclerView recyclerView;
List<RPostLoad> rPostLoads;
SupportPlaceAutocompleteFragment source,destination;
private static final String URL_RecyclerLoad="http://192.168.43.38/internship_project/android_web_services/RecyclerLoad.php";
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.frag_load, container, false);
g_type=view.findViewById(R.id.goodstype);
l_capacity=view.findViewById(R.id.loadCap);
date=view.findViewById(R.id.txtDate);
quotation=view.findViewById(R.id.txtQuotations);
search=view.findViewById(R.id.postSearch);
recyclerView=view.findViewById(R.id.rvload);
recyclerView.setLayoutManager(new LinearLayoutManager(this.getActivity()));
recyclerView.setHasFixedSize(true);
rPostLoads=new ArrayList<>();
source= (SupportPlaceAutocompleteFragment) getChildFragmentManager().findFragmentById(R.id.place_autocomplete_fragment2);
destination= (SupportPlaceAutocompleteFragment) getChildFragmentManager().findFragmentById(R.id.place_autocomplete_fragment1);
search.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
rvLoad();
}
});
return view;
}
private void rvLoad() {
Map<String, String> params = new HashMap<>();
params.put("g_type", g_type.getText().toString());
AndroidNetworking.post("http://192.168.43.38/internship_project/android_web_services/RecyclerLoad.php").addBodyParameter(params).setTag("Login").setPriority(Priority.LOW).build().getAsJSONObject(new JSONObjectRequestListener() {
#Override
public void onResponse(JSONObject response) {
try {
Log.d("TAG", "Response" + response.toString());
JSONArray array=response.getJSONArray("Data");
for (int i=0;i<array.length();i++){
JSONObject product=array.getJSONObject(i);
rPostLoads.add(new RPostLoad(
product.getString("owner_name"),
product.getString("g_type"),
product.getString("truck_cap")
));
}
RPostLoadAdp adp=new RPostLoadAdp(getActivity(),rPostLoads);
recyclerView.setAdapter(adp);
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onError(ANError anError) {
Toast.makeText(getActivity(), "Server time out please try later", Toast.LENGTH_SHORT).show();
}
});
}
}
Above code is of the class from where I get the recycler item from database and need to send the recycler view item to another fragment. The thing is that I am a beginner at android so I have no idea how to send it. The fragment in which I have to receive the recycler item is empty so i didnt post it here.
you have one Activity one Fragment and one RecyclerView
and yor Activity opens Fragment and inside of fragment you implemented the RecylcerView
to communicate between your Activity and RecyclerView you need to have a Listener
create this Interface (listener) :
public interface OnSomeThingHappens {
public void onEvent(); // you can use some argument for the method
}
then in your Activity implement the interface and create a method to your fragment to pass the listener from activity to the fragment and then pass it from fragment to RecyclerView's adapter. your activity will be some thing like this :
public class ActivityMain extends AppCompatActivity implements OnSomeThingHappens{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
YourFragment yourFragment = (YourFragment) getFragmentManager().findFragmentById(R.id.test_fragment);
yourFragment.setOnSomeThingListener(this); // this indication the listener that is implemented in ActivityMain
}
#Override
public void onEvent() {
// to do your logic
}
}
and in your Fragment when you implement RPostLoadAdp send the listener object adapter to the adapter using a setter method in adapter.
then you will have access to the listener and when you want you can call the onEvent() method of listener and in ActivityMain the method will be called.
now you can do your logic in this method in ActivityMain (send some data to other fragment or ..)
hope this help.
I am a beginner in stack-overflow and this is my first question,that i cant solve that. so before every thing excuse me if I don't know more about this site.
The question is:
I want click on a specific view of one item of recyclerView adapter from activity and not from own adapter, some thing like implement on-click from adapter to activity that called this adapter.
thanks for reading this unclear text :)
If I understand correctly you can obtain your goal by using an interface.
Your adapter should contain an instance of a listener for your click event.
public class MyAdapter extends RecyclerView.Adapter {
OnAdapterClickListener onAdapterClickListener;
public MyAdapter(OnAdapterClickListener onAdapterClickListener) {
this.onAdapterClickListener = onAdapterClickListener;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(onAdapterClickListener != null) {
onAdapterClickListener.onViewClicked(view);
}
}
});
}
}
The interface should be something like this:
public interface OnAdapterClickListener {
void onViewClicked(View view);
}
And finally your activity has to implement the interface:
public class MainActivity implements OnAdapterClickListener {
private MyAdapter myAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myAdapter = new MyAdapter(this);
}
#Override
public void onViewClicked(View view) {
}
}
Now you can implement your OnClickListener in your Activity.
I have read some similar questions and and i have tried to get it work but i can't understand why my adapter is not updating my recyclerview after return from my SaveItem activity. So i have two tabs: ALL notes and Favourite notes. To be more specific: App image
.
When i press the floating action button from the bottom it starts a new activity where i can record a new note, but when i return to MainActivity the first fragment it's not updating my recyclerview:
Here is where I fill my adapter:
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
adapter = new NoteAdapter(fillAdapter(),this,getActivity());
recycler.setAdapter(adapter);
recycler.setLayoutManager(new LinearLayoutManager(getActivity(),LinearLayoutManager.VERTICAL,false));
}
Here is where I try to update my recyclerview:
#Override
public void onResume() {
super.onResume();
adapter.addAll(fillAdapter());
recycler.setAdapter(adapter);
}
Here is my addAll method:
public class NoteAdapter extends RecyclerView.Adapter<NoteAdapter.ViewHolderNote> {
// Other codes....
public void addAll(List<Note> newNotes) {
this.notes.clear();
this.notes.addAll(newNotes);
this.notifyDataSetChanged();
}
}
Take a list of Note in your Fragment class.
private List<Note> allNotes;
Then inside your onActivityCreated
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
allNotes = fillAdapter();
adapter = new NoteAdapter(allNotes, this, getActivity());
recycler.setAdapter(adapter);
recycler.setLayoutManager(new LinearLayoutManager(getActivity(),LinearLayoutManager.VERTICAL,false));
}
Now to update your list call the fillAdapter function again to popuate the allNotes list again and modify your onResume like this.
#Override
public void onResume() {
super.onResume();
allNotes = fillAdapter();
adapter.notifyDatasetChanged();
}
The addAll function has no necessity right now. Remove the function from your NoteAdapter.
The key thing is the reference of your list which is being passed to the adapter.
I have a ListView in my activity.On clicking on the list item it invokes another activity.In that activity I have implemented ViewPager and fragments.
When it loads first time onResume() ,onCreate() and onCreateView() method called twice, if I clicks on first list item. (i.e. it loads first and second fragment view)
when I click on the any other List fragment except first then it calls onResume() ,onCreate() and onCreateView() methods three times (i.e. It loads previous and after and click view )
It is absoutely fine but I have google analytics code with which I have to track only current page so where I can put this code to load for only current page
My question is my googleAnalytics code tracs three or two pages at first time even user doesnot gone through those pages how to avoid this ?
My code is as below for fragment
public class MainListActivity extends Activity{
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.v(TAG, "onCreate()");
CustomFragmentPagerAdapter adapter = new CustomFragmentPagerAdapter();
viewPager.setAdapter(adapter);
}
}
//code for fragment adapter
public class CustomFragmentPagerAdapter extends FragmentPagerAdapter {
public CustomFragmentPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int pos) {
CustomFragment customFragment = new CustomFragment();
arrayList.add(customFragment);
return customFragment;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return arrayList.size();
}
}
//code for fragment
public class CustomFragment extends Fragment{
public CustomFragment() {
super();
}
#Override
public void onResume() {
super.onResume();
Log.v(TAG, "onCreate -Resume");
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.v(TAG, "onCreate");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
Log.v(TAG, "onCreateView");
return myAnyView;
}
}
The problem is that the onResume() method is called for all your fragments, that is including the invisible ones.
Check gorn's answer here:
How to determine when Fragment becomes visible in ViewPager
You have to override
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (isVisibleToUser) {
// Your logic
}
and do your logic in there.
How can I create a pull down to refresh list in android?
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.pull_to_refresh);
// Set a listener to be invoked when the list should be refreshed.
((PullToRefreshListView) getListView()).setOnRefreshListener(new OnRefreshListener() {
#Override
public void onRefresh() {
// Do work to refresh the list here.
new GetDataTask().execute();
}
});
mListItems = new LinkedList<String>();
mListItems.addAll(Arrays.asList(mStrings));
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, mListItems);
setListAdapter(adapter);
}`
This is not an android design pattern. However, this excellent library lets you do it easily. Have a look at the examples.
Hope I helped.
Edit -- 12/06/2015 -- Disregard the previous statement:
This is now a design pattern that is fully supported by the SDK on Android.
It is very simple, you need to use a SwipeRefreshLayout as the parent view to your list (or other data you might want to refresh). You can put any view as a child, it will create a Pull-To-Refresh animation for that view.
Aftewards, you just need to implement SwipeRefreshLayout.OnRefreshListener to handle the network code of the actual data refresh:
public class MainActivity extends FragmentActivity implements OnRefreshListener {
private SwipeRefreshLayout _pullToRefreshLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.activity_main);
_pullToRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_layout);
_pullToRefreshLayout.setOnRefreshListener(this);
super.onCreate(savedInstanceState);
}
#Override
public void onRefresh() {
//When this is called, your view has a little loader showing to show the user that a network call is in progress
Log.i("SO17065814", "Starting refresh...");
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
mSwipeRefreshLayout.setRefreshing(false); //This stops the refresh animation
Log.i("SO17065814", "Ending refresh...");
}
}, 5000);
}
}