Adding items to textview and scrollbar stays consistent - android

I am working on an Android app. In my app there is an activity that it has a ListView. ListView elements changes dynamically (programmatically). But when I add a new element, listview scrolls and I don't want it. I want to adding elements to listview and user see new elements just when user interact with it, not automatically. I call notifyDataSetChanged() on listview adapter.
I have an example to clear my mean:
ListView contains = **{ 1 , 2 , 3 , 4 , 5}
But screen size just allow 3 of them. Suppose now {3, 4, 5} are in screen.
Now, we add the '6' element and listview automatically scrolls to top and screen shows {4 , 5 , 6}
I want to when I add the '6' element, listview don't scrolls and shows the same things (to be consistent) and if user interact with listview and scroll, he see '6' element.

Just call listView.setSelectionAfterHeaderView(); after updating the list

I am new to android too.
I tried adding elements to listview on button click, i didnt face those problems....
<RelativeLayout
...>
<ListView
android:id="#+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_marginTop="133dp">
</ListView>
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="55dp"
android:text="Button" />
public class MainActivity extends Activity {
ListView lv;
Button btn;
int counter = 0;
ArrayAdapter<String> adapter;
ArrayList<String> array = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv = (ListView) findViewById(R.id.listView1);
btn = (Button) findViewById(R.id.button1);
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, array);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String s = "Clicked "+ ++counter;
array.add(s);
adapter.notifyDataSetChanged();
}
});
lv.setAdapter(adapter);
}
}
It doesn't auto scroll to the bottom.
But if you add
android:stackFromBottom="true"
android:transcriptMode="alwaysScroll"
to the listview xml then it auto scroll to the bottom when you add a new element to the listview.
I hope it helps.

Related

How to add ListView items on button click using adapter

How to take data that was typed in EditText and by clicking "submit" in that window should add it to previous activity listview items?
What I need to do is:
Creating EditText and submit button
Creating listview in same Activity
By clicking submit button it should display it in listview.
I saw this similar question here:add items to listview dynamically android
But i couldn't understand the answer.Somebody please explain how to do this.
You just do the following :
Prepare your xml like this :
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<EditText
android:id="#+id/editText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_toLeftOf="#+id/addItem"
android:hint="Add a new item to List View" />
<Button
android:id="#+id/addItem"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:text="Add" />
<ListView
android:id="#+id/listView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/editText" >
</ListView>
</RelativeLayout>
Activity looks like following :
public class MainActivity extends Activity {
EditText editText;
Button addButton;
ListView listView;
ArrayList<String> listItems;
ArrayAdapter<String> adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText = (EditText) findViewById(R.id.editText);
addButton = (Button) findViewById(R.id.addItem);
listView = (ListView) findViewById(R.id.listView);
listItems = new ArrayList<String>();
listItems.add("First Item - added on Activity Create");
adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, listItems);
listView.setAdapter(adapter);
addButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
listItems.add(editText.getText().toString());
adapter.notifyDataSetChanged();
}
});
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> a, View v, int position,
long id) {
Toast.makeText(MainActivity.this, "Clicked", Toast.LENGTH_LONG)
.show();
}
});
}
}
Create String Arraylist and initialize it
ArrayList<String> str1 = new ArrayList<String>();
Add some values on it
str1.add("First Row");
str1.add("Second Row");
str1.add("Third Row");
str1.add("Fourth Row");
str1.add("Fifth Row");
Then set Adapter to ListView
adapter=new ListAdapter(this,str1);
list.setAdapter(adapter);
then add your EditText text into str1 and then called adapter.notifyDataSetChanged(); like
str1.add(edit_message.getText().toString());
adapter.notifyDataSetChanged();
Try to add this code into Button onclick()
Demo Output:
Suppose you have an arraylist
ArrayList<String> dataList = new Arraylist ();
So On clicking of button, you need to add the new data item into your data arraylist.
For this first take the value entered in edittext and store in a string.
String editedValue = yourEditText.getText.toString();
Then we need to add this in our datalist.
Like
dataList.add(editedValue);
And then just call adapter.notifyDataSetChanged()
yourAdapter.notifyDataSetChanged();
It will work.

Android Views within Layouts

Ok so I'm running into problems creating an app (force closing) and I think it has to do with the way I implemented the layout. So a few questions: First, I have a relative layout that includes a text input with a button next to it, a list view (still within the relative layout) and another button below that. This is my main xml file:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/RelativeLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
<EditText
android:id="#+id/edit_choice"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/Button1"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_toLeftOf="#+id/Button1"
android:hint="#string/edit_choice" />
<Button
android:id="#+id/Button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:onClick="addString"
android:text="#string/button_add" />
<Button
android:id="#+id/Button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="22dp"
android:text="#string/button_random" />
<ListView
android:id="#+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_above="#+id/Button2"
android:layout_alignParentLeft="true"
android:layout_below="#+id/Button1"
tools:listitem="#android:layout/simple_list_item_1" >
</ListView>
</RelativeLayout>
Before I even changed anything in the .java files when I tried running this, only the text input and the 2 buttons appeared and the theme changed from Holo to Holo light. So I'm wondering if this works, I've only seen examples where the list view matches the parent layout completely.
My second question is how do I handle using the input to add values to the list view, can I do that in the main activity class or can I have another class to handle the list view and still reference the main layout.
This is my Main class:
public class MainActivity extends Activity
{
public ArrayList <String> choices = new ArrayList <String>();
public ListView listView = (ListView) findViewById(R.id.listView1);
public String [] choicesArray;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView listView = (ListView) findViewById(R.id.listView1);
choicesArray = new String [] {"You have not entered a choice yet"};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, android.R.id.text1, choicesArray);
listView.setAdapter(adapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
//adds the string to the list
public void addString(View view)
{
choicesArray = (String[]) choices.toArray();
EditText editText = (EditText) findViewById(R.id.edit_choice);
String message = editText.getText().toString();
choices.add(message);
}
}
Hopefully this makes sense and thank you for any help.
Problem is you are calling this line
public ListView listView = (ListView) findViewById(R.id.listView1);
before setting content view by setContentView() method in onCreate() so you are getting NullPointerException. Do not forget that before calling findViewById you have to set content view. So delete above line because you are creating function scope listView in onCreate method and your NullPointerException problem will be solved. And also change first line of addString method like this
choicesArray = choices.toArray(choicesArray);
Define your ArrayAdapter as member for your class (not as variable
in onCreate()).
Set the adapter to your listView in onCreate().
Set the onClickListener for your button.
Add the text from EditText to your adapter when you click on the
button.
Profit!

listview adding spinner in each row?

I am facing problem while putting Spinner in layout. My acctual requirement is to place Spinner once, at the top of layout.
This output I am getting:
I have Relative layout
<Spinner
android:id="#+id/spinner1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:entries="#array/string_array"
android:prompt="#string/spinner_msg"
/>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/notesTextView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textColor="#android:color/white"
android:minHeight="?android:attr/listPreferredItemHeight"
android:gravity="center_vertical"
android:textAppearance="?android:attr/textAppearanceMedium"
</TextView>`
MyActivity class is extended by ListActivity here's onCreate method
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
listView=getListView();
listView.setOnItemClickListener(listener);
spinner1=(Spinner)findViewById(R.id.spinner1);
getDetailsCursor();
String[] from = new String[] {"db_column"};
int[] to = new int[] { R.id.notesTextView};
curAdapter=new SimpleCursorAdapter(MyActivity.this, R.layout.mylist, null, from, to);
setListAdapter(curAdapter);
registerForContextMenu(listView);
}`
Here is the code in which spinner inflates on the top of listview :
listView= (ListView) findViewById(R.id.list);
LayoutInflater inflater = LayoutInflater.from(this);
View mTop = inflater.inflate(R.layout.spin, null);
authorityView.addHeaderView(mTop);
R.layout.spin is that layout which contains only spinner.
And inside the List you have to inflate textView only. as you are doing in mylist.xml ,
just remove spinner from it and made seprate xml for spinner.
so spinner is once, at the top of layout (ListView).
I have some difficulty making out what your actual question is, some layout.xml code would help here, too. I think, that you are placing the spinner inside the listitem.xml instead of the main.xml, so that it gets replicated for each item in your listview. Please share some code.
Since you declare both the TextView and the Spinner in mylist.xml, you get both those elements in each Item of your List.
If you only want one spinner, you shouldn't use a ListActivity, but instead create a normal Activity with a Spinner and a ListView in the Layout. Then define another layout to use for the list items (e.g. with only the TextView).

Create a new listview when a button is pressed in android

I am a newbie to android programming
I have two listviews in my activity and two buttons. If I press first button one listview will be created and shown in the activity and when the second button is clicked the second listview is created and first one should be closed.
Can anyone suggest me how to do this??
Thanks in advance..
The easy option will be to change the list adapter on a list at runtime on button click.
like
on first button click
list.setAdapter(adapter1);
on second button click
list.setAdapter(adapter2);
And You can use tabs also to show two lists
See this example for
http://joshclemm.com/blog/?p=59
and
http://www.edumobile.org/android/android-beginner-tutorials/tab-control/
You should consider using fragments. Use a frame layout in your main activity. Then depending on the user choice load one of the fragment dynamically.
case (R.id.button1):
FragmentTransaction fragmentTransaction = fragmentManager
.beginTransaction();
fragmentTransaction.replace(R.id.fragment, frag1);
fragmentTransaction.commit();
break;
See http://developer.android.com/guide/components/fragments.html && http://android-developers.blogspot.com/2011/02/android-30-fragments-api.html
It sounds very much like a Tab interface. So this should be easy with
http://developer.android.com/reference/android/app/ActionBar.html#newTab()
The documentation there has a full implementation example using fragments. You might not have used fragments before but don't fear, they are basically just views. Get the example working before trying to get the listviews flying around.
Hope this helps!
Try this,
While i pressed second button
firstlistView.setVisibility(1);(1->Invisible state)first listview goes invisible state
secondlistview.setVisiblity(0);(0->Visible)Ur second listview shown by this code
if u want to display two list on two different button,you can use just one list with two different
ArrayAdapter and change list.
sample code...
Put this code in your xml file
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="List1" />
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_toRightOf="#+id/button1"
android:text="List2" />
<ListView
android:id="#+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/button1" >
</ListView>
</RelativeLayout>
Put this code in your Activity
public class MainActivity extends Activity {
ListView listView1;
Button list1Button,list2Button;
ArrayAdapter<String> adapter1,adapter2;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView1 = (ListView)findViewById(R.id.listView1);
list1Button = (Button)findViewById(R.id.button1);
list2Button = (Button)findViewById(R.id.button2);
String[] names1 = {"Android","Iphone","Titenium"};
String[] names2 = {"java",".net","php"};
adapter1 = new ArrayAdapter<String>(MainActivity.this,android.R.layout.simple_list_item_1,names1);
adapter2 = new ArrayAdapter<String>(MainActivity.this,android.R.layout.simple_list_item_1,names2);
listView1.setAdapter(adapter1);
list1Button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
listView1.setAdapter(null);
listView1.setAdapter(adapter1);
}
});
list2Button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
listView1.setAdapter(null);
listView1.setAdapter(adapter2);
}
});
}
}
i hope this may help you..

How to set a single image for an android ListView background?

I have used this code for the row layout:
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:background="#drawable/bckimage"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="10dp"
android:textSize="16sp" >
</TextView>
and this is for the class that builds the list:
public class ListTestActivity extends ListActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
String[] myArray = new String[] {...};
super.onCreate(savedInstanceState);
setListAdapter(new ArrayAdapter<String>(this, R.layout.listlayout,myArray));
ListView listView = getListView();
listView.setCacheColorHint(0);
listView.setBackgroundResource(R.drawable.bckimage);
listView.setTextFilterEnabled(true);
listView.setOnItemClickListener(new OnItemClickListener() {
//. . .
});
}
}
This shows an image for each row, not for the whole background. How can I add a single image for background? I saw several methods in here also but nothing worked.
Set the image as the background for the ListView element instead:
getListView().setBackgroundResource(R.drawable.bckimage);
Your list rows probably hide the background image. Also add:
getListView().setCacheColorHint(android.R.color.transparent);
As you stated, set background to your list and not to the row layout.
You can set background to your list in following way:
((ListView)findViewById(android.R.id.list)).setBackgroundResource(R.drawable.bckimage);
Whenever you are using ListActivity, it have ListView with id "list".

Categories

Resources