how to scroll listview to specific position in android programmatically - android

I try to make listview to scroll to position , i have tried all possible functions but all not work
for more explanation of code
firstly : i put markers on map then call list adapter
secondly L if user click marker on map the list view should show the selected position as marker clicked
private void Putting_places_on_Map(final List<PlaceModel> Places) {
// TODO Auto-generated method stub
for (int i = 0; i < Places.size(); i++) {
LatLng place_loc = new LatLng(Double.parseDouble(Places.get(i)
.getLatitude()), Double.parseDouble(Places.get(i)
.getLongitude()));
map.addMarker(new MarkerOptions().position(place_loc).icon(
BitmapDescriptorFactory
.fromResource(R.drawable.glossygreencirclemarker)));
}
// when marker clicked
map.setOnMarkerClickListener(new OnMarkerClickListener() {
#Override
public boolean onMarkerClick(Marker marker) {
// TODO Auto-generated method stub
LatLng PlaceLocation = marker.getPosition();
int selected_marker=-1;
for (int i = 0; i < Places.size(); i++) {
if (PlaceLocation.latitude == Double.parseDouble(Places
.get(i).getLatitude())
&& PlaceLocation.longitude == Double
.parseDouble(Places.get(i).getLongitude())) {
selected_marker=i;
}
}
Update_List_Places(Places, selected_marker);
return false;
}
});
}
private void Update_List_Places(List<PlaceModel> Places,
int selected_marker_position) {
// TODO Auto-generated method stub
list_places_returned = true;
ListPlacesNearbyAdapter placesNearbyAdapter = new ListPlacesNearbyAdapter(
(ArrayList<PlaceModel>) Places, activity,
selected_marker_position);
placesNearbyAdapter.notifyDataSetChanged();
if(selected_marker_position != -1){
//listview_nearby_locations.setSelection(selected_marker_position);
//listview_nearby_locations.smoothScrollToPosition(selected_marker_position);
//listview_nearby_locations.setSelectionFromTop(selected_marker_position, 100);
int y= selected_marker_position*40;
listview_nearby_locations.scrollTo(0,y);
}
listview_nearby_locations.setAdapter(placesNearbyAdapter);
}
see this pic

Try this:
listview_nearby_locations.setSelection(9);

For a direct scroll:
getListView().setSelection(21);
For a smooth scroll:
getListView().smoothScrollToPosition(21);
Taken from here: Programmatically scroll to a specific position in an Android ListView

thanks guys i used this
Runnable runnable = new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
if(selected_marker_position != -1){
listview_nearby_locations.setSelection(selected_marker_position);
}
}
};
runnable.run();

Use the following code..
context.yourListView.smoothScrollToPosition(10);

Related

Google Map info window adapter

I am trying to impliment InfoWindow Adapter.
I am facing the problem of having info for the first marker being displayed for all markers.
I have read that i have to impliment OnInfoWindowClickListener() but i failed to .
The code the load the map is as below.
public void getBridgeData()
{
db= new DbHelperClass(this);
bridges= db.getAllBridges();
DecimalFormat dc=new DecimalFormat("#.00");
Builder builder= new LatLngBounds.Builder();
for (int i= 0;i<bridges.size();i++)
{
final Bridge b= (Bridge)bridges.get(i);
// get bridge info
double lati= b.getLatitude();
double longo= b.getLongitude();
// references for calculating Chainage
double reflat= b.getReflat();
double reflong= b.getReflong();
LatLng start = new LatLng(reflat,reflong);
LatLng end = new LatLng(lati,longo);
GeneralUtils uts= new GeneralUtils();
final double ch= uts.calculateDistance(start, end);
final String schainage ="Chainage:" + dc.format(ch) + "Km";
map.setInfoWindowAdapter(new InfoWindowAdapter() {
#Override
public View getInfoWindow(Marker arg0) {
// TODO Auto-generated method stub
View v = getLayoutInflater().inflate(R.layout.infor_window, null);
// set custom window info details
TextView bname= (TextView) v.findViewById(R.id.bridge);
String txtname="Bridge Name:" + b.getBridgename();
bname.setText(txtname);
TextView rname= (TextView) v.findViewById(R.id.road_name);
String txtroad="Road:" + b.getRoadname();
rname.setText(txtroad);
TextView chainage= (TextView) v.findViewById(R.id.chainage);
chainage.setText( schainage);
TextView btype= (TextView) v.findViewById(R.id.bridge_type);
String txttype= "Bridge Type:" + b.getBridgetype();
btype.setText(txttype);
TextView blength= (TextView) v.findViewById(R.id.bridge_length);
String l= "Length:" + b.getBridgelength() + "M";
blength.setText(l);
TextView bwidth= (TextView) v.findViewById(R.id.bridge_width);
String w= "Width:" + b.getBridgewidth() + "M";
bwidth.setText(w);
return v;
}
#Override
public View getInfoContents(Marker arg0) {
return null;
}
});
Marker mm=map.addMarker(new MarkerOptions().position(
new LatLng(lati, longo))
);
//mm.showInfoWindow();
builder.include(mm.getPosition());
}
final LatLngBounds bounds= builder.build();
map.setOnMapLoadedCallback(new GoogleMap.OnMapLoadedCallback() {
#Override
public void onMapLoaded() {
// TODO Auto-generated method stub
map.moveCamera(CameraUpdateFactory.newLatLngBounds(bounds, 20));
map.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
}
});
map.setOnInfoWindowClickListener(new OnInfoWindowClickListener() {
#Override
public void onInfoWindowClick(Marker arg0) {
arg0.showInfoWindow();
}
});
}
Any ideas on how to make it work?
Ronald
The problem is that you put the map.setInfoWindowAdapter in the for loop which will change and change each time you iterate the data.. so the last data of the bridges will be the infowindow layout so that why all of your info window are identical..
Solution:
instead if putting the map.setInfoWindowAdapter in the forloop. just set the bridges as a tag to the marker and use the marker parameter getInfoWindow(Marker arg0) to get the tag..

How to make item visible and invisible by clicking same line?

I have one Linearlayout - totalincome and another TableLayout normalincometable, which should appear just below the totalincome. normalincometable will be invisible when the program runs. When the user clicks on "totalincome" the table should display. If the user clicks on "totalincome again", the table should disappear. I have tried this code, but It didnt work.
totalincome.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
int x =0;
// TODO Auto-generated method stub
if (x==0)
{
normalincometable.setVisibility(View.VISIBLE);
x=1;
}
else
{
normalincometable.setVisibility(View.GONE);
x=0;
}
});
}
From this code, I can make the table visible in first click but It doesnt disappear in next click. Are there any options ?
Try this:
#Override
public void onClick(View v) {
if(normalincometable.getVisibility() == View.VISIBLE) {
normalincometable.setVisibility(View.GONE);
} else {
normalincometable.setVisibility(View.VISIBLE);
}
}
You have declared int x =0; inside onClick method. So, when ever onClick is called, it assigns 0 to "x". Declare it outside at class scope.
because you have define x in the button click code so whenever button click it set to 0. define x outside the button click scope.
try this way:put x variable outside the button onclick() or defined x globally
int x =0;
totalincome.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (x==0)
{
normalincometable.setVisibility(View.VISIBLE);
x=1;
}
else
{
normalincometable.setVisibility(View.GONE);
x=0;
}
});
}
Use like this:
int x =0;
totalincome.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (x==0)
{
normalincometable.setVisibility(View.VISIBLE);
x=1;
}
else
{
normalincometable.setVisibility(View.GONE);
x=0;
}
});
}
Try this
Boolean isFirstTimeClicked=true;
totalincome.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (isFirstTimeClicked)
{
normalincometable.setVisibility(View.VISIBLE);
}
else
{
normalincometable.setVisibility(View.GONE);
}
isFirstTimeClicked=!isFirstTimeClicked;
});
}
and in your code you have declared int x =0; inside onClick method. So, when ever onClick is called, it assigns 0 to "x". Declare it outside at class scope.
Easiest Method is
button.setVisibility(View.VISIBLE == button.getVisibility() ? View.GONE:View.VISIBLE);

Android map v2-Get marker position on marker click

How to get marker item position on marker click just like in ListView's itemclick?
ok i got the answer
#Override
public void onInfoWindowClick(Marker marker) {
// TODO Auto-generated method stub
System.out.println("onInfoWindowClick method calling and marker position is "+marker.getPosition());
String title =marker.getTitle();
for(int i=0;i<CommonUtilities.CoffeeShop_array_list.size();i++){
String s =CommonUtilities.CoffeeShop_array_list.get(i).Title;
if(title.equalsIgnoreCase(s)){
**marker_position** = i;
System.out.println("position of marker - "+marker_position);
}
}
}
This may help you
mGoogleMap.setOnInfoWindowClickListener(
new OnInfoWindowClickListener(){
#Override
public void onInfoWindowClick(Marker arg0) {
// TODO Auto-generated method stub
arg0.hideInfoWindow();
double dlat =arg0.getPosition().latitude;
double dlon =arg0.getPosition().longitude;
String slat = String.valueOf(dlat);
String slon = String.valueOf(dlon);
alert.showpickAlertDialog2(PlacesMapActivity.this,slat , slon, arg0.getSnippet());
}
}
);
Here is a short code for get location from marker:-
LatLng myLatLng = new LatLng(myMarker.getPosition().latitude,myMarker.getPosition().longitude);
try it.

How two build two line of text and one image in one item?

i am using java android .
i have a problem in my app and i need some code that can make my item has two lines of texts and one image .
please save me and help .
here is the code for what i tried please make sure that you can help and give your opinion and how i can solve it cause i stucked here.
the main activity
private void setUpView() {
// TODO Auto-generated method stub
etInput = (EditText)this.findViewById(R.id.editText_input);
Pinput = (EditText)this.findViewById(R.id.editText1);
btnAdd = (Button)this.findViewById(R.id.button_add);
lvItem = (ListView)this.findViewById(R.id.listView_items);
itemArrey = new ArrayList<String>();
itemAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,itemArrey);
lvItem.setAdapter(itemAdapter);
btnAdd.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
addItemList();
}
});
etInput.setOnKeyListener(new View.OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
// TODO Auto-generated method stub
if (keyCode == KeyEvent.KEYCODE_ENTER){
addItemList();
}
return false ;
}
});
Pinput.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(keyCode== KeyEvent.KEYCODE_NUM) {
addItemList();
}
return;
}
});
}
protected void addItemList() {
// TODO Auto-generated method stub
// TODO Auto-generated method stub
if (isInputValid(Pinput )) {
itemArrey.add(Pinput.getText().toString());
itemArrey.add(etInput.getText().toString());
Pinput.setText("");
etInput.setText("");
itemAdapter.notifyDataSetChanged();
} if (isInputValid(etInput )) {
itemArrey.add(Pinput.getText().toString());
itemArrey.add(etInput.getText().toString());
Pinput.setText("");
etInput.setText("");
itemAdapter.notifyDataSetChanged();
}
}
protected boolean isInputValid(EditText etInput2 ) {
// TODO Auto-generatd method stub
if (etInput2.getText().toString().trim().length()<1) {
return false;
} else {
return true;
}
}
}
If you want a custom view in your ListView I recommend doing one xml layout by yourself and replace android.R.layout.simple_list_item_1 in your Adapter call with the new created one.
This would be the easiest way but as I think that you might need more freedom to create/modify the content of the row, I strongly suggest to create your own Adapter extending from BaseAdapter. In the getView() method of the adapter you can easily inflate and set up the layout like you want for that row.
Okie... you tag android-listview and list view item. So I think you need list view with image and and Text.
For that you have to use Custom List View.
See this
May be this will help you. and not then pls make your que more clear. :)

Start new Activity on MapOverlay Tapping

I am new to Android.I am building one Tabbed app having 5 Tabs.I use different ViewGroups, each tab have there respactive ViewGroup according to as per need & there child Activities.First tab is TabGroupHome having different child Activities.TabGroupHome first start GoogleMapActivity (having overlayItems) as its child activity. these overlays reprasents different users. I get the data of these users from one JSONArray which is returned by one php file on server having data of differnt users. when i launch my App its look->
launching_view!
it have one actionbar on the top having different buttons(e.g., List, profile & refresh). when i click on List it show me one list of all users ->
list of Users! & user_profile!!
& when i click on listItem it show me complete profile of respactive User pointed above
Where i stuck off is-> ??? i want to show this profile of user when i tap on MapPin...
my code to do this is->
public class GoogleMapActivity extends MapActivity implements ActionBar {
Button btnOnMapList, btnProfileHome, btnRefresh;
Intent intent;
private JSONArray jArray;
private JSONObject jFan_Data;
private ItemBean bean;
private FansData fansdata;//reference of FansData class that return me JSONArray
HelloItemizedOverlay itemizedOverlay;//..........
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
btnProfileHome = (Button) findViewById(R.id.btn_profile_home);
btnOnMapList = (Button) findViewById(R.id.btn_list_home);
btnRefresh = (Button) findViewById(R.id.btn_refresh_home);
super.onCreate(savedInstanceState);
setContentView(R.layout.googlemapactivity);
MapView mapView = (MapView) findViewById(R.id.mapview);
mapView.setBuiltInZoomControls(true);
mapView.displayZoomControls(true);
// mapView.setSatellite(true);
/**TG_1 -> Here i write code to get my current location(e.g., through LocationManager)
* after getting location, i write my location`s latitude & longitude into
* shearedPreference */
//geading preference to get my unique id
SharedPreferences myUid=GoogleMapActivity.this.getSharedPreferences("uid", MODE_WORLD_READABLE);
String myId=myUid.getString("myId", "");
Log.i("MyUid", myId);
/** calling FansData class to get all users data. Currently i am providing my hard codded location but i have to get it from LocationManager */
fansdata=new FansData();
jArray=fansdata.jFanDataArray(1000, 12.9716060, 77.5903760, "h9ow0");
System.out.println(jArray.toString());
/** to showing Users on map as pins */
List<Overlay> mapOverlays = mapView.getOverlays();
Drawable drawable = this.getResources().getDrawable(
R.drawable.small_football_icon);
HelloItemizedOverlay itemizedOverlay = new HelloItemizedOverlay(
drawable, getParent());
for(int i=0;i<jArray.length();i++){
try {
jFan_Data=jArray.getJSONObject(i);
GeoPoint geoPoint = new GeoPoint((int) (jFan_Data.getDouble("lat")* 1E6),
(int) (jFan_Data.getDouble("lang")* 1E6));
OverlayItem overlayitem = new OverlayItem(geoPoint, jFan_Data.getString("name"),
jFan_Data.getString("uniqid"));
itemizedOverlay.addOverlay(overlayitem);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
mapOverlays.add(itemizedOverlay);
}
#Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
#Override
public void onHomeList(View view) {
Intent in = new Intent(getParent(), MapPinsList.class);
TabGroupActivity prnt = (TabGroupActivity) getParent();
prnt.startChildActivity("MapPinsList", in);
}
#Override
public void onHomeProfile(View view) {
Intent in = new Intent(getParent(), ProfileActivity.class);
TabGroupActivity prnt = (TabGroupActivity) getParent();
prnt.startChildActivity("ProfileActivity", in);
}
#Override
public void onHomeRefresh(View view) {
// TODO Auto-generated method stub
}
#Override
public void onListMap(View view) {
// TODO Auto-generated method stub
}
#Override
public void onListProfile(View view) {
// TODO Auto-generated method stub
}
}
My HelloItemizedOverlay Class is->
public class HelloItemizedOverlay extends ItemizedOverlay {
private static final int VIEW_PROFILE = 1;
private static final int SEND_MASSAGE = 2;
OverlayItem item;
private ArrayList<OverlayItem> mOverlays = new ArrayList<OverlayItem>();
Context mContext;
public HelloItemizedOverlay(Drawable defaultMarker) {
super(boundCenterBottom(defaultMarker));
}
public HelloItemizedOverlay(Drawable defaultMaker, Context context) {
// super(defaultMaker);
super(boundCenterBottom(defaultMaker));
mContext = context;
}
#Override
public boolean onTap(int index) {
// Option to select on clicking pin
final String[] option = new String[] { "View Profile", "Send Massage",
"Cancle" };
// to hold option
ArrayAdapter<String> adapter = new ArrayAdapter<String>(mContext,
android.R.layout.select_dialog_item, option);
//OverlayItem item = mOverlays.get(index);
item = mOverlays.get(index);
AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
builder.setTitle(item.getTitle());
// builder.setMessage(item.getSnippet());
builder.setAdapter(adapter, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int i) {
// TODO Auto-generated method stub
if (i == 0) {
String fId=item.getSnippet();
Toast.makeText(mContext, "Profile View is on Progress...!"+fId,
Toast.LENGTH_SHORT).show();
Intent in = new Intent(mContext, FanProfile.class);
Bundle fBundle= new Bundle();
fBundle.putString("fanId", fId);
in.putExtras(fBundle);
in.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
mContext.getApplicationContext().startActivity(in);
} else if (i == 1) {
Toast.makeText(mContext,"Send Massage View is on Progress...!",
Toast.LENGTH_SHORT).show();
} else if (i == 2) {
dialog.cancel();
}
}
});
builder.show();
// AlertDialog dialog= builder.create();
return true;
}
public void addOverlay(OverlayItem overlayItem) {
// for(int i=0;i<=size();i++){
mOverlays.add(overlayItem);
populate();
// }
}
#Override
protected OverlayItem createItem(int i) {
// TODO Auto-generated method stub
return mOverlays.get(i);
}
#Override
public int size() {
// TODO Auto-generated method stub
return mOverlays.size();
}
}
FanProfile in "onTap" is the same activity which i call when i click on listItem of user`s list!
above code works but it start the view over my tabView which hides my Tabs...
[this] http://i.stack.imgur.com/lgT2G.png
i am not getting where i commit mistake or doing WRONG.
Your suggestions are valuable for me!!!
I would greatly appreciate pointers or sample code to where I get the solution of this problem...
One possible solution is to add Tabs to the FanProfile activity which are same as the Previous activity
here after a long R&D i get the solution the correct way to show FanProfile when i tap on MapPin is
#Override
public void onClick(DialogInterface dialog, int i) {
// TODO Auto-generated method stub
if (i == 0) {
//getting the unique-id of fan, whose pin is clicked on map`s pins
String fId=item.getSnippet();
Toast.makeText(mContext, "Profile View is on Progress...!"+fId,
Toast.LENGTH_SHORT).show();
//getting the parent context(cast the context of GoogleMapActivity into its Parent e.g.,"TabGroupActivity")
/** i cast the mContext into its parent Activity`s context which extends ViewGroup */
tga=(TabGroupActivity)mContext;
//1.intent that start my "FanProfile" Activity
Intent in = new Intent(tga, FanProfile.class);
//2.Bundle that hold data which i want to send to "FanProfile" Activity.
Bundle fBundle= new Bundle();
//3.putting values into bundle
fBundle.putString("fanId", fId);
//4.Binding the bundle with the intent
in.putExtras(fBundle);
//5.Starting intent
tga.startChildActivity("FanProfile", in);
} else if (i == 1) {
Toast.makeText(mContext,
"Send Massage View is on Progress...!",
Toast.LENGTH_SHORT).show();
} else if (i == 2) {
dialog.cancel();
}
}
This Works well & now i am happy that i get which need -> this!
Tanks a lot #Rajdeep Dua for youe`s Valuable suggestion!!! I will again thankful to "StackOverFlow" & you all & hoping the same cooperation & suggestions from all...
StackOverFlow is really a nice fantastic -> fabulous ->
fantabulous ... :)

Categories

Resources