In My application i customized gridview to show header and subitems. But i can't select individual items. My codes as follows
main_activity
public class MainActivity extends Activity {
private TextView tv;
private GridView gv;
private GridAdapter ga;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView)findViewById(R.id.TextMsg);
gv = (GridView)findViewById(R.id.gridView);
ga = new GridAdapter(this);
gv.setAdapter(ga);
GridAdapter.Item item = new GridAdapter.Item();
item.set("Header1", "Item1_1", "Item1_2", "Item1_3");
ga.add(item);
item = new GridAdapter.Item();
item.set("Header2", "Item2_1", "Item2_2", "Item2_3");
ga.add(item);
item = new GridAdapter.Item();
item.set("Header3", "Item3_1", "Item3_2", "Item3_3");
ga.add(item);
}
}
GridAdapter.java
package com.example.testapplication;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class GridAdapter extends ArrayAdapter<GridAdapter.Item> {
private LayoutInflater m_vi = null;
private GridAdapter.Item m_item = null;
private ViewHolderItem m_holderItem = null;
public GridAdapter(Context context) {
super(context, 0);
m_vi = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
m_item = (GridAdapter.Item)getItem(position);
if (convertView == null || !convertView.getTag().equals(m_holderItem)){
convertView = m_vi.inflate(R.layout.mygrid, null);
m_holderItem = new ViewHolderItem();
convertView.setTag(m_holderItem);
}
else {
m_holderItem = (ViewHolderItem) convertView.getTag();
}
m_holderItem.tvHeader = (TextView)convertView.findViewById(R.id.gridhead);
m_holderItem.tvItem1 = (TextView) convertView.findViewById(R.id.gridtext1);
m_holderItem.tvItem2 = (TextView) convertView.findViewById(R.id.gridtext2);
m_holderItem.tvItem3 = (TextView) convertView.findViewById(R.id.gridtext3);
m_holderItem.tvHeader.setText(m_item.getHeader());
m_holderItem.tvItem1.setText(m_item.getItem1());
m_holderItem.tvItem2.setText(m_item.getItem2());
m_holderItem.tvItem3.setText(m_item.getItem3());
return convertView;
}
public static class ViewHolderItem {
public TextView tvHeader;
public TextView tvItem1;
public TextView tvItem2;
public TextView tvItem3;
}
public static class Item {
public String Header, Item1, Item2, Item3;
public Item(){
this.Header = "";
this.Item1 = "";
this.Item2 = "";
this.Item3 = "";
}
public void set(String Header_i, String Item1_i, String Item2_i, String Item3_i) {
this.Header = Header_i;
this.Item1 = Item1_i;
this.Item2 = Item2_i;
this.Item3 = Item3_i;
}
public String getHeader(){
return this.Header;
}
public String getItem1(){
return this.Item1;
}
public String getItem2(){
return this.Item2;
}
public String getItem3(){
return this.Item3;
}
}
}
mygrid-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">
<TextView
android:id="#+id/gridhead"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:id="#+id/gridtext1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<View
android:layout_width="20dp"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/gridtext2"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<View
android:layout_width="20dp"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/gridtext3"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
<View
android:layout_width="wrap_content"
android:layout_height="5dp"
/>
</LinearLayout>
present image;
i just want o/p like just below
Select only item2-2
Since the items you want selected are not distinct gridview items, but children of gridview items, I believe your only option is to set the onClickListeners for each of the textViews you add in the getView method, and write your own code for coloring the background of the "selected" textview, returning the previous textview to normal color, etc.
It also requires a fairly good understanding of how adapter views are recycled, and such.
Edit: A rough outline how to accomplish this:
It is a bit of an undertaking. The best I can post for you is a good outline:
setOnClickListener for each View you hope to capture a click. These will be the particular TextViews you add in the GetView method.
Do whatever you want to graphically indicate the view is selected. (e.g. yellow background).
Record the position of the selected view.
Find previous selected View, and remove graphical selection, if needed.
Because views get recycled, whatever you do graphically for the "selected" view, may start appearing on other views as you scroll, if the graphical elements are not checked and removed everytime getView is called; they will also need to be reapplied when the user scrolls back.
Related
Radio Buttons Deselected on scrolling in custom listview
i have made custom listview that add
run time radiobutton added autimatically
but it deselected on scroll
my code given below of adapter and mainclass and activity files
Layout file
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:background="#drawable/gradient11"
android:layout_width="match_parent" android:layout_height="wrap_content">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<RadioGroup
android:layout_width="match_parent"
android:layout_height="match_parent">
<RadioButton
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="option one is selected now so you can"
android:textColor="#00ff00"
android:id="#+id/op1"/>
<RadioButton
android:checked="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="op2"
android:textColor="#00ff00"
android:id="#+id/op2"/>
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="op3"
android:textColor="#00ff00"
android:id="#+id/op3"/>
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="op4"
android:textColor="#00ff00"
android:id="#+id/op4"/>
</RadioGroup>
</LinearLayout>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/quest"
android:textColor="#e2000000"/>
</LinearLayout>
The Adapter file
package com.patel.ravin.com.domparsing;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.RadioButton;
import android.widget.TextView;
import java.util.ArrayList;
/**
* Created by lenovo on 08-08-2016.
*/
public class Adpt extends BaseAdapter
{
Context context;
ArrayList<MyBean> arrayList;
public Adpt(Context context,ArrayList<MyBean> arrayList)
{
this.context=context;
this.arrayList=arrayList;
}
#Override
public int getCount() {
return arrayList.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int i, View view, ViewGroup parent) {
LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = layoutInflater.inflate(R.layout.listview, null);
TextView txtFName = (TextView) view.findViewById(R.id.qid);
TextView txtLName = (TextView) view.findViewById(R.id.quest);
RadioButton op1=(RadioButton)view.findViewById(R.id.op1);
RadioButton op2=(RadioButton)view.findViewById(R.id.op2);
RadioButton op3=(RadioButton)view.findViewById(R.id.op3);
RadioButton op4=(RadioButton)view.findViewById(R.id.op4);
MyBean myBean = arrayList.get(i);
txtFName.setText("" + myBean.getQid());
txtLName.setText(" Answer= " + myBean.getQname());
op1.setText(myBean.getOp1());
op2.setText(myBean.getOp2());
op3.setText(myBean.getOp3());
op4.setText(myBean.getOp4());
return view;
}
}
The Activity file
package com.patel.ravin.com.domparsing;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.patel.ravin.com.domparsing.AsyncTask.AsyncTaskLoader;
import com.patel.ravin.com.domparsing.AsyncTask.OnAsyncResult;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
public class MainActivity extends AppCompatActivity {
TextView textView;
ListView listView1;
Adpt adpt;
ArrayList<MyBean> arrayList=null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// textView= (TextView) findViewById(R.id.tv1);
listView1=(ListView)findViewById(R.id.llv);
// Adpt adpt=new Adpt(getApplicationContext(),arrayList);
//listView.setAdapter(new ArrayAdapter<String>(getApplicationContext(),android.R.layout.simple_list_item_1,arrayList));
OnAsyncResult onAsyncResult=new OnAsyncResult() {
#Override
public void onAsyncResult(String result) {
Log.e("h", result.toString());
try {
// textView.setText(""+result.toString());
// String co=result.toString();
JSONArray jsonArray=new JSONArray(result);
MyBean myBean;
arrayList = new ArrayList<>();
for(int i=1;i<=jsonArray.length();i++)
{
JSONObject jsonObject=jsonArray.getJSONObject(i);
myBean = new MyBean();
myBean.setQid(jsonObject.getString("que"));
myBean.setQname(jsonObject.getString("ans"));
myBean.setOp1(jsonObject.getString("a"));
myBean.setOp2(jsonObject.getString("b"));
myBean.setOp3(jsonObject.getString("c"));
myBean.setOp4(jsonObject.getString("d"));
arrayList.add(myBean);
listView1.setAdapter(new Adpt(getApplicationContext(),arrayList));
}
//JSONObject object = new JSONObject(result);
//String contact = object.getString("que");
// textView.setText(co);
} catch (Exception e) {
e.printStackTrace();
}
}
};
AsyncTaskLoader asyncTaskLoader=new AsyncTaskLoader(MainActivity.this,onAsyncResult,null,"http://quiz/jsonapi.php");
asyncTaskLoader.execute();
}
}
Radio Buttons Deselected on scrolling in custom listview
i have made custom listview that add
run time radiobutton added autimatically
but it deselected on scroll
This is a very common problem in Android with Listviews and Radio buttons.
First, I would recommend you to check this post:
Using radio button in custom listview in Android
Now, I'm going to tell you which solution fits for me. In my case I use GridView, but it also works for ListView.
In your Adapter's class you have to have a variable for the selected item and his index, it could be something like:
private int mSelectedPosition = -1;
private RadioButton mSelectedRB;
Then, define a function to retrieve this information:
public int getItemSelected(){
return mSelectedPosition;
}
Now, In order to make it works properly, you have to user a ViewHolder (in my case every item in the GridView has a Image and a RadioButton), so you define your ViewHolder in the Adapter's class as well:
private class ViewHolder {
ImageView image;
RadioButton radio;
}
Then, in your getView function, you have to work with the ViewHolder. In the code I write comments to follow.
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View view = convertView; // assign the view
ViewHolder holder; // declare the ViewHolder
if(view == null){
// cutom layout for each row (item) of the ListView
view = mLayoutInflater.inflate(R.layout.item_list_company, parent, false);
holder = new ViewHolder();
// initialize the ViewHolder's field
holder.image = (ImageView) view.findViewById(R.id.c1);
holder.radio = (RadioButton)view.findViewById(R.id.cN1);
view.setTag(holder); // set the tag
}else{ // already initialized
holder = (ViewHolder)view.getTag(); // so we only set the tag
}
// on click triggered for each RadioButton in the ListView
holder.radio.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(position != mSelectedPosition && mSelectedRB != null){
mSelectedRB.setChecked(false); // uncheck the last one
}
mSelectedPosition = position; // change the item selected index
mSelectedRB = (RadioButton)v; // assign the new item selected
}
});
// just to control the right item checked
if(mSelectedPosition != position){
holder.radio.setChecked(false);
}else{
holder.radio.setChecked(true);
if(mSelectedRB != null && holder.radio != mSelectedRB){
mSelectedRB = holder.radio;
}
}
return view;
}
Finally, in the custom layout (item_list_company.xml in my case) for each item in the ListView, I have the following code:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:orientation="vertical"
android:layout_height="match_parent">
<ImageView android:id="#+id/c1"
android:layout_width="wrap_content"
android:layout_height="100dp"
android:layout_gravity="center"
android:scaleType="centerInside" />
<RadioButton
android:id="#+id/cN1"
android:layout_width="wrap_content"
android:layout_height="50dp"
android:buttonTint="#color/colorPrimary"
android:textColor="#color/colorAccent"
android:focusable="false"
android:layout_gravity="left"
android:clickable="false"
android:focusableInTouchMode="false"
android:textSize="20dp"/>
</LinearLayout>
Special attention for this three attributes of the RadioButton:
android:focusable="false"
android:clickable="false"
android:focusableInTouchMode="false"
So, with all of this, you only have to set your adapter and ListView in your Activity and call to the right function to retrieve the selected item:
ArrayList<MyBean> arrayList = new ArrayList<>();
ListView listView1 = (ListView)findViewById(R.id.llv);
Adpt adpt = new Adpt(getApplicationContext(), arrayList);
// add data to the ArrayList
adpt.notifyDataSetChanged(); // notify for the new data in the ArrayList
// retrieve the item selected
int selected = adpt.getItemSelected();
Hope it helps!
I am not able to set textview's setText property inside getView() method of Custom Adapter.
I already tried below solutions but it does not work for me :
Solution One
Solution Two
Solution Three
Listview.xml file :
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/imgLayout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:id="#+id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="40dp"
android:divider="#null"
android:dividerHeight="5dp"
android:scrollbars="none" />
</RelativeLayout>
Below is my keep_resing xml file :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/customRowLayout"
android:layout_width="fill_parent"
android:layout_height="60dp"
android:layout_marginTop="20dp"
android:orientation="horizontal" >
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:orientation="vertical" >
<ImageButton
android:id="#+id/Btn"
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_marginLeft="10dp"
android:background="#drawable/thumb_down_disabled" />
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:text="#string/resing"
android:textColor="#357EC7"
android:textSize="10sp" />
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:orientation="vertical" >
<TextView
android:id="#+id/lyricsTxt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal" />
<RelativeLayout
android:id="#+id/parentLayout"
android:layout_width="120dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="5dp"
android:background="#drawable/playing_view"
android:orientation="horizontal" >
<TextView
android:id="#+id/helloTxt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:layout_marginLeft="5dp"
android:singleLine="true"
android:text="Hello"
android:textColor="#357EC7"
android:textSize="14sp" />
<ImageView
android:layout_width="20dp"
android:layout_height="20dp"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:layout_marginRight="5dp"
android:background="#drawable/volume" />
</RelativeLayout>
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:orientation="vertical" >
<ImageButton
android:id="#+id/keepBtn"
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_marginRight="10dp"
android:background="#drawable/thumb_up_disabled" />
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:text="#string/keep"
android:textColor="#357EC7"
android:textSize="10sp" />
</LinearLayout>
</RelativeLayout>
Below is my adapter code :
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.simpleframework.xml.stream.Position;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.AssetFileDescriptor;
import android.content.res.Resources;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Handler;
import android.os.PowerManager;
import android.sax.StartElementListener;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
public class KeepReSingAdapter extends BaseAdapter implements OnClickListener {
/*********** Declare Used Variables *********/
private Activity activity;
private ArrayList data;
private static LayoutInflater inflater = null;
public Resources res;
SongCue tempValues = null;
int i = 0;
private ArrayList<SongCue> songCue;
private int cueIndex = 0;
private String selectedSongId;
private MediaPlayer mMediaPlayer;
ViewHolder holder;
View vi;
boolean right_button_flag, left_button_flag;
SessionManager session;
// int left_button_flag;
/************* CustomAdapter Constructor *****************/
public KeepReSingAdapter(Activity a, ArrayList d, Resources resLocal) {
/********** Take passed values **********/
activity = a;
data = d;
res = resLocal;
/*********** Layout inflator to call external xml layout () ***********/
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
selectedSongId = SessionManager.getInstance(
activity.getApplicationContext()).getString(
AppConstants.SONG_ID);
right_button_flag = false;
left_button_flag = false;
// Session class instance
session = new SessionManager(activity.getApplicationContext());
}
/******** What is the size of Passed Arraylist Size ************/
public int getCount() {
if (data.size() <= 0)
return 1;
return data.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
/********* Create a holder Class to contain inflated xml file elements *********/
public static class ViewHolder {
public TextView lyricsTxt, helloTxt;
// public TextView text1;
public ImageButton leftBtn, rightBtn;
public RelativeLayout parentLayout;
public LinearLayout rowLayout;
// public TextView textWide;
// ImageView image;
}
/****** Depends upon data size called for each row , Create each ListView row *****/
public View getView(final int position, View convertView, ViewGroup parent) {
vi = convertView;
if (convertView == null) {
vi = inflater.inflate(R.layout.keep_resing, null);
holder = new ViewHolder();
holder.lyricsTxt = (TextView) vi.findViewById(R.id.lyricsTxt);
holder.helloTxt = (TextView) vi.findViewById(R.id.helloTxt);
holder.leftBtn = (ImageButton) vi.findViewById(R.id.reSingBtn);
holder.rightBtn = (ImageButton) vi.findViewById(R.id.keepBtn);
holder.parentLayout = (RelativeLayout) vi
.findViewById(R.id.parentLayout);
holder.rowLayout = (LinearLayout) vi
.findViewById(R.id.customRowLayout);
vi.setTag(holder);
} else {
holder = (ViewHolder) vi.getTag();
}
if (data.size() <= 0) {
} else {
/***** Get each Model object from Arraylist ********/
tempValues = null;
tempValues = (SongCue) data.get(position);
holder.lyricsTxt.setText(tempValues.getLyric());
List<Song> AllSong = SplashScreen_Activity.songs;
if (selectedSongId != null) {
for (Song tempsong : AllSong) {
if (tempsong.songId.equals(selectedSongId)) {
songCue = (ArrayList<SongCue>) tempsong.songCues.songCue;
}
}
} else {
}
holder.parentLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(activity.getApplicationContext(),
" " + position, Toast.LENGTH_SHORT).show();
holder.helloTxt.setText("Test");
Toast.makeText(activity.getApplicationContext(),
holder.helloTxt.getText().toString(),
Toast.LENGTH_LONG).show();
}
});
}
vi.setOnClickListener(new OnItemClickListener(position));
return vi;
}
#Override
public void onClick(View v) {
Log.v("CustomAdapter", "=====Row button clicked=====");
}
/********* Called when Item click in ListView ************/
private class OnItemClickListener implements OnClickListener {
private int mPosition;
OnItemClickListener(int position) {
mPosition = position;
}
#Override
public void onClick(View arg0) {
}
}
}
Problem is, I am not able to change the text view text to "Test".
Note : If I see the value in Toast by doing "holder.helloTxt.getText().toString()" it shows me "Test".
I don't know why this problem is arising.Any help will be highly appreciated.
Thanks
Finally I got the solution to my question and guess what it was a minor updation in the code.
I updated my code to :
final ViewHolder holder;
inside getView() of CustomAdapter instead of declaring it globally.
Once again, thanking you all for your answers.
It helped me to look into my code in detail.
Try this hope this helps
vi = convertView;
if (vi == null) {
vi = inflater.inflate(R.layout.xmlfile, null);
holder = new ViewHolder();
holder.helloTxt= (TextView) vi.findViewById(R.id.hearTxt);
holder.parentLayout= (RelativeLayout) vi
.findViewById(R.id.parentLayout);
vi.setTag(holder);
}else
holder=(ViewHolder)vi.getTag();
holder.parentLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(activity.getApplicationContext(),
" " + position, Toast.LENGTH_SHORT).show();
holder.helloTxt.setText("Test");// not required
// just change the value of text in your list(which you are passing to the adapter) at corresponding position and then notify the list
notifyDataSetChanged();
Toast.makeText(activity.getApplicationContext(),
holder.helloTxt.getText().toString(),
Toast.LENGTH_LONG).show();
}
});
return vi;
It will display the text "test" but when you scroll, it will again changed to its original value so you have to change the value in the list also which you are sending to the adapter
Also in your case the problem is, when you update the text of your TextView, it gets updated for the time being that's why you are getting the TextView text in your Toast. But in order to show the updated text in ListView, you have to notify the List. But when you do so, your TextView resets to original value. So all you have to do is to take a global String variable and intialise that to your initial value whatever you want like this
private String yourText="initial text"
and in getView() set your TextView text to this variable like this
holder.helloTxt.setText(yourText);
and when you click your parentLayout,just assign, this string the value you want and notify the list
yourText="test";
notifyDataSetChanged();
and this will do the trick. But remember this works only when you have single row, if you have multiple rows you have to take a String array.
Do you perform a holder = vi.getTag(); in case the convertView not is null?
This is necessary when a view is already created to reinitialise it in the state it was.
Problem is, I am not able to change the text view text to "Test".
you are doing it wrong. Let's say your adapter is made of String. What I would have expected, is
if (convertView == null) {
// inflate stuff
// create older
// set the older in the converView's tag
} else {
// retriewholder
}
// here you set the String in the holder at position:
String tmpString = getItem(position);
holder.helloTxt.setText(tmpString);
holder.parentLayout.setTag(position);
Inside the onClick, you can retrieve the position trough the tag object, and update the String in the dataset and call notifyDataSetChanged
Your problem is you didnot touch the parent layout. Make sure that your finger can touch the parentLayout, you can add padding for it. Or you can try
holder.helloTxt.setOnClickListener(...)
instead of parentLayout.
I've seen a lot of ways but for me the simple way is pass component view to adapter. Then you can change you need. See an example below:
Link
I've been through every stack discussion on this I could find, along with about a dozen tutorials. I'm just not getting it. I'm using 'getItemViewType' to determine which layout I should use. Here's where I run into a problem (and maybe the way I'm getting the position is the root issue, not sure):
What I'm doing is getting the first character of the contact's name at position x. If it's different than the first character in position x-1, I know that it's the next letter in the list and it needs a section header, which would be inserted ABOVE the current list item. How do I get my adapter to add a new layout in position x-1?
This is my adapter code. I've stripped the code which was causing the app to force close, which leaves me with just the 1 layout. I can't figure out how to insert the 'section' layout at position x-1. Below the adapter code I threw in the xml for my 2 layouts. Let me know if you need anything else. Thanks in advance.
import java.util.ArrayList;
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 ContactNameAdapter extends BaseAdapter {
public static final int CONTACT_NAME = 0;
public static final int ALPHA_HEADER = 1;
private static final int NUMBER_OF_LAYOUTS = 2;
Context context;
private ArrayList<ListItemDetails> sItemDetailsArrayList;
public ContactNameAdapter(ArrayList<ListItemDetails> data, Context context) {
sItemDetailsArrayList = data;
this.context = context;
}
#Override
public int getCount() {
return sItemDetailsArrayList.size();
}
#Override
public ListItemDetails getItem(int position) {
return sItemDetailsArrayList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public int getViewTypeCount() {
return NUMBER_OF_LAYOUTS;
}
#Override
public int getItemViewType(int position) {
if (position != 0) {
if (getItem(position).getName().toUpperCase().charAt(0) == getItem(
position - 1).getName().toUpperCase().charAt(0)) {
return CONTACT_NAME;
} else {
return ALPHA_HEADER;
}
} else {
return ALPHA_HEADER;
}
}
#Override
public View getView(int position, View view, ViewGroup parent) {
ImageView mImageView;
TextView mTextView;
if (view == null) {
LayoutInflater layoutInflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = layoutInflater.inflate(R.layout.contactlistlayout, null);
mImageView = (ImageView) view.findViewById(R.id.ivContactPhoto);
mTextView = (TextView) view.findViewById(R.id.textView1);
view.setTag(new ViewHolder(mImageView, mTextView));
} else {
ViewHolder viewHolder = (ViewHolder) view.getTag();
mImageView = viewHolder.mImageView;
mTextView = viewHolder.mTextView;
}
ListItemDetails listItemDetails = getItem(position);
mTextView.setText(listItemDetails.getName());
mImageView.setImageBitmap(listItemDetails.getImage());
if (listItemDetails.getImage() == null) {
mImageView.setImageResource(R.raw.default_contact);
}
return view;
}
private static class ViewHolder {
public final TextView mTextView;
public final ImageView mImageView;
public ViewHolder(ImageView mImageView, TextView mTextView) {
this.mImageView = mImageView;
this.mTextView = mTextView;
}
}
}
list layout:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/contactView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:visibility="visible" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:clickable="false"
android:focusable="false"
android:focusableInTouchMode="false"
android:paddingLeft="2dp"
android:textAppearance="?android:attr/textAppearanceMedium" />
<ImageView
android:id="#+id/ivContactPhoto"
android:layout_width="60dp"
android:layout_height="60dp"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:clickable="false"
android:focusable="false"
android:focusableInTouchMode="false" />
</RelativeLayout>
section layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/layoutView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:descendantFocusability="blocksDescendants"
android:orientation="vertical" >
<TextView
android:id="#+id/tvAlphaHeader"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:focusable="true"
android:paddingBottom="10dp"
android:paddingLeft="2dp"
android:paddingTop="10dp"
android:textAppearance="?android:attr/textAppearanceSmall" />
<ImageView
android:id="#+id/ivSectionLine"
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#android:color/holo_blue_light"
android:focusable="true" />
</LinearLayout>
I've looked at a bunch of tutorials that ended up confusing me more than helping me, but I found this one to be great. If you've been around the world on this like I have, take a look at this tutorial :)
http://codelikes.blogspot.com/2012/04/android-alphabet-listview-like-contacts.html?zx=d40863f078ab91b4
I am new to the android api and I have some problems with .. the basics.
I'm trying to get a list working, but the list displays the wrong text:
Each row has two TextViews (title, subtitle), heres the xml:
<?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="wrap_content"
android:orientation="horizontal"
android:padding="5dip" >
<TextView
android:id="#+id/row_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TITLE"
android:textSize="15dip"
android:layout_gravity="center_vertical" />
<TextView
android:id="#+id/row_subtitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/row_title"
android:text="SUBTITLE"
android:textSize="10dip"
android:layout_gravity="center_vertical" />
</RelativeLayout>
I extend ListFragment (I need this fragment thing, because of a slidingMenu library), have a custom adapter and an item class.
in the onActivityCreated() method I add some random items to the adapter:
package com.slidingmenu.example;
import android.app.Fragment;
import android.app.ListFragment;
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.TextView;
public class SampleListFragment extends ListFragment {
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.list, null);
}
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
SampleAdapter adapter = new SampleAdapter(getActivity());
for (int i = 0; i < 20; i++) {
adapter.add(new SampleItem(new Fragment(), "title no. " + i, "some subtitle"));
}
setListAdapter(adapter);
}
private class SampleItem {
public Fragment frag;
public String title;
public String subTitle;
public SampleItem(Fragment frag, String title, String subTitle) {
this.frag = frag;
this.title = title;
this.subTitle = subTitle;
}
}
public class SampleAdapter extends ArrayAdapter<SampleItem> {
public SampleAdapter(Context context) {
super(context, 0);
}
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.row, null);
}
TextView title = (TextView) convertView.findViewById(R.id.row_title);
TextView subTitle = (TextView) convertView.findViewById(R.id.row_subtitle);
return convertView;
}
}
}
So I thougt that the list would display something like this:
title no. 0
some subtitle
-
title no. 1
some subtitle
-
title no. 2
some subtitle
-
etc.
but instead it just displays what I defined in the row.xml:
TITLE
SUBTITLE
-
TITLE
SUBTITLE
-
etc.
I think getView() needs to be changed (at least it doesn't make to much sense to me) but I'm not sure.
Everything I try results in some nullpointer exception or worse.
Please, can someone tell me what I need to change?
The error is int the Adapter:
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.row, null);
}
TextView title = (TextView) convertView.findViewById(R.id.row_title);
TextView subTitle = (TextView) convertView.findViewById(R.id.row_subtitle);
return convertView;
}
the getView never fills up the title and subtitle. Second you never submit to the superclass the dataset you want to show in the ListFragment.
Here you have to ways. Or you ovveride the getCount and getItem and getItemId methods, or feed up the superclass with the dataset, using this constructor. Read carefully the documentation.
I want to have a list of elements (using a ListView) and each element in list is styled with a relative layout. Currently, the items are being displayed correctly, however, for some reason the listview items dont glow green when they're clicked. Why is this?
I have removed all code to minimals and it still does this.
Activity class
package com.test;
import android.app.Activity;
public class My_ListView extends Activity
{
private ListView_Adapter listViewAdapter;
private ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.my_listview);
// initialise the list-view object
listViewAdapter = new ListView_Adapter(this);
listView = (ListView) findViewById(R.id.listview);
listView.setAdapter(listViewAdapter);
for (int i=0;i<20;i++)
{
listViewAdapter.add("item "+i);
}
}
public void clicked(View v)
{
v.setBackgroundColor(0xFF0000FF);
}
}
The listview item adapter class
package com.test;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
public class ListView_Adapter extends ArrayAdapter<String>
{
public ListView_Adapter(Context c)
{
super(c, R.layout.my_listview_item);
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
View row = convertView;
StationFinder_ListViewItemHolder holder = null;
if (row == null)
{
LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.my_listview_item, parent, false);
holder = new StationFinder_ListViewItemHolder(row);
row.setTag(holder);
}
else
{
holder = (StationFinder_ListViewItemHolder) row.getTag();
}
holder.populateFrom(getItem(position));
return row;
}
static class StationFinder_ListViewItemHolder
{
private TextView destination = null;
StationFinder_ListViewItemHolder(View row)
{
destination = (TextView) row.findViewById(R.id.text1);
}
void populateFrom(String locationDistance)
{
destination.setText(locationDistance);
}
}
}
my_listview.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"
>
<ListView android:id="#+id/listview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>
</LinearLayout>
my_listview_item.xml
<?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:onClick="clicked"
>
<TextView android:id="#+id/text1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</RelativeLayout>
I think you may have to call invalidate() after setting the background color.
You may want to do this instead by setting the listSelector and possibly drawSelectorOnTop for your ListView. That way the selection/deselection and clicks will be handled in the normal manner.
Edit - also, since you're using a ListView, you probably want to listen for clicks by setting an OnItemClickListener on your ListView.