I'm trying to add a progress spinner at the top of my app while data is being received from the volley. There may be an easier way to do this but this is what i've tried so far only I have a few errors. The first error being newsListView getting the error 'varied is accessed from within inner class, needs to be declared final'. and the string values cannot be resolved. Here is the class I made within the oncreate method:
public class MainActivity extends AppCompatActivity {
private List<NewsRecord> newsListData = new ArrayList<NewsRecord>();
private GridView newsListView;
private NewsListAdapter adapter;
LinearLayout layout;
private ProgressDialog pDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
GridView newsListView = (GridView) findViewById(R.id.newsFeedList);
adapter = new NewsListAdapter(this, R.layout.adapter_news_list, newsListData, this);
layout = (LinearLayout) findViewById(R.id.progressbar_view);
newsListView.setAdapter(adapter);
pDialog = new ProgressDialog(this);
// Showing progress dialog before making http request
pDialog.setMessage("Loading Articles...");
pDialog.show();
newsListView.setOnItemClickListener(itemClicked);
nextStart = 0;
updateListData(nextStart, 20);
}
public int nextStart = 0;
public void updateListData(int StartPoint, int count){
String url = "http://www.efstratiou.info/projects/newsfeed/getList.php?start=" + StartPoint + "&count=" + count;
EDANewsApp app = EDANewsApp.getInstance();
JsonArrayRequest jsonRequest = new JsonArrayRequest(url, listener, errorListener);
app.requestQueue.add(jsonRequest);
nextStart +=count;
}
#Override
public boolean onCreateOptionsMenu (Menu menu){
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main_menu, menu);
return true;
}
#Override
public void onDestroy() {
super.onDestroy();
hidePDialog();
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
public boolean onOptionsItemSelected(MenuItem item){
switch (item.getItemId()) {
case R.id.action_about:
Intent intent = new Intent(this, AboutActivity.class);
startActivity(intent);
return true;
case R.id.action_search:
return true;
case R.id.action_settings:
return true;
default:
return super.onOptionsItemSelected(item);
}
}
AdapterView.OnItemClickListener itemClicked = new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(MainActivity.this, NewsItemActivity.class);
intent.putExtra("newsItemId", newsListData.get(position).recordId);
startActivity(intent);
}
};
private SearchView.OnQueryTextListener searchQueryListener = new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
Intent searchIntent = new Intent(MainActivity.this, SearchResultsActivity.class);
searchIntent.putExtra("query", query);
return true;
}
#Override
public boolean onQueryTextChange(String newText) {
return false;
}
};
//Listeners
Response.Listener<JSONArray> listener = new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
//we successfully received the JSONArray
//Here we will extract the data and use it in our app
hidePDialog();
//Clear the dataset before loading new data
// newsListData.clear();
//Go through all the JSON objects
for (int i = 0; i < response.length(); i++) {
try {
//Get one JSON object
JSONObject jsonObj = response.getJSONObject(i);
//Put JSON data in a Java object
NewsRecord record = new NewsRecord();
record.recordId = jsonObj.getInt("record_id");
record.title = jsonObj.getString("title");
record.date = jsonObj.getString("date");
record.shortInfo = jsonObj.getString("short_info");
record.imageUrl = jsonObj.getString("image_url");
newsListData.add(record);
} catch (JSONException e) {
e.printStackTrace();
}
}
adapter.notifyDataSetChanged();
}
};
Response.ErrorListener errorListener = new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//There was an error in the communication
//We can notify the user about it
hidePDialog();
}
};
}
and the progress bar appears in the activity_main.xml like so:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/newsListItem"
android:layout_width="match_parent"
android:layout_height="wrap_content"
tools:context=".MainActivity">
<LinearLayout
android:id="#+id/progressbar_view"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:orientation="vertical" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:orientation="horizontal" >
<ProgressBar
style="?android:attr/progressBarStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical|center_horizontal" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical|center_horizontal"
android:text="Loading data..." />
</LinearLayout>
<View
android:layout_width="fill_parent"
android:layout_height="1dp"
android:background="#C0C0C0" />
</LinearLayout>
<GridView
android:id="#+id/newsFeedList"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:verticalSpacing="0dp"
android:horizontalSpacing="0dp"
android:stretchMode="columnWidth"
android:numColumns="2"/>
</FrameLayout>
Here is the way I often do in my projects, IMO you can take a look and apply to your project, hope it helps!
#Override
protected void onCreate(Bundle savedInstanceState) {
...
mRequestQueue = Volley.newRequestQueue(this);
mProgressBar = (ProgressBar) findViewById(R.id.progressBar);
mProgressBar.setVisibility(View.VISIBLE);
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, url, null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
mProgressBar.setVisibility(View.INVISIBLE);
// do something...
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
mProgressBar.setVisibility(View.INVISIBLE);
// do something...
}
});
mRequestQueue.add(jsonArrayRequest);
...
}
you declare your progressbar
private ProgressDialog pDialog;
pDialog = new ProgressDialog(this);
// Showing progress dialog before making http request
pDialog.setMessage("Loading...");
pDialog.show();
you call you Volley request than when you get the response (either success or error event) you call the hidePDialog method
hidePDialog();
//method to hide progressbar
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
don't forget to call the method in onDestroy() also
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
GridView newsListView = (GridView) findViewById(R.id.newsFeedList);
adapter = new NewsListAdapter(this, R.layout.adapter_news_list, newsListData, this);
layout = (LinearLayout) findViewById(R.id.progressbar_view);
newsListView.setAdapter(adapter);
newsListView.setOnItemClickListener(itemClicked);
EDANewsApp app = EDANewsApp.getInstance();
nextStart = 0;
updateListData(nextStart, 20);
}
private class Task extends AsyncTask<String, Integer, Boolean> {
private ProgressDialog dialog;
#Override
protected void onPreExecute() {
dialog.setMessage("Doing something, please wait.");
dialog.show();
layout.setVisibility(View.VISIBLE);
newsListView.setVisibility(View.GONE);
super.onPreExecute();
}
#Override
protected void onPostExecute(Boolean result) {
dialog.dismiss();
layout.setVisibility(View.GONE);
newsListView.setVisibility(View.VISIBLE);
adapter.notifyDataSetChanged();
super.onPostExecute(result);
}
#Override
protected Boolean doInBackground(String... params) {
stringValues.add("String 1");
stringValues.add("String 2");
stringValues.add("String 3");
stringValues.add("String 4");
stringValues.add("String 5");
try {
Thread.sleep(3000);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
Hope this will help you.
Related
This question already has answers here:
Create clickable link in text view in android
(2 answers)
Closed 2 years ago.
I'm trying to develop an Android application with Java. I need to separate all words in a text (bookText in code) and make them clickable. How can I do this? I will be grateful if you could help me. Thanks in advance.
public class BookActivity extends AppCompatActivity {
public static final String BOOK_TEXT = "com.example.altaybook.BOOK_TEXT";
BookViewModel bookViewModel;
private TextView bookTextView;
private String bookName;
private String bookText;
ProgressBar bookTextProgressBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_book);
bookTextView = findViewById(R.id.book_text_id);
bookTextProgressBar = findViewById(R.id.bookTextProgressBar);
Intent intent = getIntent();
final int bookPosition = intent.getIntExtra(BOOK_TEXT, -1);
bookViewModel = new ViewModelProvider(this, ViewModelProvider.AndroidViewModelFactory.getInstance(this.getApplication())).get(BookViewModel.class);
bookViewModel.getAllBooks().observe(this, new Observer<List<Book>>() {
#Override
public void onChanged(List<Book> books) {
bookName = books.get(bookPosition).getName();
setTitle(bookName);
bookText = books.get(bookPosition).getText();
SetTextAsyncTask setTextAsyncTask = new SetTextAsyncTask();
setTextAsyncTask.execute();
bookTextView.setMovementMethod(LinkMovementMethod.getInstance());
}
});
}
public class SetTextAsyncTask extends AsyncTask<String, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
bookTextProgressBar.setVisibility(View.VISIBLE);
}
#Override
protected Void doInBackground(String... strings) {
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
bookTextView.setText(bookText);
bookTextProgressBar.setVisibility(View.GONE);
}
}
}
You can use LinearLayout. Here is an example:
activity_book.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center">
<LinearLayout
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:orientation="horizontal"
android:gravity="center"
android:id="#+id/container"/>
</LinearLayout>
BookActivity.java
public class BookActivity extends Activity
{
public static final String BOOK_TEXT = "com.example.altaybook.BOOK_TEXT";
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_book);
LinearLayout ll = findViewById(R.id.container);
String[] splitText = BOOK_TEXT.split("\\.");
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
for(int i=0; i < splitText.length; i++) {
TextView content = new TextView(this);
if(i == 0) { content.setText(splitText[i]);
} else { content.setText("." + splitText[i]); }
content.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(BookActivity.this, "You clicked: " + ((TextView)view).getText(), Toast.LENGTH_SHORT).show();
}
});
ll.addView(content, params);
}
}
}
I am trying to add bookmark in my web browser and have added it but , it is only saving 1 link . for example if I am at https://www.wikipedia.org/ and save this bookmark
and i browse wikipedia more and landed on this link https://en.wikipedia.org/wiki/Portal:Featured_content
the bookmark will show remove in snack bar and is just saving 1 link and removing 1 link
I want to save both links.
public static final String PREFERENCES = "PREFERENCES_NAME";
public static final String WEB_LINKS = "links";
public static final String WEB_TITLE = "title";
String murl;
//
CoordinatorLayout coordinatorLayout;
private ProgressBar progressBar;
//
android.webkit.WebView webView;
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN) {
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
if (webView.canGoBack()) {
webView.goBack();
} else {
finish();
}
return true;
}
}
return super.onKeyDown(keyCode, event);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_web_view);
webView = (android.webkit.WebView) findViewById(R.id.webview);
progressBar = findViewById(R.id.progressBar);
initWebview();
WebSettings settings = webView.getSettings();
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("");
toolbar.setNavigationIcon(R.drawable.ic_arrow_back);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onBackPressed();
}
});
murl = getIntent().getExtras().getString("url");
coordinatorLayout = findViewById(R.id.main_content);
settings.setJavaScriptEnabled(true);
settings.setLoadWithOverviewMode(true);
settings.setUseWideViewPort(true);
settings.setSupportZoom(true);
// zoom
settings.setBuiltInZoomControls(true);
// zoom
settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
settings.setDomStorageEnabled(true);
webView.setScrollBarStyle(webView.SCROLLBARS_OUTSIDE_OVERLAY);
webView.setScrollbarFadingEnabled(true);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
webView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
} else {
webView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
}
webView.setWebViewClient(new WebViewClient());
webView.loadUrl(murl);
webView.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);
webView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
webView.getSettings().setAppCacheEnabled(true);
// webView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
settings.setDomStorageEnabled(true);
// settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
settings.setSaveFormData(true);
settings.setEnableSmoothTransition(true);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.saved, menu);
SharedPreferences sharedPreferences = getSharedPreferences(PREFERENCES, Context.MODE_PRIVATE);
String links = sharedPreferences.getString(WEB_LINKS, null);
if (links != null) {
Gson gson = new Gson();
ArrayList<String> linkList = gson.fromJson(links, new TypeToken<ArrayList<String>>() {
}.getType());
if (linkList.contains(murl)) {
menu.getItem(0).setIcon(R.drawable.bookmark);
} else {
menu.getItem(0).setIcon(R.drawable.bookmark);
}
} else {
menu.getItem(0).setIcon(R.drawable.bookmark);
}
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.action_bookmark) {
String message;
SharedPreferences sharedPreferences = getSharedPreferences(PREFERENCES, Context.MODE_PRIVATE);
String jsonLink = sharedPreferences.getString(WEB_LINKS, null);
String jsonTitle = sharedPreferences.getString(WEB_TITLE, null);
if (jsonLink != null && jsonTitle != null) {
Gson gson = new Gson();
ArrayList<String> linkList = gson.fromJson(jsonLink, new TypeToken<ArrayList<String>>() {
}.getType());
ArrayList<String> titleList = gson.fromJson(jsonTitle, new TypeToken<ArrayList<String>>() {
}.getType());
if (linkList.contains(murl)) {
linkList.remove(murl);
titleList.remove(webView.getTitle().trim());
Editor editor = sharedPreferences.edit();
editor.putString(WEB_LINKS, new Gson().toJson(linkList));
editor.putString(WEB_TITLE, new Gson().toJson(titleList));
editor.apply();
message = "removed";
} else {
linkList.add(murl);
titleList.add(webView.getTitle().trim());
Editor editor = sharedPreferences.edit();
editor.putString(WEB_LINKS, new Gson().toJson(linkList));
editor.putString(WEB_TITLE, new Gson().toJson(titleList));
editor.apply();
message = "Saved";
}
} else {
ArrayList<String> linkList = new ArrayList<>();
ArrayList<String> titleList = new ArrayList<>();
linkList.add(murl);
titleList.add(webView.getTitle());
Editor editor = sharedPreferences.edit();
editor.putString(WEB_LINKS, new Gson().toJson(linkList));
editor.putString(WEB_TITLE, new Gson().toJson(titleList));
editor.apply();
message = "Saved";
}
Snackbar snackbar = Snackbar.make(coordinatorLayout, message, Snackbar.LENGTH_LONG);
snackbar.show();
invalidateOptionsMenu();
}
return super.onOptionsItemSelected(item);
}
private void initWebview() {
webView.setWebViewClient(new WebViewClient() {
#Override
public void onPageStarted(android.webkit.WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
progressBar.setVisibility(View.VISIBLE);
murl = url;
invalidateOptionsMenu();
}
#Override
public boolean shouldOverrideUrlLoading(android.webkit.WebView view, String url) {
webView.loadUrl(url);
return true;
}
#Override
public boolean shouldOverrideUrlLoading(android.webkit.WebView view, WebResourceRequest request) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
webView.loadUrl(request.getUrl().toString());
}
return true;
}
#Override
public void onPageFinished(android.webkit.WebView view, String url) {
super.onPageFinished(view, url);
progressBar.setVisibility(View.GONE);
invalidateOptionsMenu();
}
#Override
public void onReceivedError(android.webkit.WebView view, WebResourceRequest request, WebResourceError error) {
super.onReceivedError(view, request, error);
progressBar.setVisibility(View.GONE);
invalidateOptionsMenu();
}
});
}
}
xml file :
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/main_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#android:color/white"
android:fitsSystemWindows="true">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<WebView
android:id="#+id/webview"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<ProgressBar
android:id="#+id/progressBar"
style="#style/Widget.AppCompat.ProgressBar.Horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="-7dp"
android:indeterminate="true"
android:visibility="gone"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
</android.support.design.widget.CoordinatorLayout>
I am creating an app which displays the apk files on phone in a list view. I am using ListActivity in this app.When I select a row in listview, it gets highlighted and the app corresponding to the apk file opens.I do not want the app to open, I want the row to stay highlighted after selecting it and no other further action. I tried using
1. setOnItemLongClickListener (but it won't work here) .
2. android:choiceMode="singleChoice" (not working again)
3. getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE); (working but opens the app on clicking )
I do not want the row to be highlighted after some time, I want it to be highlighted on click & stay highlighted and I do not want the app to open, I want the row to stay highlighted after selecting it and no other further action. How can I achieve this ?
AllAppsActivity.java:
public class AllAppsActivity extends ListActivity {
private PackageManager packageManager = null;
private List<ApplicationInfo> applist = null;
private ApplicationAdapter listadaptor = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_apk);
packageManager = getPackageManager();
new LoadApplications().execute();
getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
getListView().setSelector(android.R.color.darker_gray);
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
ApplicationInfo app = applist.get(position);
try {
Intent intent = packageManager
.getLaunchIntentForPackage(app.packageName);
if (null != intent) {
startActivity(intent);
}
} catch (ActivityNotFoundException e) {
Toast.makeText(AllAppsActivity.this, e.getMessage(),
Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(AllAppsActivity.this, e.getMessage(),
Toast.LENGTH_LONG).show();
}
}
private List<ApplicationInfo> checkForLaunchIntent(List<ApplicationInfo> list) {
ArrayList<ApplicationInfo> applist = new ArrayList<ApplicationInfo>();
for (ApplicationInfo info : list) {
try {
if (null != packageManager.getLaunchIntentForPackage(info.packageName)) {
applist.add(info);
}
} catch (Exception e) {
e.printStackTrace();
}
}
return applist;
}
private class LoadApplications extends AsyncTask<Void, Void, Void> {
private ProgressDialog progress = null;
#Override
protected Void doInBackground(Void... params) {
applist = checkForLaunchIntent(packageManager.getInstalledApplications
(PackageManager.GET_META_DATA));
listadaptor = new ApplicationAdapter(AllAppsActivity.this,
R.layout.snippet_list_row, applist);
return null;
}
#Override
protected void onCancelled() {
super.onCancelled();
}
#Override
protected void onPostExecute(Void result) {
setListAdapter(listadaptor);
progress.dismiss();
super.onPostExecute(result);
}
#Override
protected void onPreExecute() {
progress = ProgressDialog.show(AllAppsActivity.this, null,
"Loading application info...");
super.onPreExecute();
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
}
}
activity_apk.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/btn_playlist" />
<ListView
android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:divider="#242424"
android:dividerHeight="1dp"
/>
</LinearLayout>
If you want do nothing do nothing. Don't override method onListItemClick (delete it) and that's all.
Define a flag in your adapter bean,set highlight by the flag in the adapter, change the flag and adapter.notifyDataSetChanged() when you click item.
I am very...very new to android development and I am trying to recreate a hybrid app I built in ionic, but do it in actual android.
I am having an issue with either layouts or fragment loading that I can't figure out.
What I want is something similar to the IG layout, where there is a bar at the bottom for navigation, clicking the button would load the new page. From my understanding the best way to accomplish that is to use a main activity, then each of the tabs at the bottom are fragments.
So I built that, but I want the top toolbar to disappear on the second tab, so in the second tab "onCreateView" method I added the toolbar.setVisibility(View.GONE); however, as soon as I load the app, even on the first tab, the toolbar at the top is gone, signifying it is loading the views for each fragment when the app loads. I would think that would severely impact performance on a large app. Am I crazy?
Here is my main layout for the main activity...
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/main_layout">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:background="#color/colorPrimary"
android:elevation="6dp"
android:minHeight="?attr/actionBarSize"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light" />
<android.support.v4.view.ViewPager
android:id="#+id/content"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/toolbar" />
<android.support.design.widget.TabLayout
android:id="#+id/tab_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabMode="fixed"
android:gravity="center_horizontal"
android:layout_gravity="center_horizontal"
android:background="?attr/colorPrimary"
android:elevation="6dp"
app:tabSelectedTextColor="#FFFFFF"
app:tabTextColor="#D3D3D3"
app:tabIndicatorColor="#FF00FF"
android:minHeight="?attr/actionBarSize"
android:layout_alignParentBottom="true" />
</RelativeLayout>
Then my HomeActivity class..
public class HomeActivity extends BaseActivity implements OnFragmentTouched {
private TextView mTextMessage;
private static final String SELECTED_ITEM = "arg_selected_item";
private int mSelectedItem;
private BottomNavigationView mBottomNav;
private FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
#Override
protected void onSaveInstanceState(Bundle outState) {
outState.putInt(SELECTED_ITEM, mSelectedItem);
super.onSaveInstanceState(outState);
}
#Override
public void onBackPressed() {
MenuItem homeItem = mBottomNav.getMenu().getItem(0);
if (mSelectedItem != homeItem.getItemId()) {
// select home item
selectFragment(homeItem);
} else {
super.onBackPressed();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
ViewPager pager = (ViewPager) findViewById(R.id.content);
PagerAdapter pagerAdapter = (PagerAdapter) new PagerAdapter(getSupportFragmentManager(), HomeActivity.this);
pager.setAdapter(pagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
tabLayout.setupWithViewPager(pager);
for(int i = 0; i < tabLayout.getTabCount(); i++) {
TabLayout.Tab tab = tabLayout.getTabAt(i);
tab.setCustomView(pagerAdapter.getTabView(i));
}
}
private void selectFragment(MenuItem item) {
Fragment frag = null;
switch(item.getItemId()) {
case R.id.navigation_home:
frag = new AllPostsFragment();
break;
case R.id.navigation_dashboard:
frag = ProfileFragment.newInstance(user.getUid());
break;
case R.id.navigation_notifications:
frag = new ChatListFragment();
break;
}
mSelectedItem = item.getItemId();
}
#VisibleForTesting
public ProgressDialog mProgressDialog;
public void showProgressDialog() {
if (mProgressDialog == null) {
mProgressDialog = new ProgressDialog(this);
mProgressDialog.setMessage(getString(R.string.loading));
mProgressDialog.setIndeterminate(true);
}
mProgressDialog.show();
}
public void hideProgressDialog() {
if (mProgressDialog != null && mProgressDialog.isShowing()) {
mProgressDialog.dismiss();
}
}
#Override
public void onStop() {
super.onStop();
hideProgressDialog();
}
#Override
public void onFragmentTouched(Fragment fragment, float x, float y) {
Log.d("FRAGMENT_TOUCHED", "The ChatListFragment touch happened");
if(fragment instanceof ChatFragment) {
final ChatFragment theFragment = (ChatFragment) fragment;
Animator unreveal = theFragment.prepareUnrevealAnimator(x, y);
unreveal.addListener(new Animator.AnimatorListener() {
#Override
public void onAnimationStart(Animator animation) {
}
#Override
public void onAnimationEnd(Animator animation) {
getSupportFragmentManager().beginTransaction().remove(theFragment).commit();
getSupportFragmentManager().executePendingTransactions();
}
#Override
public void onAnimationCancel(Animator animation) {}
#Override
public void onAnimationRepeat(Animator animation) {}
});
unreveal.start();
}
}
public String getUid() {
return FirebaseAuth.getInstance().getCurrentUser().getUid();
}
private class PagerAdapter extends FragmentPagerAdapter {
Context context;
String tabTitles[] = new String[] {"Home", "Profile", "Chat"};
public PagerAdapter(FragmentManager fm, Context context) {
super(fm);
this.context = context;
}
#Override
public Fragment getItem(int pos) {
switch(pos) {
case 0: return new AllPostsFragment();
case 1: return ProfileFragment.newInstance(user.getUid());
case 2: return new ChatListFragment();
default:
return new AllPostsFragment();
}
}
#Override
public int getCount() {
return tabTitles.length;
}
#Override
public CharSequence getPageTitle(int position) {
return tabTitles[position];
}
public View getTabView(int position) {
View tab = LayoutInflater.from(HomeActivity.this).inflate(R.layout.custom_tab, null);
TextView tv = (TextView) tab.findViewById(R.id.custom_text);
tv.setText(tabTitles[position]);
return tab;
}
}
}
So, in the "ProfileFragment" in the onCreateView method I have...
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_profile, container, false);
recyclerView = (RecyclerView) rootView.findViewById(R.id.userPostsRecycler);
RecyclerView.LayoutManager layoutManager = new GridLayoutManager(getContext(), 2);
recyclerView.setLayoutManager(layoutManager);
Toolbar toolbar = getActivity().findViewById(R.id.toolbar);
toolbar.setVisibility(View.GONE);
followingCountText = rootView.findViewById(R.id.following_count);
followersCountText = rootView.findViewById(R.id.followers_count);
titleLayout = rootView.findViewById(R.id.toolbar_layout);
titleLayout.setTitle(user.getDisplayName());
fab1Container = rootView.findViewById(R.id.fab_1);
fab2Container = rootView.findViewById(R.id.fab_2);
ImageView profilePhoto = (ImageView) rootView.findViewById(R.id.profile_photo);
Glide.with(this).load(user.getPhotoUrl()).into(profilePhoto);
fabContainer = (LinearLayout) rootView.findViewById(R.id.fabContainerLayout);
fab = (FloatingActionButton) rootView.findViewById(R.id.profile_fab);
instigatingFab = fab;
fabBaseX = fab.getX();
fabBaseY = fab.getY();
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showBlurredDialog();
}
});
progressDialog = new ProgressDialog(getContext());
uploads = new ArrayList<>();
progressDialog.setMessage("Please wait...");
progressDialog.show();
DatabaseReference followersDB = FirebaseDatabase
.getInstance()
.getReference("followers")
.child(user.getUid())
.child("count");
followersDB.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
int followersCount = dataSnapshot.getValue(Integer.class);
followersCountText.setText(Integer.toString(followersCount));
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
DatabaseReference followingReference = FirebaseDatabase.getInstance().getReference("following").child(user.getUid()).child("users");
followingReference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
DatabaseReference followingDB = FirebaseDatabase.getInstance().getReference("following").child(user.getUid()).child("count");
followingDB.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
int followingCount = dataSnapshot.getValue(Integer.class);
followingCountText.setText(Integer.toString(followingCount));
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
mDatabase = FirebaseDatabase.getInstance().getReference("/userPosts").child(user.getUid()).child("posts");
mDatabase.limitToFirst(25).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
progressDialog.dismiss();
for(DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
String postID = postSnapshot.getKey();
uploads.add(postID);
}
uploads.add("-KtvzkOL_75wiKA4CMsr");
adapter = new ProfileUserPostsViewHolder(getContext(), uploads);
recyclerView.setAdapter(adapter);
}
#Override
public void onCancelled(DatabaseError databaseError) {
progressDialog.dismiss();
}
});
return rootView;
}
As you can see I am setting the visibility for the toolbar from the HomeActivity to View.GONE, however, the toolbar is gone from all fragments now. I just want a bottom navigation setup with a top toolbar that can be hidden when certain fragments load, but is visible in other fragments. Is that even possible? Thank you.
You can control the numbers of fragments loading in view pager by simply using this method:
viewPager.setOffscreenPageLimit(1); // where n is the number of offscreen pages you want to load.
you can increase or decrease the number of fragments loading according to your requirements but atleast 1.
hope this will help you.
Hey guys I am creating an app which gets the current co-ordinates of the user and then show them on the map which is implemented on the activity.
But my problem is that the map is not movable. I have tried getUiSettings().setScrollGesturesEnabled(true); but its not working.
The Code is given below:
public class Page1 extends AppCompatActivity implements OnMapReadyCallback {
private GoogleMap mMap;
String em,n;
private DrawerLayout mDrawer;
private Toolbar toolbar;
private NavigationView nvDrawer;
TextView tv1;
private static final int MY_PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION = 2;
protected LocationManager locationManager;
Location location;
private ActionBarDrawerToggle drawerToggle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_page1);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
nvDrawer = (NavigationView) findViewById(R.id.nvView);
setupDrawerContent(nvDrawer);
// Find our drawer view
mDrawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawerToggle = setupDrawerToggle();
// Tie DrawerLayout events to the ActionBarToggle
mDrawer.addDrawerListener(drawerToggle);
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
}
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.my_menu_option, menu);
tv1= (TextView) nvDrawer.findViewById(R.id.textView5);
Intent i=getIntent();
em=i.getStringExtra("k");
tv1.setText(em);
return true;
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
Location nwLocation =getLocation(LocationManager.NETWORK_PROVIDER);
if (nwLocation != null) {
double latitude = nwLocation.getLatitude();
double longitude = nwLocation.getLongitude();
LatLng location = new LatLng(latitude,longitude);
mMap.addMarker(new MarkerOptions().position(location).title("I am here"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(location));
float zoomLevel = 16; //This goes up to 21
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(location, zoomLevel));
googleMap.getUiSettings().setScrollGesturesEnabled(true);
}
else {
showSettingsAlert("Network");
}
}
public Location getLocation(String provider) {
if (locationManager.isProviderEnabled(provider)) {
if(ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION)!= PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(this,new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION},MY_PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION);
}
else {
if (locationManager != null) {
location = locationManager.getLastKnownLocation(provider);
return location;
}
}
}
return null;
}
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0 ) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, "Permission Granted", Toast.LENGTH_SHORT).show();
}
else if(grantResults[0]==PackageManager.PERMISSION_DENIED) {
Toast.makeText(this, "Permission Denied", Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(this, "Never Ask Again", Toast.LENGTH_SHORT).show();
}
}
return;
}
}
}
public void showSettingsAlert(String provider) {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(
Page1.this);
alertDialog.setTitle(provider + " Settings");
alertDialog.setMessage(provider + " is not enabled! Want to go to settings menu?");
alertDialog.setPositiveButton("Settings",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
Page1.this.startActivity(intent);
}
});
alertDialog.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alertDialog.show();
}
private ActionBarDrawerToggle setupDrawerToggle() {
return new ActionBarDrawerToggle(this, mDrawer, toolbar, R.string.drawer_open, R.string.drawer_close);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (drawerToggle.onOptionsItemSelected(item)) {
return true;
}
switch (item.getItemId()) {
case R.id.m1:
onMapReady(mMap);
return true;
case R.id.m2:
Intent i=new Intent(this,AboutUs.class);
startActivity(i);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void setupDrawerContent(final NavigationView navigationView) {
navigationView.setNavigationItemSelectedListener(
new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
selectDrawerItem(menuItem);
View headerLayout = navigationView.getHeaderView(0);
return true;
}
});
}
public void selectDrawerItem(MenuItem menuItem) {
// Create a new fragment and specify the fragment to show based on nav item clicked
switch(menuItem.getItemId()) {
case R.id.nav_first_fragment:
mFirst(menuItem);
mDrawer.closeDrawers();
break;
case R.id.nav_second_fragment:
/*Intent i = new Intent(Page1.this, ShowInfo.class);
i.putExtra("j", em);
startActivity(i);*/
Toast.makeText(this, "Location Updated", Toast.LENGTH_SHORT).show();
int a=0;
Intent i=getIntent();
a=i.getIntExtra("u",0);
Location nwLocation =getLocation(LocationManager.NETWORK_PROVIDER);
if (nwLocation != null) {
double latitude = nwLocation.getLatitude();
double longitude = nwLocation.getLongitude();
updateLocation(a,latitude,longitude);
}
else {
showSettingsAlert("Network");
}
break;
case R.id.sub1:
startActivity(new Intent(this, ShowInfo.class));
break;
case R.id.sub2:
startActivity(new Intent(this, LoginPage.class));
finish();
break;
default:
mFirst(menuItem);
mDrawer.closeDrawers();
}
menuItem.setChecked(true);
setTitle(menuItem.getTitle());
mDrawer.closeDrawers();
}
public void updateLocation(int userid,double xCoordinate,double yCoordinate){
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("userId", userid);
jsonObject.put("deviceName", "Mi4i");
jsonObject.put("xCoordinate",xCoordinate);
jsonObject.put("yCoordinate",yCoordinate);
jsonObject.toString();
} catch (JSONException e) {
e.printStackTrace();
}
final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
final OkHttpClient client = new OkHttpClient();
RequestBody body = RequestBody.create(JSON, String.valueOf(jsonObject));
final Request request = new Request.Builder()
.url("http://172.31.4.91:8090/rest/saveLocation")
.post(body)
.build();
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Request request, IOException e) {
e.printStackTrace();
}
#Override
public void onResponse(Response response) throws IOException {
if (!response.isSuccessful()) {
throw new IOException("Unexpected code " + response);
} /*else {
}*/
}
});
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
drawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
drawerToggle.onConfigurationChanged(newConfig);
}
}
The UI for this activity is :-
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:map="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.pb.larcenytest.Page1" >
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- The main content view where fragments are loaded -->
<FrameLayout
android:id="#+id/flContent"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<include
layout="#layout/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
<android.support.design.widget.NavigationView
android:id="#+id/nvView"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
app:headerLayout="#layout/nav_header"
android:background="#android:color/white"
app:menu="#menu/drawer_view" />
</android.support.v4.widget.DrawerLayout>
</fragment>
you are getting location from Network provider , this takes time
what about add location.LocationListener
public class Page1 extends AppCompatActivity implements OnMapReadyCallback,location.LocationListener {
#Override
public void onLocationChanged(Location location)
{
CameraPosition position = new CameraPosition.Builder()
.target(new LatLng(Location.getLatitude, Location.getLongitude))
.zoom(17).build();
mMap.animateCamera(CameraUpdateFactory.newCameraPosition(position));
}
}