Reputation: 103
I have the following subclass for update design rows of my gridview:
What is the simplest way when loading data in gridview to keep the scrollbar position at the current position?
public class TextAdapter : BaseAdapter
{
Context context;
List<string> Sources;
string res;
public TextAdapter(Context c, List<string> s)
{
context = c;
Sources = s;
}
public override int Count
{
get { return Sources.Count; }
}
public override Java.Lang.Object GetItem(int position)
{
return null;
}
public override long GetItemId(int position)
{
return 0;
}
// create a new ImageView for each item referenced by the Adapter
public override View GetView(int position, View convertView, ViewGroup parent)
{
TextView textView;
if (convertView == null)
{
textView = new TextView(context);
textView.SetLines(6);
}
else
{
textView = (TextView)convertView;
}
textView.SetText(Sources[position], null);
return textView;
}
What is the simplest way when loading data in gridview to keep the scrollbar position at the current position?
Gridview:
<GridView
android:id="@+id/gvContagem"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:numColumns="1"
android:textStyle="bold"
android:layout_below="@+id/headerLabel"
android:layout_marginTop="33dp" />
.CS File:
readonly JavaList<String> artigos = new JavaList<string>();
List<string> mItems = new List<string>();
GridView gvContagem = FindViewById<GridView>(Resource.Id.gvContagem);
sqliteConnection con = new SqliteConnection("Data Source = " + BaseDados);
con.Open();
artigos.Clear();
string stm = "SELECT Artigo, Descricao FROM Trend";
using (SqliteCommand cmd = new SqliteCommand(stm, con))
{
using (SqliteDataReader rdr = cmd.ExecuteReader())
{
while (rdr.Read())
{
artigos.Add(rdr.GetValue(0) + rdr.GetValue(1));
}
}
}
gvContagem.Adapter = new TextAdapter(this,artigos);
Upvotes: 1
Views: 386
Reputation: 6088
I was able to make a working sample with fairly minimal effort as it turns out.
Try the following (adding two lines of code, one before and one after you create the new TextAdapter
:
IParcelable gridViewState = gvContagem.OnSaveInstanceState(); // <-- save scroll position
gvContagem.Adapter = new TextAdapter(this, artigos);
gvContagem.OnRestoreInstanceState(gridViewState); // <-- Load scroll position
I tested the above and it works, but if the new data set is smaller than the old data set, and you were scrolled on the old data set to beyond where the new data set extends, then the new data will be scrolled to the end. In other words if the old data set had 20 items, and the new data set has 10 items, and you were scrolled so that item 15 is at the bottom, when the new smaller data set is loaded, you will be scrolled so that item 10 is at the bottom.
By the way, there was a somewhat duplicate question answered here: Maintain Scroll Position of GridView through Screen Rotation , but with native Java code.
Upvotes: 1