I'm quite new in android and i have a problem trying to develop an app.
I want to make a countdown timer in my activity but i need to do it within a fragment, so i need to put a for loop that count from 0 - 10 and refresh a TextView inside that fragment.
I need the fragment to do it independently from the activity.
thanks for your collaboration
public class fragmento_3 extends Fragment {
int count= 10;
TextView texto_count;
View v;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
v = inflater.inflate(R.layout.fragmento_3, container, false);
texto_count = (TextView)v.findViewById(R.id.texto_count);
return v;
}
}
and I want to put this inside
for(int x = count; x >= 0 ; x--){
texto_count.setText(String.valueOf(x));
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
thanks,
It is better to use Timer for periodic tasks rather than using Thread.sleep.
Try this code
public class fragmento_3 extends Fragment{
int count= 10;
TextView texto_count;
Timer t;
View v;
TimerTask timer= new TimerTask(){
#Override
public void run() {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
count--;
if(count >= 0) {
texto_count.setText(Integer.toString(count));
}
}
});
if (count <= 0) {
t.cancel();
}
}
};
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
v = inflater.inflate(R.layout.fragmento_3, container, false);
texto_count = (TextView)v.findViewById(R.id.texto_count);
t = new Timer();
t.scheduleAtFixedRate(timer , 0 , 2000);
return v;
}
}
Its probably because you are using the wrong variable texto_conteo. You have declared texto_count as the instance variable so you probably want to use that.
Related
So, I wanted to make an app that has the main activity in which I can switch between two fragments containing a number randomizer and the other one a stopwatch. The stopwatch, meanwhile, must not stop if I switch to another fragment (it may only stop after I click again a start/stop button). I can switch between them normally, but when I try to generate a random number via button or I try to start the stopwatch, the app crashes. This is what I tried:
Stopwatch fragment:
public class frStopwatch extends Fragment {
View view;
EditText etTime;
Button btnStartStop;
Button btnReset;
Chronometer chronometer;
private boolean running;
private long pauseOffset;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
view = inflater.inflate(R.layout.fragment_fr_stopwatch, container, false);
btnStartStop = (Button) view.findViewById(R.id.btnStartStop);
btnReset = (Button) view.findViewById(R.id.btnReset);
btnStartStop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
chronometer.start();
}
});
btnReset.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
chronometer.setBase(SystemClock.elapsedRealtime());
}
});
return view;
}
}
Randomizer fragment:
public class frRandomizer extends Fragment {
View view;
Button btnRandom;
EditText etShowNum;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
view = inflater.inflate(R.layout.fragment_fr_randomizer, container, false);
btnRandom = view.findViewById(R.id.btnRandom);
etShowNum = view.findViewById(R.id.etShowNum);
btnRandom.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Random r = new Random();
etShowNum.setText(r.nextInt(9));
}
});
return view;
}
}
The app crashes on both emulator and mobile phone.
I have a BottomSheetDialogFragment and inside onCreateView i am inflating 2 different views based on a condition. Now my 1st view contains a recyclerView and the condition on which i want to switch my views is that if the list is empty then inflate view 1 else inflate view 2. Now my problem is when my list data count becomes 0 i want to call the onCreateView again so that based on the condition my 2nd view would be inflated. But i don't know how am i supposed to do it or rather is this the right way to do it.
My Code -
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
if (this.documentCount > 0) {
View v = inflater.inflate(R.layout.bottom_sheet_layout_document_attachments_added, container, false);
documentArrayList = dataToRender.get(fieldPosition).getAttachments();
Button attachMore = (Button) v.findViewById(R.id.btn_attachMore);
if(documentCount == 5){
attachMore.getBackground().setAlpha(128);
}else{
attachMore.getBackground().setAlpha(255);
}
attachMore.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try{
if(documentCount == 5){
PageLoader.showToast(getResources().getString(R.string.document_limit_message));
}else{
pickDocuments();
}
}
catch (Exception e){
Sentry.captureException(e);
}
}
});
Button btnCloseDrawer = (Button) v.findViewById(R.id.btn_closeDrawer);
btnCloseDrawer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dismiss();
}
});
recyclerview_documents = v.findViewById(R.id.recyclerview_documents);
adapter_documents = new DocumentAdapter(this, documentArrayList, fieldPosition);
recyclerview_documents.setAdapter(adapter_documents);
recyclerview_documents.setLayoutManager(new LinearLayoutManager(mContext));
return v;
} else {
View v = inflater.inflate(R.layout.bottom_sheet_layout_document, container, false);
TextView txtview_attach = (TextView) v.findViewById(R.id.txtview_attach);
txtview_attach.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try{
permissionManager.checkPermission(mContext, Manifest.permission.READ_EXTERNAL_STORAGE, new PermissionManager.PermissionAskListener() {
#Override
public void onNeedPermission() {
ActivityCompat.requestPermissions(getActivity(), new String[]{
Manifest.permission.READ_EXTERNAL_STORAGE
}, REQUEST_EXTERNAL_STORAGE);
}
#Override
public void onPermissionPreviouslyDenied() {
showDocumentRational();
}
#Override
public void onPermissionPreviouslyDeniedWithNeverAskAgain() {
dialogForSettings(getResources().getString(R.string.permission_denied), getResources().getString(R.string.permission_denied_document_access_message));
}
#Override
public void onPermissionGranted() {
pickDocuments();
}
});
}
catch (Exception e){
Sentry.captureException(e);
}
}
});
return v;
}
}```
Can't use more then one views for one fragment, but you can create a fragment wrapper that depends on the conditions, will show or create the fragment you need with the view you need.
for example WrapperFragment checking list size and creating Fragment1, when list size changed Wrapper fragment removung from fragment manager Fragment1 and add Fragment2
I am new to Java/android develop and trying to follow instructions from android site but cannot find clear answer to implementing onclicklistener in fragment. Please help me why its keep crashing in runtime when I click.
public class TestFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_mngr_user, container, false);
return v;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mDBhelper = new UserBaseHelper(getActivity());
// Capture our button from layout
TextView TextviewShow = (TextView)getActivity().findViewById(R.id.text_show);
// Register of onClick listener with the implementation above
TextviewShow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// do something when the text_show is clicked
displayInfo();
}
});
}
.....
}
try this
use this
TextView TextviewShow = (TextView)v.findViewById(R.id.text_show);
instead of this
TextView TextviewShow = (TextView)getActivity().findViewById(R.id.text_show);
change your code as below
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_mngr_user, container, false);
// Capture our button from layout
TextView TextviewShow = (TextView)v.findViewById(R.id.text_show);
// Register of onClick listener with the implementation above
TextviewShow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// do something when the text_show is clicked
displayInfo();
}
});
return v;
}
Try this
public class TestFragment extends Fragment {
View v;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
v = inflater.inflate(R.layout.fragment_mngr_user, container, false);
return v;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mDBhelper = new UserBaseHelper(getActivity());
// Capture our button from layout
TextView TextviewShow = (TextView)v.findViewById(R.id.text_show);
// Register of onClick listener with the implementation above
TextviewShow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// do something when the text_show is clicked
displayInfo();
}
});
}
.....
}
Move your code from onCreate() method to onCreateView() method and change the following code
From
(TextView)getActivity().findViewById(R.id.text_show);
to
(TextView)v.findViewById(R.id.text_show);
I have this piece of code:
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
tableView = inflater.inflate(R.layout.fragment_table, container, false);
View layout = inflater.inflate(R.layout.fragment_1, container, false);
if (roomArray == null || roomArray.isEmpty()) {
roomArray = getTablesList(new VolleyCallback() {
#Override
public void onSuccess(ArrayList<RoomsClass> result) {
Toast.makeText(getActivity(), "onSuccess", Toast.LENGTH_LONG).show();
}
});
} else {
ArrayList<View> tableList = new ArrayList<>();
ArrayList<Tables> tables;
Toast.makeText(getActivity(), "IsNotNull", Toast.LENGTH_LONG).show();
tables = roomArray.get(0).getTables();
GridLayout gridLayout = (GridLayout) layout.findViewById(R.id.grid_layout);
for (int i = 0; i < 1; i++) {
tableView = inflater.inflate(R.layout.fragment_table, container, false);
TextView textView = (TextView) tableView.findViewById(R.id.table_number);
textView.setText(tables.get(i).getTableNumber());
GridLayout.Spec row = GridLayout.spec(i / 5);
GridLayout.Spec col = GridLayout.spec(i);
GridLayout.LayoutParams params = new GridLayout.LayoutParams(row, col);
gridLayout.addView(tableList.get(i), i, params);
}
}
return layout;
}
so I have onSuccess, but I cant add views to my fragment. I need to somehow call all methods after onSuccess, but its inner class so I can't handle anything there. So what is the right way of doing this?
Are you inflating two fragments in createView?
tableView = inflater.inflate(R.layout.fragment_table, container, false);
View layout = inflater.inflate(R.layout.fragment_1, container, false);
have u try to use handler to solve this problem , the use of handler can avoid do something in a inner class.
Handler myHandler = new Handler() {
public void handleMessage(Message msg) {
switch (msg.what) {
case a:
//do somthing
break;
}
super.handleMessage(msg);
}
};
I have a fragment[MainMenu] which has just menus and background image.I want to load the MainMenu fragment image and after some time i want to load the menus one by one after certain interval. And I tired to do this:
public class MainMenu extends Fragment{
public MainMenu(){}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main_menu, container, false);
return rootView;
}
#Override
public void onViewCreated(final View view, Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onViewCreated(view, savedInstanceState);
ShowMenu(view);
}
private static void ShowMenu(final View container){
String[] menu = container.getResources().getStringArray(R.array.array_menu_string);
final LinearLayout llMenu = (LinearLayout)container.findViewById(R.id.llButtons);
for(int i = 0; i<menu.length; i++){
final String menuName = menu[i];
try {
Thread.sleep(2000);
TextView tvMenu = new TextView(container.getContext());
tvMenu.setText(menuName);
tvMenu.setPadding(5, 5, 5, 5);
llMenu.addView(tvMenu);
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}finally{
System.out.println(menuName);
}
}
}
}
But the problem is the menus are already loaded then only the fragment is displayed? Please help to understand me why is this happening... and what should be done?