CheckedTextView not working in custom ListView - java

I have created a ListView containig CheckedTextView.
I'm feeding the elements in this ListView via a custom ArrayAdapter.
the list is displayed fine, but the checkbox is not responding when I select the list item
Code:
MainActivity class:
public class MainActivity extends ListActivity {
ArrayList<String> m_list;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
new AsyncHandler(this).execute();
}
public class AsyncHandler extends AsyncTask {
Context context;
public AsyncHandler(Context c) {
context = c;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
Toast.makeText(context, "In onPreExecute()", Toast.LENGTH_SHORT)
.show();
}
#Override
protected Object doInBackground(Object... arg0) {
getList();
return null;
}
#Override
protected void onPostExecute(Object result) {
// super.onPostExecute(result);
setListAdapter(new ElementAdapter(context, m_list));
}
private void getList() {
m_list = new ArrayList<String>();
m_list.add("Ele 1");
m_list.add("Ele 2");
m_list.add("Ele 3");
m_list.add("Ele 4");
}
}
}
Adapter class
public class ElementAdapter extends ArrayAdapter implements OnClickListener {
ArrayList<String> items = new ArrayList<String>();
Context context;
CheckedTextView tvElement;
public ElementAdapter(Context c, ArrayList<String> elements) {
super(c, R.layout.row, elements);
this.items = elements;
this.context = c;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.row, parent, false);
tvElement = (CheckedTextView) view
.findViewById(R.id.ctvElements);
tvElement.setText(items.get(position));
tvElement.setOnClickListener(this);
return view;
}
#Override
public void onClick(View view) {
switch(view.getId()){
case R.id.ctvElements:
if(!tvElement.isChecked()){
tvElement.setChecked(true);
tvElement.setCheckMarkDrawable(android.R.drawable.checkbox_on_background);
}else{
tvElement.setChecked(false);
tvElement.setCheckMarkDrawable(android.R.drawable.checkbox_off_background);
}
notifyDataSetChanged();
}
}
}
Row 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="horizontal">
<CheckedTextView android:id="#+id/ctvElements"
android:paddingLeft="20dip" android:paddingRight="20dip"
android:paddingTop="10dip" android:paddingBottom="10dip"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="?android:attr/listPreferredItemHeight"
android:gravity="center_vertical" android:checkMark="#android:drawable/checkbox_off_background"
android:focusable="false" />
<!-- <CheckBox android:id="#+id/checkBox1" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:focusable="false" /> <TextView
android:id="#+id/tvElement" android:layout_width="wrap_content" android:layout_height="wrap_content"
android:text="Element" android:textSize="25sp" /> -->
</LinearLayout>

If you only want to add checkmarks to each row then use ListView.setChoiceMode(). The checkmarks will respond to a click anywhere in the row without adding any onClickListeners or custom Adapters.
Add this to your onCreate:
ListView listView = (ListView) findViewById(android.R.id.list);
listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
Then use the built-in ArrayAdapter:
#Override
protected void onPostExecute(Object result) {
// super.onPostExecute(result);
setListAdapter(new ArrayAdapter<String>(context, R.layout.row, m_list));
}
You can use the default checked row layout with android.R.layout.simple_list_item_checked.
Otherwise if you want some customization the ListView rows change row.xml to this:
<CheckedTextView android:id="#android:id/text1"
android:layout_height="?android:attr/listPreferredItemHeight"
android:layout_width="fill_parent"
android:checkMark="#android:drawable/checkbox_off_background"
android:gravity="center_vertical"
android:paddingLeft="20dip"
android:paddingRight="20dip"
android:paddingTop="10dip"
android:paddingBottom="10dip"
/>

Related

Set background color of one item in list view if switch is turned on

Hi I am completing a school project, and I need the background of a list item to be red with white text if the urgent switch is on. Currently, if I add an item with the urgent switch all of the background of the list view changes. I seen somewhere someone said to use an array, but when I tried that block of code it wouldn't work. Thanks in advance!
<GridLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ListView
android:id="#+id/listView"
android:layout_width="match_parent"
android:layout_height="576dp"
android:layout_columnSpan="3"
android:focusableInTouchMode="true"
android:isScrollContainer="true">
</ListView>
<EditText
android:id="#+id/editText"
android:layout_width="209dp"
android:layout_height="wrap_content"
android:layout_weight="0"
android:hint="#string/typeHere"
android:textSize="20dp" />
<Switch
android:id="#+id/switch1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_row="1"
android:layout_column="1"
android:layout_weight="0"
android:text="#string/urgent" />
<Button
android:id="#+id/buttonAdd"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_row="1"
android:layout_column="2"
android:layout_weight="0"
android:text="#string/add" />
</GridLayout>
<?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">
<TextView
android:id="#+id/to_do_TextView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Testing"
android:textSize="25dp" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
Button buttonAdd;
Boolean urgent = false;
EditText editText;
ListAdapter adapter;
ListView myListView;
Switch switch1;
ArrayList<String> itemList = new ArrayList<String>( Arrays.asList("Clean Bathroom","Buy Apples","Buy Bananas" ));
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//declare variables
buttonAdd = findViewById(R.id.buttonAdd);
editText = findViewById(R.id.editText);
switch1 = findViewById(R.id.switch1);
ListView myListView = findViewById(R.id.listView);
myListView.setAdapter(adapter = new ListAdapter());
buttonAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
itemList.add(editText.getText().toString());
editText.setText("");
//also tried setting value you here and using in getView
if(switch1.isChecked()){
urgent = true;
} else{
urgent = false;
}adapter.notifyDataSetChanged();
}
});
}
// adapter class
class ListAdapter extends BaseAdapter{
#Override
public int getCount() {
return itemList.size();
}
#Override
public Object getItem(int position) {
return itemList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View old, ViewGroup parent) {
View newView =old;
LayoutInflater inflater = getLayoutInflater();
if(newView==null){
newView = inflater.inflate(R.layout.item,parent,false);
}
TextView textview= newView.findViewById(R.id.to_do_TextView);
textview.setText(getItem(position).toString());
if(switch1.isChecked()){
textview.setBackgroundColor(Color.RED);
textview.setText(getItem(position).toString());
}return newView;
}
//to do row class
class ToDoItem {
String name;
Boolean urgent;
}}}
This happen because you use a global variable Boolean urgent to all items in list.
You need send to ListAdapter the information if is urgent with a String doing use of class ToDoItem like this:
itemList.add(new ToDoItem(itemList.add(editText.getText().toString()), switch1.isChecked()));
the full code would be:
public class MainActivity extends AppCompatActivity {
Button buttonAdd;
EditText editText;
ListAdapter adapter;
ListView myListView;
Switch switch1;
//Create list
ArrayList<ToDoItem> itemList = new ArrayList<>();
//add data
itemList.add(new ToDoItem("Clean Bathroom", false);
itemList.add(new ToDoItem("Buy Apples", false);
itemList.add(new ToDoItem("Buy Bananas", true);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//declare variables
buttonAdd = findViewById(R.id.buttonAdd);
editText = findViewById(R.id.editText);
switch1 = findViewById(R.id.switch1);
ListView myListView = findViewById(R.id.listView);
myListView.setAdapter(adapter = new ListAdapter());
buttonAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Here set to list a item with String and boolean
itemList.add(new ToDoItem(itemList.add(editText.getText().toString()), switch1.isChecked()));
editText.setText("");
adapter.notifyDataSetChanged();
}
});
}
// adapter class
class ListAdapter extends BaseAdapter{
#Override
public int getCount() {
return itemList.size();
}
//Here get a item like ToDoItem
#Override
public ToDoItem getItem(int position) {
return itemList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View old, ViewGroup parent) {
View newView =old;
LayoutInflater inflater = getLayoutInflater();
if(newView==null){
newView = inflater.inflate(R.layout.item,parent,false);
}
TextView textview= newView.findViewById(R.id.to_do_TextView);
//Here get a name
textview.setText(getItem(position).name);
if(getItem(position).urgent){
textview.setBackgroundColor(Color.RED);
}
return newView;
}
}
//Class that have the information on items
class ToDoItem {
String name;
Boolean urgent;
public ToDoItem(String name, Boolean urgent) {
this.name = name;
this.urgent = urgent;
}
}
}

Unable to display two items in customview

I want to show items in my custom listview but I cant seem to get it to work. Activity just crashes. My purpose is to show both items in a listview. I am able to retrieve and store the necessary data from firebase into separate arraylists but unable to show them in the listview. Attaching all necessary codes below.
This is my customadapter class
public class CustomAdapter extends ArrayAdapter<String>{
private final Activity context;
private final ArrayList main;
private final ArrayList sub;
public CustomAdapter(Activity context,
ArrayList main, ArrayList sub) {
super(context, R.layout.colortext, main);
this.context = context;
this.main = main;
this.sub = sub;
}
#Override
public View getView(int position, View view, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View rowView= inflater.inflate(R.layout.colortext, null, true);
TextView txtTitle = (TextView) rowView.findViewById(R.id.textmain);
TextView txtSub=rowView.findViewById(R.id.address);
txtTitle.setText((Integer) main.get(position));
txtSub.setText((Integer) sub.get(position));
return rowView;
}
}
xml of custom
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/linearLayout1"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/listView1">
</ListView>
<TextView
android:id="#+id/textmain"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:minHeight="?android:attr/listPreferredItemHeight"
android:paddingLeft="6dip"
android:paddingRight="10dip"
android:textSize="23dp"
android:textColor="#01B9F5"
android:textAppearance="?android:attr/textAppearanceLarge" />
<CheckBox
android:id="#+id/checkBox"
android:clickable="true"
android:gravity="center_vertical"
android:minHeight="?android:attr/listPreferredItemHeight"
android:paddingLeft="6dip"
android:paddingRight="10dip"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:focusable="false"
/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello"
android:id="#+id/address"
android:layout_below="#+id/checkBox"
android:textColor="#color/white"/>
</RelativeLayout>
mainactivity
mDatabase.child("users").child(mUserId).child("locs").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot ds:dataSnapshot.getChildren())
{
main.add(ds.child("title").getValue(String.class));
String g = main.toString();
sub.add(ds.child("addr").getValue(String.class));
String s = sub.toString();
ListView list = findViewById(R.id.listView1);
CustomAdapter adapter2 = new CustomAdapter(Location.this, main, sub);
list.setAdapter(adapter2);
}
}
Try this. In your adapter add these methos to add item in your arraylist.
public class CustomAdapter extends ArrayAdapter<String>{
private final ArrayList mainList;
private final ArrayList subList;
public void addMain(Main main){
mainList.add(main);
notifyDataSetChanged();
}
public void addSub(Sub sub){
subList.add(sub);
notifyDataSetChanged();
}
// manage your data in onBind
#Override
public void onBindViewHolder(final ViewHolder holder, int
position) {
if(position < mainList.size() ){
// display mainlist related data here
// after adding items in mainlist, this will executed.
}
if(position > mainList.size()-1) {
// display sublist related data here
}
}
}
You need to add mainList first for the condition in onbind will be met.
You can add data to your adapter like below.
// For example this is that path of your main lists
DatabaseReference ref = database.getReference().child("main");
ref.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
// I assume you have a custom object. In this case let's just say `Main`
Main main = dataSnapshot.getValue(Main.class);
adapter.addMain(notification);
}
// ... other override methods

customised listview using arrayadapter class in android

how to select row item using Tick mark like iphone in android?iam using imageview in list_row.xml.when i click the list row item then i show image in row imageview.
if(getItem(position)!=null){
img.setvisibilty(View.Visible);}
else{System.out.println("imagenull");}
iam using this but image display in last row only.please help me how to select item using tickmark image.
public class DistanceArrayAdapter extends ArrayAdapter<Constant>{
public static String category,state,miles;
public ImageView img;
private Context context;
private int current = -1;
ArrayList<Constant> dataObject;
public DistanceArrayAdapter(Context context, int textViewResourceId,
ArrayList<Constant> dataObject) {
super(context, textViewResourceId, dataObject);
this.context=context;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View rowView=convertView;
if(rowView==null){
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
rowView = inflater.inflate(R.layout.category_row, parent, false);
}
//TextView textView = (TextView) rowView.findViewById(R.id.text1);
TextView textView1 = (TextView) rowView.findViewById(R.id.text2);
//textView.setText(""+getItem(position).id);
textView1.setText(""+getItem(position).caption);
img=(ImageView)rowView.findViewById(R.id.img);
img.setVisibility(View.GONE);
if(position%2==1)
{
rowView.setBackgroundResource(R.color.even_list);
}
else
{
rowView.setBackgroundResource(R.color.odd_list);
}
rowView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(img.getVisibility()==View.GONE)
{
img.setVisibility(View.VISIBLE);
System.out.println("1");
}
if(img.getVisibility()==View.VISIBLE){
img.setVisibility(View.GONE);
System.out.println("12");
}
miles=getItem(position).caption;
System.out.println("miles"+miles);
}
});
return rowView;
}
}
Drawing from https://groups.google.com/forum/?fromgroups#!topic/android-developers/No0LrgJ6q2M
public class MainActivity extends Activity implements AdapterView.OnItemClickListener {
String[] GENRES = new String[] {"Action", "Adventure", "Animation", "Children", "Comedy", "Documentary", "Drama", "Foreign", "History", "Independent", "Romance", "Sci-Fi", "Television", "Thriller"};
private CheckBoxAdapter mCheckBoxAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ListView listView = (ListView) findViewById(R.id.lv);
listView.setItemsCanFocus(false);
listView.setTextFilterEnabled(true);
listView.setOnItemClickListener(this);
mCheckBoxAdapter = new CheckBoxAdapter(this, GENRES);
listView.setAdapter(mCheckBoxAdapter);
Button b = (Button) findViewById(R.id.button1);
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
StringBuilder result = new StringBuilder();
for (int i = 0; i < GENRES.length; i++) {
if (mCheckBoxAdapter.mCheckStates.get(i) == true) {
result.append(GENRES[i]);
result.append("\n");
}
}
Toast.makeText(MainActivity.this, result, 1000).show();
}
});
}
public void onItemClick(AdapterView parent, View view, int position, long id) {
mCheckBoxAdapter.toggle(position);
}
class CheckBoxAdapter extends ArrayAdapter implements CompoundButton.OnCheckedChangeListener {
LayoutInflater mInflater;
TextView tv1, tv;
CheckBox cb;
String[] gen;
private SparseBooleanArray mCheckStates;
private SparseBooleanArray mCheckStates;
CheckBoxAdapter(MainActivity context, String[] genres) {
super(context, 0, genres);
mCheckStates = new SparseBooleanArray(genres.length);
mInflater = (LayoutInflater) MainActivity.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
gen = genres;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return gen.length;
}
}
}
activity_main.xml
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ListView
android:id="#+id/lv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/button1"/>
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:text="Button" />
</RelativeLayout>
And the XML file for the checkboxes:
<?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="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="15dp"
android:layout_marginTop="34dp"
android:text="TextView" />
<CheckBox
android:id="#+id/checkBox1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_below="#+id/textView1"
android:layout_marginRight="22dp"
android:layout_marginTop="23dp" />
</RelativeLayout>
When you click the button a toast message with list of item choosen is displayed. You can modify the above according to your requirements.
Set selection mode on your ListView
//if using ListActivity or ListFragment
getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
//or
myListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
//myListView is reference to your ListView
1.Make visibility gone to you tick mark image
2.Implement view.setOnClickListener in arrayadapter.
3.In that check image.getVisibility()==View.GONE then make image.setVisibity(View.Visible)
4.if image.getVisiblity()==View.VISIBLE then make your image.setVisibity(View.GONE)
Try this.

ListView / ListAdapter with 2 strings in Android project

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;
}
}
}

How to replace fragment run time

I want to add and replace Frame layout with fragment on fragment-1 and fragment-2 on item click of Grid and List item.
I had created main.xml class
<?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" >
<LinearLayout
android:layout_width="0dp"
android:layout_weight="1"
android:orientation="vertical"
android:layout_height="fill_parent" >
<fragment
android:id="#+id/fragment1"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
class="com.example.fragment.Fragment1" />
<View
android:layout_width="fill_parent"
android:layout_height="1dp"
android:background="#000000" />
<fragment
android:id="#+id/fragment2"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
class="com.example.fragment.Fragment2" />
</LinearLayout>
<View
android:layout_width="1dp"
android:layout_height="fill_parent"
android:background="#000000" />
<FrameLayout
android:id="#+id/fragment3"
android:layout_width="0dp"
android:layout_height="fill_parent"
android:layout_weight="2"/>
Here is my fragment_1.xml
<?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"
android:paddingLeft="8dp"
android:paddingRight="8dp" >
<GridView
android:id="#+id/Grid1"
android:layout_width="match_parent"
android:numColumns="auto_fit"
android:columnWidth="100dp"
android:layout_height="0dp"
android:layout_weight="1"
android:drawSelectorOnTop="false" />
and here is my row_fragment1_list.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:layout_margin="15dp"
android:orientation="vertical" >
<ImageView
android:id="#+id/img_view"
android:layout_width="50dp"
android:layout_height="50dp"
android:background="#CCCCCC"
android:textSize="16sp"
android:textStyle="bold" />
<TextView
android:id="#+id/text2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="16sp" />
and fragment_3.xml
<?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:gravity="center"
android:orientation="vertical" >
<TextView
android:id="#+id/tv_fragment3"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="22sp"
android:gravity="center"
android:text="This is 3rd Fragment" />
and here is my Main.xml
public class Main extends Activity
{
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
}
and here is Fragment1.class
public class Fragment1 extends Fragment implements OnItemClickListener
{
Activity myActivity;
GridView mGridView;
private String ListItem[] = {"Item 1","Item 2","Item 3","Item 4","Item 5","Item 6","Item 7"};
private int imgID[] = {R.drawable.admin_access_rule,
R.drawable.admin_backup,R.drawable.admin_browsesite,
R.drawable.admin_comment_post,R.drawable.admin_content,
R.drawable.admin_content_type,R.drawable.admin_logout,};
#Override
public void onAttach(Activity activity)
{
super.onAttach(activity);
this.myActivity = activity;
Toast.makeText(activity.getApplicationContext(), "On Attach", Toast.LENGTH_SHORT).show();
}
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
Toast.makeText(myActivity.getApplicationContext(), "On Create", Toast.LENGTH_SHORT).show();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
Toast.makeText(myActivity.getApplicationContext(), "On Create View", Toast.LENGTH_SHORT).show();
View view = inflater.inflate(R.layout.fragment_1,container, false);
mGridView = (GridView)view.findViewById(R.id.Grid1);
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState)
{
Toast.makeText(myActivity.getApplicationContext(), "On Activity Created", Toast.LENGTH_SHORT).show();
super.onActivityCreated(savedInstanceState);
}
#Override
public void onStart()
{
super.onStart();
mGridView.setAdapter(new GridBaseAdapter(myActivity));
mGridView.setOnItemClickListener(this);
}
private class GridBaseAdapter extends BaseAdapter
{
LayoutInflater mLayoutInflater = null;
public GridBaseAdapter(Context mContext)
{
mContext = myActivity;
mLayoutInflater = LayoutInflater.from(mContext);
}
#Override
public int getCount()
{
return ListItem.length;
}
#Override
public Object getItem(int position)
{
return null;
}
#Override
public long getItemId(int position)
{
return ListItem.length;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent)
{
if(convertView == null)
{
convertView = mLayoutInflater.inflate(R.layout.row_fragment_list, null);
}
ImageView mImageView = (ImageView) convertView.findViewById(R.id.img_view);
mImageView.setImageResource(imgID[position]);
TextView tvUserEmail = (TextView) convertView.findViewById(R.id.text2);
tvUserEmail.setText("Sub " +ListItem[position]);
return convertView;
}
}
#Override
public void onItemClick(AdapterView<?> arg0, View view, int position, long id)
{
TextView txt3 = (TextView)myActivity.findViewById(R.id.tv_fragment3);
txt3.setText("1st Fragment's : " + position +" Item Clicked");
}
}
My Fragment2.class
public class Fragment2 extends ListFragment
{
Activity myActivity;
private String ListItem[] = {"Item 1","Item 2","Item 3","Item 4","Item 5","Item 6","Item 6","Item 7"};
#Override
public void onAttach(Activity activity)
{
super.onAttach(activity);
this.myActivity = activity;
Toast.makeText(activity.getApplicationContext(), "On Attach", Toast.LENGTH_SHORT).show();
}
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
Toast.makeText(myActivity.getApplicationContext(), "On Create", Toast.LENGTH_SHORT).show();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
Toast.makeText(myActivity.getApplicationContext(), "On Create View", Toast.LENGTH_SHORT).show();
/** Creating an array adapter to store the list of countries **/
ArrayAdapter<String> adapter = new ArrayAdapter<String>(inflater.getContext(), android.R.layout.simple_list_item_1,ListItem);
/** Setting the list adapter for the ListFragment */
setListAdapter(adapter);
return super.onCreateView(inflater, container, savedInstanceState);
}
#Override
public void onActivityCreated(Bundle savedInstanceState)
{
Toast.makeText(myActivity.getApplicationContext(), "On Activity Created", Toast.LENGTH_SHORT).show();
super.onActivityCreated(savedInstanceState);
}
#Override
public void onListItemClick(ListView l, View v, int position, long id)
{
Toast.makeText(myActivity.getApplicationContext(), position +" Item Clicked", Toast.LENGTH_SHORT).show();
TextView txt3 = (TextView)myActivity.findViewById(R.id.tv_fragment3);
txt3.setText("2nd Fragment's : " + position +" Item Clicked");
super.onListItemClick(l, v, position, id);
}
}
And Last my Fragment3.class
public class Fragment3 extends Fragment
{
Activity myActivity;
TextView txt_view;
#Override
public void onAttach(Activity activity)
{
super.onAttach(activity);
this.myActivity = activity;
Toast.makeText(activity.getApplicationContext(), "On Attach", Toast.LENGTH_SHORT).show();
}
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
Toast.makeText(myActivity.getApplicationContext(), "On Create", Toast.LENGTH_SHORT).show();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
Toast.makeText(myActivity.getApplicationContext(), "On Create View", Toast.LENGTH_SHORT).show();
View view = inflater.inflate(R.layout.fragment_3,container, false);
txt_view = (TextView)view.findViewById(R.id.tv_fragment3);
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState)
{
Toast.makeText(myActivity.getApplicationContext(), "On Activity Created", Toast.LENGTH_SHORT).show();
super.onActivityCreated(savedInstanceState);
}
}
Make fragments expose interface that your activity can attach itself to. The event should occur when desired (e.g. list item is clicked). Then, activity should place instance of the fragment where it should be, for example:
// fragment is an instance of the fragment you want to show
final FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.fragment3, fragment);
transaction.commit();

Categories