I create a custom listview and it extend ListActivity and works fine. But I want to put a ListView in my main activity that extends Activity. How can I do this?
For example, I want to put a custom ListView in my one part of my screen not the screen filled by only ONE ListView that extends ListActivity.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:id="#+id/lvresult"
android:paddingTop="2dip"
android:paddingBottom="3dip"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
</LinearLayout>
and this is MyListActivity:
package Dic.proj.pkg;
import java.util.ArrayList;
import android.app.ListActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class MyListActivity extends ListActivity {
EditText et;
TextView tv;
TextView tvresult;
String resulttext;
ArrayList<String> mArrayList = new ArrayList<String>();
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
String[] values = new String[] { "Android", "iPhone", "WindowsMobile",
"Blackberry", "WebOS", "Ubuntu", "Windows7", "Max OS X",
"Linux", "OS/2" };
// Use your own layout
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
R.layout.customlist, R.id.lvresult, values);
setListAdapter(adapter);
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
String item = (String) getListAdapter().getItem(position);
Toast.makeText(this, item + " selected", Toast.LENGTH_LONG).show();
}
}
This works fine but I can see only one List view on screen. I want to put this custom Listview in my main activity. How can I do this?
you do like below:-
public class StoreListActivity extends Activity {
private List<Store> mStores;
private StoreAdapter mStoreAdapter;
private ListView mListView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.store_list);
mListView = (ListView) findViewById(R.id.store_listview);
mStores = getTheStoresFromSomewhere();
mStoreAdapter = new StoreAdapter(this, mStores);
mListView.setAdapter(mStoreAdapter);
}
// roadmapscreen.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:background="#ffffff"
android:layout_height="fill_parent"
>
<ListView
android:cacheColorHint="#00000000"
android:id="#+id/roadmaplist"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:listSelector="#android:color/transparent"
android:divider="#null"/>
</RelativeLayout>
//roadmap_list_item
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#ffffff"
>
<TextView
android:id="#+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello"
android:textColor="#000000"
android:layout_marginTop="12dp"
android:layout_marginLeft="12dp"
android:textStyle="bold"
/>
</RelativeLayout>
//Main Activity
public class RoadmapActivity extends Activity {
ListView lv;
ArrayList<String> catList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.roadmapscreen);
catList=new ArrayList<String>();
catList.add("Work");
catList.add("Time");
catList.add("Money");
catList.add("Health");
catList.add("Fun & Recreation");
catList.add("Friends & Relatives");
catList.add("Spirituality & Growth");
catList.add("Home & Housework");
catList.add("Death & Dying");
catList.add("Sexual Intimacy");
catList.add("Marriage/Commitment");
catList.add("Children");
catList.add("Miscellaneous");
lv=(ListView)findViewById(R.id.roadmaplist);
lv.setAdapter(new CustomAdapter());
}
public class CustomAdapter extends BaseAdapter
{
public int getCount() {
// TODO Auto-generated method stub
return catList.size();
}
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
final ViewHolder holder;
LayoutInflater inflater=(LayoutInflater)getSystemService(LAYOUT_INFLATER_SERVICE);
if (convertView == null)
{
convertView=inflater.inflate(R.layout.roadmap_list_item, null);
holder = new ViewHolder();
}
else
{
holder = (ViewHolder) convertView.getTag();
}
holder.txt1=(TextView)convertView.findViewById(R.id.text);
convertView.setTag(holder);
holder.txt1.setText(catList.get(position));
convertView.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
}
});
return convertView;
}
class ViewHolder {
TextView txt1;
}
}
}
Related
I have a problem with the following exception:
exception:java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference
I have an Adapter class:
public class SimpleAdapter extends BaseAdapter {
private LayoutInflater lInflater;
private String [] simpleValueList;
public SimpleAdapter(Context context, String[] simpleValueList) {
lInflater = LayoutInflater.from(context);
this.simpleValueList = simpleValueList;
}
#Override
public int getCount() {
return simpleValueList.length;
}
#Override
public Object getItem(int position) {
return simpleValueList[position];
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if (view == null) {
view = lInflater.inflate(R.layout.test, parent, false);
TextView textSimple = view.findViewById(R.id.simple_list);
textHours.setText(simpleValueList[position]);
}
return view;
}
}
my CustomView class:
public class SimpleView extends View {
private String[] valueList = {"aa", "2", "bb", "3"};
private ListView listView;
private SimpleAdapter simpleAdapter;
public SimpleView(Context context, ViewGroup mviewGroup) {
super(context);
inflate(context, R.layout.test, mviewGroup);
listView = findViewById(R.id.simple_list);
simpleAdapter = new SimpleAdapter(context, valueList);
listView.setAdapter(simpleAdapter);
}
}
my Activity class:
public class SimpleActivity extends AppCompatActivity {
private SimpleView simpleView;
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LinearLayout linearLayout = findViewById(R.id.custom_view);
simpleView = new SimpleView(this, linearLayout);
linearLayout.addView(simpleView);
}
}
test. xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:custom="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="100dp"
android:layout_height="220dp"
android:layout_gravity="center">
<ListView
android:id="#+id/simple_list"
android:layout_width="100dp"
android:layout_height="100dp"
android:background="#color/orange" />
</LinearLayout>
my activity_main.xml
<?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:id="#+id/custom_view"
android:layout_width="400dp"
android:layout_height="match_parent"
android:orientation="vertical">
</LinearLayout>
If I do not add the Adapter in the SimpleView class then it works. But if I add the Adapter in the SimpleView class I get the exception:
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference. (at ...here: listView.setAdapter(simpleAdapter); (simpleView = new SimpleView(this, linearLayout));
The problem is that the code is calling the SimpleView's version of findViewById which is using test.xml, but the ListView is located in activity_main.xml in the SimpleActivity.
listView = findViewById(R.id.custom_view1);
This will return null because there is no view with the ID R.id.custom_view1 inside SimpleView.
There probably is not any need for the SimpleView class. The following lines of code could be moved into onCreate in SimpleActivity:
listView = findViewById(R.id.custom_view1);
simpleAdapter = new SimpleAdapter(context, valueList);
listView.setAdapter(simpleAdapter);
If you do want to create a CustomView on the other hand, all the views you are working with need to be in R.layout.test. You could in theory, move the ListView in there, but I think it is probably unnecessary. I would just inflate, find it and set the adapter in onCreate of the Activity.
If you do want an abstraction to contain the ListView, I would investigate putting it into a Fragment.
EDIT:
If it has to be done with a custom view then make sure the following is in test.xml:
<ListView
android:id="#+id/custom_view1"
android:layout_width="71dp"
android:layout_height="77dp"
android:orientation="vertical">
It is important to use this ID android:id="#+id/custom_view1 so that it matches up with listView = findViewById(R.id.custom_view1); in the Java code.
To void the crash you are getting now:
public SimpleView(Context context, ViewGroup mviewGroup) {
super(context);
View layout = inflate(context, R.layout.test, mviewGroup);
listView = layout.findViewById(R.id.simple_list);
simpleAdapter = new SimpleAdapter(context, valueList);
listView.setAdapter(simpleAdapter);
}
Make sure you do the find on the value being returned from inflate.
=== Code Dump ===:
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:custom="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/custom_view_container"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"/>
test.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:custom="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center">
<ListView
android:id="#+id/simple_list"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
row.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:custom="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="100dp"
android:layout_height="220dp"
android:layout_gravity="center">
<TextView
android:id="#+id/txt"
android:layout_width="100dp"
android:layout_height="100dp"/>
</LinearLayout>
ActivityMain.java:
package com.example.myapplication2000;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.LinearLayout;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LinearLayout linearLayout = findViewById(R.id.custom_view_container);
SimpleView simpleView = new SimpleView(this, linearLayout);
linearLayout.addView(simpleView);
}
}
SimpleView.java:
package com.example.myapplication2000;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
public class SimpleView extends View {
private String[] valueList = {"aa", "2", "bb", "3"};
private ListView listView;
private SimpleAdapter simpleAdapter;
public SimpleView(Context context, ViewGroup mviewGroup) {
super(context);
View layout = inflate(context, R.layout.test, mviewGroup);
listView = layout.findViewById(R.id.simple_list);
simpleAdapter = new SimpleAdapter(context, valueList);
listView.setAdapter(simpleAdapter);
}
public class SimpleAdapter extends BaseAdapter {
private LayoutInflater lInflater;
private String [] simpleValueList;
public SimpleAdapter(Context context, String[] simpleValueList) {
lInflater = LayoutInflater.from(context);
this.simpleValueList = simpleValueList;
}
#Override
public int getCount() {
return simpleValueList.length;
}
#Override
public Object getItem(int position) {
return simpleValueList[position];
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if (view == null) {
view = lInflater.inflate(R.layout.row, parent, false);
TextView textSimple = view.findViewById(R.id.txt);
textSimple.setText(simpleValueList[position]);
}
return view;
}
}
}
Sorry, I might have changed one or two of the names. I hope it does not cause any confusion.
Also, you can clean-up the layout. There are a few 'extra' LinearLayouts that I picked up from pasting in your code, but they are not really needed.
But this code is displaying 4 list items on my device.
I've utilized the following code from another StackOverflow post (How could i add a spinner in listview with its listitems by using customadapter?):
package com.android.main;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.Spinner;
public class DemoListSpinnerActivity extends Activity {
ListView _listview;
String[] itemsarray=new String[]{"one","two","three"};
ArrayAdapter<String> adapter;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
adapter=new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,itemsarray);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
_listview=(ListView)findViewById(R.id.listView1);
_listview.setAdapter(new CustomAdapter(this));
}
private class CustomAdapter extends BaseAdapter
{
LayoutInflater inflater;
public CustomAdapter(Context context)
{
inflater=LayoutInflater.from(context);
}
public int getCount() {
// TODO Auto-generated method stub
return 1;
}
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public View getView(int arg0, View convertview, ViewGroup arg2) {
ViewHolder viewHolder;
if(convertview==null)
{
convertview=inflater.inflate(R.layout.listrow,null);
viewHolder=new ViewHolder();
viewHolder.spinner=(Spinner)convertview.findViewById(R.id.spinner1);
viewHolder.spinner.setAdapter(adapter);
convertview.setTag(viewHolder);
}
else
{
viewHolder=(ViewHolder)convertview.getTag();
}
return convertview;
}
public class ViewHolder
{
Spinner spinner;
}
}
}
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/hello"
/>
<ListView android:layout_height="wrap_content" android:id="#+id/listView1" android:layout_width="match_parent"></ListView>
</LinearLayout>
listrow.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">
<Spinner android:layout_height="wrap_content" android:layout_width="match_parent" android:id="#+id/spinner1"></Spinner>
</LinearLayout>
While the layouts are obviously different from mine... I have a button that I want to be able to add a new ListViewItem.
And this new Spinner (inside of the ListViewItem) needs to be autopopulated with the String[].
So assuming I have:
FloatingActionButton addButton= (FloatingActionButton) findViewById(R.id.addButton);
addButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Add New Spinner Item
// Populate Spinner with String[]
}
});
I'm looking to add a new spinner item to the ListView, and then populate that list with the string[] earlier defined.
I want to fix a button on top of the layout and just below the button a dynamic edit text is created. I am creating my own Adapter. On button click another activity starts and returns string which is to be shown on the list view items below the button. How can I do this ?
My XML Layout -
<?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" >
<Button
android:id="#+id/button1"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button" />
<EditText
android:id="#+id/etList"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10" >
</EditText>
</LinearLayout>
My list view adapter -
package com.example.tasktable;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.TextView;
public class TaskAdapter extends ArrayAdapter<String> {
private final Context context;
private final String[] values;
Button click;
TextView textView;
public TaskAdapter(Context context, String[] values) {
super(context, R.layout.list_view, values);
this.context = context;
this.values = values;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
LayoutInflater inflator = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflator.inflate(R.layout.list_view, parent, false);
click = (Button) rowView.findViewById(R.id.button1);
textView = (TextView) rowView.findViewById(R.id.etList);
textView.setText(values[position]);
return rowView;
}
}
I don't want to inflate button with every edit text.
You can position layout elements with Relative Layouts https://developer.android.com/reference/android/widget/RelativeLayout.html
//try this way, hope this will help you...
**XML** code
**activity.xml**
<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">
<Button
android:id="#+id/btnAdd"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Add"/>
<ScrollView
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1">
<LinearLayout
android:id="#+id/lnrEdit"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
</LinearLayout>
</ScrollView>
</LinearLayout>
**list_activity.xml**
<ListView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
**list_item.xml**
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center">
<TextView
android:id="#+id/txtValue"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"/>
<Button
android:id="#+id/btnSelect"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Select"/>
</LinearLayout>
**ACTIVITY** code
**MyActivity**
public class MyActivity extends Activity{
private Button btnAdd;
private LinearLayout lnrEdit;
private final int GET_LIST_ITEM = 1;
private HashMap<String,String> listItemMap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity);
btnAdd = (Button) findViewById(R.id.btnAdd);
lnrEdit = (LinearLayout) findViewById(R.id.lnrEdit);
listItemMap = new HashMap<String, String>();
btnAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MyActivity.this,MyListActivty.class);
startActivityForResult(intent,GET_LIST_ITEM);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == RESULT_OK){
if(requestCode == GET_LIST_ITEM);
{
String getListValue = data.getStringExtra("value");
int index = data.getIntExtra("index",0);
if(listItemMap.containsKey(String.valueOf(index))){
Toast.makeText(this,"This item already taken !!!",Toast.LENGTH_LONG).show();
} else{
listItemMap.put(String.valueOf(index),getListValue);
EditText editText = new EditText(this);
editText.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
editText.setId(index);
editText.setText(getListValue);
editText.setTag(getListValue);
editText.setFocusable(false);
editText.setFocusableInTouchMode(false);
editText.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String value = v.getTag().toString();
Toast.makeText(MyActivity.this,value,Toast.LENGTH_SHORT).show();
}
});
lnrEdit.addView(editText);
}
}
}
}
}
**MyListActivity**
public class MyListActivty extends ListActivity{
private String[] listArray;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list_activity);
listArray = new String[]{"Android4.1","Android4.2","Android4.3","Android4.4","Android4.5"};
setListAdapter(new TaskAdapter(this,listArray));
}
class TaskAdapter extends ArrayAdapter<String> {
private final Context context;
private final String[] values;
public TaskAdapter(Context context, String[] values) {
super(context, R.layout.list_item, values);
this.context = context;
this.values = values;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if(convertView==null){
holder = new ViewHolder();
convertView = LayoutInflater.from(context).inflate(R.layout.list_item, parent, false);
holder.button = (Button) convertView.findViewById(R.id.btnSelect);
holder.textView = (TextView) convertView.findViewById(R.id.txtValue);
convertView.setTag(holder);
} else{
holder = (ViewHolder)convertView.getTag();
}
holder.textView.setText(values[position]);
holder.button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.putExtra("index",position);
intent.putExtra("value",values[position]);
setResult(RESULT_OK,intent);
finish();
}
});
return convertView;
}
#Override
public int getCount() {
return values.length;
}
}
static class ViewHolder{
Button button;
TextView textView;
}
}
I have a problem with my app. I have a list of items and when I select one item i want to showcase a popup with some text and with a button that will take me to another activity. With the code that i have so far i have the list but is not functional. I need to add the popup and the transition to another activity.Can someone help me with my problem?
This is what i have so far..:
MainActivity:
package com.example.test;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.widget.ListView;
public class Lesson extends Activity {
public static int [] prgmImages= {R.drawable.ic_launcher,R.drawable.ic_launcher,R.drawable.ic_launcher,
R.drawable.ic_launcher,R.drawable.ic_launcher,R.drawable.ic_launcher,
R.drawable.ic_launcher,R.drawable.ic_launcher,R.drawable.ic_launcher,
R.drawable.ic_launcher,R.drawable.ic_launcher,R.drawable.ic_launcher,};
public static String[] prgmNameList = {"Ex1","Ex2","Ex3","Ex4","Ex5","Ex6","Ex7","Ex8","Ex9","Ex10","Ex11","Ex12",};
public static String[] prgmDescription = {"asdafasdsad","asdsafasfas","aaaaaa","lkjhggfdds",
"asdafasdsad","asdsafasfas","aaaaaa","lkjhggfdds",
"asdafasdsad","asdsafasfas","aaaaaa","lkjhggfdds"};
Context context;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_lesson);
context = this;
ListView lv = (ListView) findViewById(R.id.listView1);
lv.setAdapter(new CustomAdapter(this, prgmNameList, prgmImages, prgmDescription));
}
}
CustomAdapter.java :
package com.example.test;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class CustomAdapter extends BaseAdapter {
String [] description;
String [] result;
Context context;
int [] imageId;
private static LayoutInflater inflater=null;
public CustomAdapter(Lesson lesson, String[] prgmNameList, int[] prgmImages, String[] prgmDescription){
// TODO Auto-generated constructor stub
result=prgmNameList;
description=prgmDescription;
context=lesson;
imageId=prgmImages;
inflater = ( LayoutInflater )context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return result.length;
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public class Holder
{
TextView tv;
TextView tv2;
ImageView img;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
Holder holder=new Holder();
View rowView;
rowView = inflater.inflate(R.layout.list_field, null);
holder.tv2=(TextView) rowView.findViewById(R.id.textView2);
holder.tv=(TextView) rowView.findViewById(R.id.textView1);
holder.img=(ImageView) rowView.findViewById(R.id.imageView1);
holder.tv2.setText(description[position]);
holder.tv.setText(result[position]);
holder.img.setImageResource(imageId[position]);
rowView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//Toast.makeText(context, "You Clicked "+result[position], 2000).show();
}
});
return rowView;
}
}
activity_lessons.xml:
<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"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".Lesson" >
<ListView
android:id="#+id/listView1"
android:layout_width="match_parent"
android:layout_height="300dp"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true" >
</ListView>
</RelativeLayout>
list_field:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="#+id/textView1"
android:layout_width="200dp"
android:layout_height="30dp"
android:layout_alignTop="#+id/imageView1"
android:layout_toRightOf="#+id/imageView1"
android:text="TextView" />
<TextView
android:id="#+id/textView2"
android:layout_width="200dp"
android:layout_height="18dp"
android:layout_below="#+id/textView1"
android:layout_toRightOf="#+id/imageView1"
android:text="TextView" />
<ImageView
android:id="#+id/imageView1"
android:layout_width="48dp"
android:layout_height="48dp"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true" />
</RelativeLayout>
You can open alert on item click like this :
rowView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//Toast.makeText(context, "You Clicked "+result[position], 2000).show();
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("Title");
builder.setMessage("Message");
builder.setPositiveButton("OK",
new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int id)
{
dialog.cancel();
Intent intent = new Intent(context, Activity2.class);
context.startActivity(intent);
}
});
AlertDialog alert = builder.create();
alert.show();
}
});
I am working on Android project. I follow tutorial from http://www.vogella.com/articles/AndroidSQLite/article.html but I stuck on something. Tutorial shows how to use Class with 1 String object. I am working with 2 String objects. So I changed few things (add new String to my class, change layout.simple_list_item_1 to android.R.layout.simple_list_item_2 etc.) And now the question is - how to make something to get Stoliki class objects (override toString() gives me only 1 item, so It's useless).
Class Stoliki
public class Stoliki {
private long id;
private String numer;
private String opis;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getNumer() {
return numer;
}
public void setNumer(String numer) {
this.numer = numer;
}
public String getOpis() {
return opis;
}
public void setOpis(String opis) {
this.opis = opis;
}
}
Activity
import android.app.ListActivity;
import android.os.Bundle;
import java.util.List;
import java.util.Random;
import android.view.View;
import android.widget.ArrayAdapter;
public class FirstGridPage extends ListActivity {
private StolikiDataSource datasource;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_list_stoliki);
datasource = new StolikiDataSource(this);
datasource.open();
List<Stoliki> values = datasource.getAllStoliki();
// Use the SimpleCursorAdapter to show the
// elements in a ListView
ArrayAdapter<Stoliki> adapter = new ArrayAdapter<Stoliki>(this,
android.R.layout.simple_list_item_1, values);
setListAdapter(adapter);
}
// Will be called via the onClick attribute
// of the buttons in main.xml
public void onClick(View view) {
#SuppressWarnings("unchecked")
ArrayAdapter<Stoliki> adapter = (ArrayAdapter<Stoliki>) getListAdapter();
Stoliki stolik = null;
switch (view.getId()) {
case R.id.add:
String[] stoliki_numer = new String[] { "1", "2", "3" };
String[] stoliki_opis = new String[] { "Czerwony", "Niebieski", "Zielony" };
int nextInt = new Random().nextInt(3);
// Save the new comment to the database
stolik = datasource.createStolik(stoliki_numer[nextInt], stoliki_opis[nextInt]);
adapter.add(stolik);
break;
case R.id.delete:
if (getListAdapter().getCount() > 0) {
stolik = (Stoliki) getListAdapter().getItem(0);
datasource.deleteStolik(stolik);
adapter.remove(stolik);
}
break;
}
adapter.notifyDataSetChanged();
}
#Override
protected void onResume() {
datasource.open();
super.onResume();
}
#Override
protected void onPause() {
datasource.close();
super.onPause();
}
}
http://www.youtube.com/watch?v=wDBM6wVEO70. Listview talk by Romain guy( android developer at google).
Main.xml
<ListView android:id="#+id/list"
android:layout_width="fill_parent"
android:layout_height="0dip"
android:focusableInTouchMode="false"
android:listSelector="#android:color/transparent"
android:layout_weight="2"
android:headerDividersEnabled="false"
android:footerDividersEnabled="false"
android:dividerHeight="8dp"
android:divider="#000000"
android:cacheColorHint="#000000"
android:drawSelectorOnTop="false">
</ListView>
</LinearLayout>
Customw row. row.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal"
android:background="#ffffff"
>
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView"
android:background="#drawable/itembkg"
/>
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:text="TextView" />
</LinearLayout>
public class CustomListView extends Activity {
/** Called when the activity is first created. */
ListView lv1;
Customlistadapter cus;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Button b= (Button) findViewById(R.id.remove);
lv1 = (ListView) findViewById(R.id.list);
cus= new Customlistadapter(this);
lv1.setAdapter(cus);
}
}
Custom list adapter. Inflate custom layout for each row.
public class Customlistadapter extends ArrayAdapter {
private LayoutInflater mInflater;
Context c;
public Customlistadapter(CustomListView customListView) {
super(customListView, 0);
// TODO Auto-generated constructor stub
this.mInflater = LayoutInflater.from(customListView);
c=customListView;
}
public int getCount() {
return 20; // number of listview rows.
}
public Object getItem(int arg0) {
return arg0;
}
public long getItemId(int arg0) {
return arg0;
}
public View getView(final int arg0, View arg1, ViewGroup arg2) {
final ViewHolder vh;
vh= new ViewHolder();
if(arg1==null )
{
arg1=mInflater.inflate(R.layout.row, arg2,false);
vh.tv1= (TextView)arg1.findViewById(R.id.textView1);
vh.tv2= (TextView)arg1.findViewById(R.id.textView2);
}
else
{
arg1.setTag(vh);
}
vh.tv1.setText("hello");
vh.tv2.setText("hello");
return arg1;
}
static class ViewHolder //use a viewholder for smooth scrolling and performance.
{
TextView tv1,tv2;
}
}
Edit:
Your activity will have a listview. This is set in oncreate setContentView(R.layout.activity_main);. The main layout will have a listview. You set the adapter of listview as listview.setAdapter(youradapter);
Then listview will have custom layout ie row.xml inflated for each row item. You custom adapter for listview is where the row.xml is inflated. You defined your class CustomAdapter which extends ArrayAdapter. You override a set of methods.
getCount() --- size of listview.
getItem(int position) -- returns the position
getView(int position, View convertView, ViewGroup parent)
// position is the position in the listview.
//convertview - view that is tobe inflated
// you will return the view that is infated.
You will have to use a viewholder for smooth scrolling and performance. Imagine 1000 rows is lstview with images it may cause memory exceptions. One way to get rid of this is to recycle views. The visible views(rows) are not recycled. The video in the link at the top has a detail explanation on the topic
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:background="#0095FF">
<ListView android:id="#+id/list"
android:layout_width="fill_parent"
android:layout_height="0dip"
android:focusableInTouchMode="false"
android:listSelector="#android:color/transparent"
android:layout_weight="2"
android:headerDividersEnabled="false"
android:footerDividersEnabled="false"
android:dividerHeight="8dp"
android:divider="#000000"
android:cacheColorHint="#000000"
android:drawSelectorOnTop="false">
</ListView>
</LinearLayout>
row.xml (layout inflated for each listview row)
<?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="horizontal" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Header" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="80dp"
android:layout_gravity="center"
android:text="TextView" />
</LinearLayout>
MainActivity
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView ll = (ListView) findViewById(R.id.list);
CustomAdapter cus = new CustomAdapter();
ll.setAdapter(cus);
}
class CustomAdapter extends BaseAdapter
{
LayoutInflater mInflater;
public CustomAdapter()
{
mInflater = (LayoutInflater) MainActivity.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return 30;
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
final ViewHolder vh;
vh= new ViewHolder();
if(convertView==null )
{
convertView=mInflater.inflate(R.layout.row, parent,false);
vh.tv2= (TextView)convertView.findViewById(R.id.textView2);
vh.tv1= (TextView)convertView.findViewById(R.id.textView2);
}
else
{
convertView.setTag(vh);
}
vh.tv1.setText("my text");
vh.tv2.setText("Postion = "+position);
return convertView;
}
class ViewHolder
{
TextView tv1,tv2;
}
}
}