[q][Solved]Using viewpager inside a fragment - Java for Android App Development

i am using view pager inside a fragment.
Code:
public class TabFragment extends android.support.v4.app.Fragment
{List fragments = new Vector();
PagerAdapter mSectionsPagerAdapter;
ViewPager mViewPager;
[user=439709]@override[/user]
public View onCreateView (LayoutInflater inflater , ViewGroup container ,
Bundle savedInstanceState) {
ViewGroup rootView = (ViewGroup ) inflater .inflate(
R . layout.tabfragment , container , false );
mSectionsPagerAdapter = new ScreenSlidePagerAdapter (getActivity().getSupportFragmentManager ());
mViewPager = (ViewPager) rootView.findViewById(R.id.pager);
setHasOptionsMenu(true);
add();
mViewPager.setAdapter(mSectionsPagerAdapter);
return rootView ;
}
private class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter
{
[user=439709]@override[/user]
public CharSequence getPageTitle(int position)
{Main ma=((Main)fragments.get(mViewPager.getCurrentItem()));
return ma.current;
}
public int getCount()
{
// TODO: Implement this method
return fragments.size();
}
public ScreenSlidePagerAdapter ( android.support.v4.app.FragmentManager fm ) {
super ( fm);
} [user=439709]@override[/user]
public android.support.v4.app.Fragment getItem ( int position ) {
android.support.v4.app.Fragment f;
f= fragments.get(position);
return f;
}
}
public void add(){
android.support.v4.app.Fragment main=new Main();
Bundle b=new Bundle();
int p=fragments.size();
b.putString("name","");
if(p==0){
b.putInt("pos",1);}
else{
b.putInt("pos",p);}
main.setArguments(b);
fragments.add(main);
mSectionsPagerAdapter.notifyDataSetChanged();
mViewPager.setCurrentItem(p);
}
public void remove(){
int pos=mViewPager.getCurrentItem();
if(pos

Related

[q][solved]View Pager doesnt adds fragments to backstack

i have made a fragment which contains view pager.it uses list of fragments so that fragments can be added or removed dynamically.
each child fragment of viewpager is a listfragment and loads list using asynctask
now my problem is when i have 3-4 child fragments in view pager,after switching to other pages(tabs),the earlier ones in which list is already loaded are reset automatically when i swipe back to them.so i want that they must be added to backstact so that they can be resumed.
Code:
public class TabFragment extends android.support.v4.app.Fragment {
List fragments = new ArrayList();
public PagerAdapter mSectionsPagerAdapter;
ViewPager mViewPager;
String home;
ActionBar actionBar;
[user=439709]@override[/user]
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.tabfragment,
container, false);
mSectionsPagerAdapter = new ScreenSlidePagerAdapter(getChildFragmentManager());
mViewPager = (ViewPager) rootView.findViewById(R.id.pager);
actionBar = getActivity().getActionBar();
mViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
public void onPageScrolled(int p1, float p2, int p3) {
// TODO: Implement this method
}
public void onPageSelected(int p1) { // TODO: Implement this// method
Main ma = ((Main) fragments.get(p1));
if (ma.current != null) {
ma.bbar(ma.current);
}
}
public void onPageScrollStateChanged(int p1) {
// TODO: Implement this method
}
});
mViewPager.setAdapter(mSectionsPagerAdapter);
return rootView;
}
private class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter {
[user=439709]@override[/user]
public CharSequence getPageTitle(int position) {
//Toast.makeText(getActivity(),""+position,Toast.LENGTH_SHORT).show();
Main ma = ((Main) fragments.get(position));
return new File(ma.current).getName();
}
public int getCount() {
// TODO: Implement this method
return fragments.size();
}
public ScreenSlidePagerAdapter(android.support.v4.app.FragmentManager fm) {
super(fm);
}
[user=439709]@override[/user]
public android.support.v4.app.Fragment getItem(int position) {
android.support.v4.app.Fragment f;
f = fragments.get(position);
return f;
}
}
public void removePage(int position) {
if(position==0){Toast.makeText(getActivity(),"Main Screen Cant be removed",Toast.LENGTH_LONG).show();}else{
fragments.remove(position);
mSectionsPagerAdapter.notifyDataSetChanged();
mViewPager.setCurrentItem(position-1);
}
}
public void add(String text) {
android.support.v4.app.Fragment main = new Main();
Bundle b = new Bundle();
int p = fragments.size();
b.putString("path", text);
b.putInt("pos", p);
main.setArguments(b);
fragments.add(main);
mSectionsPagerAdapter.notifyDataSetChanged();
mViewPager.setCurrentItem(p);
}

[Q] GPS with Fragment

Good day. I start learn Fragment and I want use GPS in my Application. and I use Fragment. in fragment who view coordinate i writed next code
Code:
public class MyFragment2 extends Fragment {
public static final String BUTTON_INDEX = "button_index";
private static final int BUTTON_INDEX_DEFAULT = -1;
static TextView txt;
static TextView txt2;
String[] mCatDescription;
public View onCreateView (LayoutInflater inflater, ViewGroup container, Bundle saveInstanceState){
View viewHier = inflater.inflate(R.layout.fragment2, container, false);
txt = (TextView)viewHier.findViewById(R.id.textView1);
txt2 = (TextView)viewHier.findViewById(R.id.textView2);
mCatDescription =getResources().getStringArray(R.array.cats);
Bundle args = getArguments();
int buttonIndex = args != null ? args.getInt(BUTTON_INDEX, BUTTON_INDEX_DEFAULT):BUTTON_INDEX_DEFAULT;
if(buttonIndex != BUTTON_INDEX_DEFAULT){
setDiscription(buttonIndex);
}
return viewHier;
}
public void setDiscription(int buttonIndex){
GPSWork gpsWork = new GPSWork();
switch(buttonIndex){
case 1:
txt2.setText("one");
break;
case 2:
gpsWork.GetCoordinates();
break;
case 3:
txt2.setText("therd");
break;
}
}
}
Ok. when we click on button 2 we call method GetCoordinates(). this class have next code
Code:
public class GPSWork{
LocationManager locationManager;
public GPSWork(){
locationManager = (LocationManager)MainActivity.mContext.getSystemService(Context.LOCATION_SERVICE);
}
public void GetCoordinates(){
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
5000, 5, locationListener);
}
private LocationListener locationListener = new LocationListener() {
@Override
public void onLocationChanged(Location location) {
MyFragment2.txt2.setText("OK");
}
@Override
public void onProviderDisabled(String provider) {
MyFragment2.txt2.setText("OK");
}
@Override
public void onProviderEnabled(String provider) {
MyFragment2.txt2.setText("OK");
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
MyFragment2.txt2.setText("OK");
}
};
}
how we see, we should get text OK on TextView on MainActivity. but we don't have text, whats wrong? and if I change code in method GetCoordinates() on
Code:
public void GetCoordinates(){
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,
1000, 10, locationListener);
}
all work fine, i see text in TextView (OK )

Passing data between two fragments

Hello guys,
I have a list of fragments created and I want to delete these fragment by long pressing on them. However, before doing so I want dialog fragment to pop up and offer the user the choice to delete or not. I have created the two fragments but I can't get the data across each other. I can't give functionality to the 'OK' button. Here is my code:
Code:
public class CourseListFragment extends Fragment implements
OnItemClickListener, OnItemLongClickListener {
public static final String ARG_ITEM_ID = "course_list";
public static final String YES_NO = "modify";
Activity activity;
ListView courseListView;
ArrayList<Course> courses;
CourseListAdapter courseListAdapter;
CourseDAO courseDAO;
private GetEmpTask task;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
activity = getActivity();
courseDAO = new CourseDAO(activity);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.schedule_fragment_course_list,
container, false);
findViewsById(view);
task = new GetEmpTask(activity);
task.execute((Void) null);
courseListView.setOnItemClickListener(this);
courseListView.setOnItemLongClickListener(this);
return view;
}
private void findViewsById(View view) {
courseListView = (ListView) view.findViewById(R.id.list_course);
}
@Override
public void onItemClick(AdapterView<?> list, View view, int position,
long id) {
Course course = (Course) list.getItemAtPosition(position);
if (course != null) {
Bundle arguments = new Bundle();
arguments.putParcelable("selectedCourse", course);
CustomCourseDialogFragment customEmpDialogFragment = new CustomCourseDialogFragment();
customEmpDialogFragment.setArguments(arguments);
customEmpDialogFragment.show(getFragmentManager(),
CustomCourseDialogFragment.ARG_ITEM_ID);
}
}
@Override
public boolean onItemLongClick(AdapterView<?> parent, View view,
int position, long id) {
// Show dialogFragment
FragmentManager fm = getActivity().getSupportFragmentManager();
CheckDialogFragment dialog = new CheckDialogFragment();
dialog.show(fm, YES_NO);
Course employee = (Course) parent.getItemAtPosition(position);
// Use AsyncTask to delete from database
courseDAO.deleteEmployee(employee);
courseListAdapter.remove(employee);
return true;
}
public class GetEmpTask extends AsyncTask<Void, Void, ArrayList<Course>> {
private final WeakReference<Activity> activityWeakRef;
public GetEmpTask(Activity context) {
this.activityWeakRef = new WeakReference<Activity>(context);
}
@Override
protected ArrayList<Course> doInBackground(Void... arg0) {
ArrayList<Course> courseList = courseDAO.getCourses();
return courseList;
}
@Override
protected void onPostExecute(ArrayList<Course> empList) {
if (activityWeakRef.get() != null
&& !activityWeakRef.get().isFinishing()) {
courses = empList;
if (empList != null) {
if (empList.size() != 0) {
courseListAdapter = new CourseListAdapter(activity,
empList);
courseListView.setAdapter(courseListAdapter);
} else {
Toast.makeText(activity, "No Course Records",
Toast.LENGTH_LONG).show();
}
}
}
}
}
/*
* This method is invoked from MainActivity onFinishDialog() method. It is
* called from CustomEmpDialogFragment when an employee record is updated.
* This is used for communicating between fragments.
*/
public void updateView() {
task = new GetEmpTask(activity);
task.execute((Void) null);
}
@Override
public void onResume() {
getActivity().setTitle("Course Schedule");
getActivity().getActionBar().setTitle("Course Schedule");
super.onResume();
}
}
//Dialog Fragment
Code:
public class CheckDialogFragment extends DialogFragment {
CourseListAdapter courseListAdapter;
CourseDAO courseDAO;
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// TODO Auto-generated method stub
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity())
.setTitle("Do you want to delete?")
.setPositiveButton(android.R.string.ok,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int which) {
// TODO Auto-generated method stub
}
})
.setNegativeButton(android.R.string.cancel,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int which) {
// TODO Auto-generated method stub
dialog.cancel();
}
});
return builder.create();
}
}
I have problems trying to get the data from onItemLongClick() of CourseListFragment to CourseListFragment. Any help would be greatly appreciated.

Problems to draw on a canvas

Hello.
I have a custom SurfaceView:
Code:
class DrawingView extends SurfaceView {
public SurfaceHolder surfaceHolder = this.getHolder();
public Canvas canvas;
public DrawingView(Context context) {
super(context);
}
public DrawingView(Context context, AttributeSet attrs){
super(context, attrs);
}
public DrawingView(Context context, AttributeSet attrs, int defStyle){
super(context, attrs, defStyle);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
if(event.getAction() == MotionEvent.ACTION_DOWN) {
if(this.surfaceHolder.getSurface().isValid()) {
}
}
return false;
}
}
I created a new DrawingView in my layout xml:
Code:
<com.example.standardbenutzer.adelpath.DrawingView
android:id="@+id/surface"
android:layout_width="128px"
android:layout_height="128px"
android:layout_centerInParent="true"/>
And in my MainActivity class i declared public variable:
Code:
public DrawingView view = null;
which i initiate in the "OnCreate"-Class of the MainActivity:
Code:
view = (DrawingView)findViewById(R.id.surface);
I have a button onClickEvent. If the click event occurs i want to draw something:
Code:
btn_left.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Camera = new Vector3D(Camera.x - 0.25f, Camera.y, Camera.z);
Canvas onScreenCanvas = view.surfaceHolder.lockCanvas();
view.draw(render());
view.surfaceHolder.unlockCanvasAndPost(onScreenCanvas);
}
});
So before i draw something i lock the view canvas. The function "render" returns a bitmap on which i draw my stuff. The bitmap is drawn to the view by "view.draw()". After i drew my bitmap to the view i update it via "unlockCanvasAndPost()".
But i don't see any image on my screen. Why is that?

[Q] Changing to another Activity when pressing on a Gridviewpager

I am trying to start a new certain Activity based on which page I am clicking on in a Gridview.
I tried to understand the Sample GridViewPager which is coming along with the sdk and trying to adapt the given explanation on stackoverflow (question # 26343337). But I really don't know how to bring these two things together and even where to start.
The first java.file Selection
Code:
public class Selection extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.selection_grid);
final GridViewPager pager = (GridViewPager) findViewById(R.id.pager);
pager.setAdapter(new Workers(this, getFragmentManager()));
DotsPageIndicator dotsPageIndicator = (DotsPageIndicator) findViewById(R.id.page_indicator);
dotsPageIndicator.setPager(pager);
}
}
and the second java.file Users (thats the Adapter):
Code:
public class Users extends FragmentGridPagerAdapter {
private static final int TRANSITION_DURATION_MILLIS = 100;
private final Context mContext;
private List<Row> mRows;
private ColorDrawable mDefaultBg;
private ColorDrawable mClearBg;
public Users (Context ctx, FragmentManager fm) {
super(fm);
mContext = ctx;
mRows = new ArrayList<Workers.Row>();
mRows.add(new Row(cardFragment(R.string.title, R.string.user1)));
mRows.add(new Row(cardFragment(R.string.title, R.string.user2)));
mRows.add(new Row(cardFragment(R.string.title, R.string.user3)));
mRows.add(new Row(cardFragment(R.string.title, R.string.user4)));
// In case in one row several cardFragments are needed
// mRows.add(new Row(
// cardFragment(R.string.cards_title, R.string.cards_text),
// cardFragment(R.string.expansion_title, R.string.expansion_text)));
mDefaultBg = new ColorDrawable(R.color.dark_grey);
mClearBg = new ColorDrawable(android.R.color.transparent);
}
LruCache<Integer, Drawable> mRowBackgrounds = new LruCache<Integer, Drawable>(3) {
@Override
protected Drawable create(final Integer row) {
int resid = BG_IMAGES[row % BG_IMAGES.length];
new DrawableLoadingTask(mContext) {
@Override
protected void onPostExecute(Drawable result) {
TransitionDrawable background = new TransitionDrawable(new Drawable[] {
mDefaultBg,
result
});
mRowBackgrounds.put(row, background);
notifyRowBackgroundChanged(row);
background.startTransition(TRANSITION_DURATION_MILLIS);
}
}.execute(resid);
return mDefaultBg;
}
};
private Fragment cardFragment(int titleRes, int textRes) {
Resources res = mContext.getResources();
CardFragment fragment =
CardFragment.create(res.getText(titleRes), res.getText(textRes));
// Add some extra bottom margin to leave room for the page indicator
fragment.setCardMarginBottom(
res.getDimensionPixelSize(R.dimen.card_margin_bottom));
return fragment;
}
static final int[] BG_IMAGES = new int[] {
R.drawable.user1,
R.drawable.user2,
R.drawable.user3,
R.drawable.user4
};
/** A convenient container for a row of fragments. */
private class Row {
final List<Fragment> columns = new ArrayList<Fragment>();
public Row(Fragment... fragments) {
for (Fragment f : fragments) {
add(f);
}
}
public void add(Fragment f) {
columns.add(f);
}
Fragment getColumn(int i) {
return columns.get(i);
}
public int getColumnCount() {
return columns.size();
}
}
@Override
public Fragment getFragment(int row, int col) {
Row adapterRow = mRows.get(row);
return adapterRow.getColumn(col);
}
@Override
public Drawable getBackgroundForRow(final int row) {
return mRowBackgrounds.get(row);
}
@Override
public int getRowCount() {
return mRows.size();
}
@Override
public int getColumnCount(int rowNum) {
return mRows.get(rowNum).getColumnCount();
}
class DrawableLoadingTask extends AsyncTask<Integer, Void, Drawable> {
private static final String TAG = "Loader";
private Context context;
DrawableLoadingTask(Context context) {
this.context = context;
}
@Override
protected Drawable doInBackground(Integer... params) {
Log.d(TAG, "Loading asset 0x" + Integer.toHexString(params[0]));
return context.getResources().getDrawable(params[0]);
}
}
}

Categories

Resources