Fragments and Thread in Android - android

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?

Related

Beginner trying out onClickListener in fragment. It keep crashing in runtime

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);

Custom Actionbar in fragment android

I create simple project using actionbar ,i've one class and one fragment class, i define custome actionbar in class, and my problem, how to call method actionbar in fragment class from class,
this code like below :
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_holder);
fragmentArray = new ConferenceFragment[8];
// Load main fragment
fragment = new HomeFragment();
fragmentArray[0] = fragment;
currentFragmentIndex = 0;
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.holder, fragment).commit();
// initMenuBar();
}
public void initMenuBar(){
ActionBar actionBar = getActionBar();
actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
actionBar.setCustomView(R.layout.menu_bar);
ImageButton buttonSideMenu = (ImageButton) findViewById(R.id.bt_menu);
buttonSideMenu.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
toggle();
// Toast.makeText(getApplicationContext(), "Clicked!",Toast.LENGTH_LONG).show();
}
});
actionBar.show();
}
// fragment class
public class HomeFragment extends Fragment{
View v;
MainActivity mainactivity;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
mainActivity.initMenuBar(); // ERROR IN THIS LINE
super.onCreateView(inflater, container, savedInstanceState);
v = inflater.inflate(R.layout.home_fragment, container, false);
return v;
}
}
ActionBar is traditionally the part of Activity and is available to activity only. You can get Activity instance by calling getActivity() from fragment and cast it to your activity then call public method to do whatever you want.
But the better option is to use ToolBar explained here support library v7
You need to get your MainActivity's context reference in your fragment to access activity's method.
Try this.
public class HomeFragment extends Fragment{
View v;
Context mContext;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreateView(inflater, container, savedInstanceState);
v = inflater.inflate(R.layout.home_fragment, container, false);
mContext = getActivity();
((MainActivity) mContext).initMenuBar();
return v;
}
}

How to make a lock screen button in fragment layout?

I want to made a lock screen Button in a Fragment Layout.
I searched some help and found the same, but made using an Activity.
The code is here:
http://karanbalkar.com/2014/01/tutorial-71-implement-lock-screen-in-android/
I don't know how to change it to work in a Fragment?
Please help
My code:
public class Tab1fragment extends Fragment {
/**
* #param args
*/
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater,
#Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
// TODO Auto-generated method stub
return inflater.inflate(R.layout.tab1_layout, container, false);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
}
you have to read more about Fragment: http://developer.android.com/reference/android/app/Fragment.html
first you have to implement View.OnClickListener in your Fragment, then create a View inside onCreateView like :
View rootView = inflater.inflate(R.layout. tab1_layout, container, false);
so your fragment became :
public class Tab1fragment extends Fragment implements View.OnClickListener {
.
.
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.tab1_layout, container, false);
mDevicePolicyManager = ...
mComponentName = ...
Button btnEnableAdmin = (Button) rootView.findViewById(R.id.btnEnable);
.
.
btnEnableAdmin.setOnClickListener(this);
.
.
return rootView;
}
public void onClick(View v) {
switch (v.getId()) {
...
}
}
}
NB: I tested this code on my device

Maintain fragment's view state

I have seen Link1 for this issue but could understand it right. I have a fragment that loads a list. When i click the list item it opens another activity. But i press back button it loads the list again. I want it to be at the same scroll position where it was before. In above mentioned link it specifies to use flag but i haven't got the point.
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dashboard);
android.app.Fragment fragment = new MeFragment();
getFragmentManager().beginTransaction().replace(R.id.layout_FragmentsContainer, fragment).addToBackStack(null).commit();
}
}
public class MeFragment extends Fragment
{
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
return inflater.inflate(R.layout.fragment_me, container, false);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
meLV = (ListView) getView().findViewById(R.id.lv_Inbox);
loadingListProgress = (ProgressBar) getView().findViewById(R.id.progress_LoadingList);
meList = new ArrayList<Message>();
meAdapter = new MessagesListAdapter(getActivity(), meList);
//addFooter();
meLV.setAdapter(meAdapter);
meLV.setOnItemClickListener(this);
pageCount = 0;
loadmoreProgressDialog = new ProgressDialog(getActivity());
loadmoreProgressDialog.setTitle("Please wait ...");
loadmoreProgressDialog.setMessage("Loading more ...");
loadmoreProgressDialog.setCancelable(true);
loadUserMessages();
meLV.setOnScrollListener(new EndlessScrollListener() {
#Override
public void onLoadMore(int page, int totalItemsCount) {
// TODO Auto-generated method stub
//addFooter();
loadmoreProgressDialog.show();
loadUserMessages();
}
});
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
// TODO Auto-generated method stub
Utils.showToast_msg(getActivity(), "MessageItemClicked");
ReferralDetailFragment fragment = new ReferralDetailFragment();
getFragmentManager().beginTransaction().replace(R.id.layout_FragmentsContainer, fragment).addToBackStack(null).commit();
}
}
public class ReferralDetailFragment extends Fragment implements OnClickListener {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.fragment_referraldetail,container, false);
linkToAcknowledge = (TextView) view.findViewById(R.id.lbl_Link_to_Acknowledge);
return view;
}
}
I implemented a simple solution for this in my app, basically when you press back to go to the fragment again, onCreateView() is called. Here in onCreateView() you have done all initialization, so we change
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.fragment_me, container, false);
/*
*Whatever you want to do
*
*/
return view;
}
to:
View view;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
if(view==null){
view = inflater.inflate(R.layout.fragment_me, container, false);
/*
*Whatever you want to do
*
*/
}
else{
((ViewGroup)view.getParent()).removeView(view);
}
return view;
}
Here, we move View view outside and make it a class variable. So if it is the first time the fragment is called, it is null and the initialization occurs, otherwise it goes to else black. Else block is required because onCreateView() adds whatever it returns as a child of the view's parent, so since view is already there, we remove it and onCreateView automatically adds it again.
According to our exchange in the comments, I completely deletde my answer and re-write a new one.
I copy/paste the code from one of my apps and removing the useless things and changing the names. Hope there is not too many typing mistakes, at that it is the minimum required to have it working.
When I pop back to FirstFragment from SecondFragment, the scroll position of FirstFragment is the same as when I clicked an item to load the SecondFragment.
Note that I don't extend FragmentActivity. I have an activity which loads the fragments.
Extend/modify to match your needs.
MainActivity :
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_layout);
}
}
FirstFragment Class :
public class FirstFragment extends Fragment implements OnItemClickListener {
private ListView mListView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.first_fragment_layout, container, false);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mListView = (ListView) getView().findViewById(R.id.listview_first_fragment);
mListView.setAdapter(mAdapter); // depends on your adapter
mListView.setOnItemClickListener(this);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
mListView.setItemChecked(position, true);
//in case you need, set the bundle here, for example pass the position
Bundle arguments = new Bundle();
arguments.putInt("position", position);
SecondFragment secondFragment = new SecondFragment();
secondFragment.setArguments(arguments);
getFragmentManager().beginTransaction().replace(R.id.fragment_container, secondFragment).addToBackStack(null).commit();
}
}
SecondFragment Class :
public class SecondFragment extends Fragment {
private Integer mPosition;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.second_fragment_layout, container, false);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Bundle arguments = getArguments();
if (arguments == null) {
mPosition= 0;
} else {
mPosition= arguments.getInt("Position");
}
}
}
What you are trying to achieve may be done with help of savedInstanceState. i also had this kind of problem which i resolved by using add() method instead of replace() in transition.
If you can change your method or already not using add() than give it a shot.
and if add() method didn't do the trick then check the implementation of savedInstanceState.
correctly save instance state.
How to save states of fragment views.

Refresh a TextView from inside a fragment

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.

Categories

Resources