In android development there’s a common scenario where you want a list of items and select from them.So, you may want a ListView with the items and and a button always fixed at the bottom. I googled a lot while i tried for the first time but failed to manage a good answer.So, this article may help the beginners.
Solution is very simple.Here’s my code:
package com.example.smsreceiver; import java.util.ArrayList; import android.os.Bundle; import android.app.Activity; import android.app.backup.SharedPreferencesBackupHelper; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.view.Menu; import android.view.View; import android.view.View.OnClickListener; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.ListView; import android.widget.Toast; public class MainActivity extends Activity implements OnClickListener{ private Button btn; private ListView listView; private ArrayList<String> musicList=new ArrayList<String>(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.musiclistfragment); listView=(ListView)findViewById(R.id.listViewMusic); btn=(Button)findViewById(R.id.btnok); musicList.add("Music 1"); musicList.add("Music 2"); musicList.add("Music 3"); musicList.add("Music 4"); musicList.add("Music 5"); musicList.add("Music 6"); musicList.add("Music 7"); musicList.add("Music 8"); musicList.add("Music 9"); musicList.add("Music 10"); ArrayAdapter<String> adapter=new ArrayAdapter<String>(getApplicationContext(),android.R.layout.simple_expandable_list_item_1,musicList); listView.setAdapter(adapter); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public void onClick(View v) { if(v.getId()==R.id.btncpanel) { Intent intent=new Intent(getApplicationContext(),MessageDetails.class); startActivity(intent); } } }
Here is the xml file:
I haven’t customize my ListView.Just kept it simple.You can change the weight of the components to your desired proportions if you wish.
<?xml version="1.0" encoding="utf-8"?> <LinearLayout 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" android:orientation="vertical" > <ListView android:id="@+id/listViewMusic" android:layout_width="match_parent" android:layout_height="0dip" android:background="#000000" android:layout_weight="5" > </ListView> <Button android:id="@+id/btnok" android:layout_width="match_parent" android:layout_height="0dip" android:layout_weight="1" android:text="Done" /> </LinearLayout>
Here’s a screenshot of the output: