I am working on an android app, currently i have following code:
<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:background="#drawable/background_main"
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=".MainActivity" >
<TextView
android:id="#+id/display_result"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="25dp"
android:textSize="20pt"
android:textColor="#FFFFFF"
android:visibility="invisible"
android:textAppearance="?android:attr/textAppearanceLarge" />
<ListView
android:id="#+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="22dp" >
</ListView>
</RelativeLayout>
and
import android.media.MediaPlayer;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
public class MainActivity extends Activity {
private TextView tv;
private MediaPlayer player = null;
ListView listV;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView)findViewById(R.id.display_result);
listV = (ListView)findViewById(R.id.listView1);
final Intent i = new Intent(this,BActivity.class);
String[] values = new String[] { "C 2 F", "F 2 C", "Currency"};
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, values);
listV.setAdapter(arrayAdapter);
listV.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
int itemPosition = position;
if(itemPosition == 0)
{
i.putExtra("identify", "c2f");
startActivityForResult(i, 1);
if(player != null)
player.stop();
}
else if(itemPosition == 1)
{
i.putExtra("identify", "f2c");
startActivityForResult(i, 1);
if(player != null)
player.stop();
}
else if(itemPosition == 2)
{
i.putExtra("identify", "currency");
startActivityForResult(i, 1);
if(player != null)
player.stop();
}
}
});
}
protected void onDestroy()
{
super.onDestroy();
player.stop();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
if(resultCode == RESULT_OK){
String result=data.getStringExtra("result");
tv.setVisibility(View.VISIBLE);
tv.setText(result);
player = MediaPlayer.create(this, R.raw.sound);
player.start();
}
}
}
}
It's all working well, but the ListView is showing very small black text alligned left, i want to change it to center and increase the size, also is there any simple way to include pictures along with text on the listview. I searched on it a lot but they are all extremely difficult to understand, kindly tell me what changes do i have to make in my code to be able to edit the listView text.
You need have another layout with TextView. Customize the below layout to suit your needs. You can increase the text size change the text color and customize the textview the way you want.
row.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="match_parent" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="41dp"
android:text="TextView" />
</RelativeLayout>
Then
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this,R.layout.row,R.id.textView1, values);
Snap
All the layout of the ListView is given by the Adapter. You're using the simple ArrayAdapter, with the simple_list_item_1 (that is a simple TextView).
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, values);
The good: this is really easy, as you have seen.
The bad: you cannot do much except a list of strings.
If you want to include images, more TextViews or other nice things you will have to create a custom Adapter, overriding the ArrayAdapter or another one, as the BaseAdapter.
Here you can find a simple tutorial by Vogella.
As you can see all the work is done in the getView method, where all the "creation" takes place.
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.rowlayout, parent, false);
TextView textView = (TextView) rowView.findViewById(R.id.label);
ImageView imageView = (ImageView) rowView.findViewById(R.id.icon);
textView.setText(values[position]);
// change the icon for Windows and iPhone
String s = values[position];
if (s.startsWith("iPhone")) {
imageView.setImageResource(R.drawable.no);
} else {
imageView.setImageResource(R.drawable.ok);
}
return rowView;
}
At the beginning you will have to "inflate" (create) the row. From the row then you will "find" the views and set the items respectively on the position of the row.
Performance note:
since Android will recycle the rows, you should check if the line was already created. So just check, before the inflate and wrapping all the code, if the convertView is null or not.
Here is your row.xml with ImageView and TextView . It's a way your list items will look.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="#dimen/item_height"
android:layout_width="match_parent">
<ImageView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/item_image"
android:layout_width="60dp"
android:layout_height="60dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#id/item_image"
android:id="#+id/item_label"/>
</RelativeLayout>
Then you need to create custom adapter, e.g. ArrayAdapter of String:
public class SampleAdapter extends ArrayAdapter<String> {
private LayoutInflater layoutInflater;
public SampleAdapter(Context context, ArrayList<String> data) {
super(context, R.layout.adapter_deals_list_fragment, data);
this.layoutInflater = LayoutInflater.from(context);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder;
String item = getItem(position);
if (convertView == null) {
convertView = layoutInflater.inflate(R.layout.row, parent, false);
viewHolder = new ViewHolder(convertView);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.imageView.setImageDrawable(new ColorDrawable(Color.parseColor("#ffaa66cc")));
viewHolder.textView.setText(item);
return convertView;
}
private class ViewHolder {
ImageView imageView;
TextView textView;
public ViewHolder(View view) {
imageView = (ImageView) view.findViewById(R.id.item_image);
textView = (TextView) view.findViewById(R.id.item_label);
}
}
}
After that do something like this in yout Activity class:
SampleAdapter sampleAdapter = new SampleAdapter(this, new String[]{"lorem", "ipsum", "dolar"});
ListView listView = (ListView) findViewById(R.id.listview1);
listView.setAdapter(sampleAdapter);
As result your ListView item will look like an Fill Colored Image and Text.
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 have a Spinner that uses a custom adapter where the getDropDownView() is overridden. Each item in the custom drop-down view is made up of a TextView and a Button.
But, when I run my code, the spinner drop-down items display fine, but clicking them does nothing. The spinner drop-down remains open and spinner.onItemSelected() is not triggered.
drop_down_item.xml
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/dropdown_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:singleLine="true" />
<Button
android:id="#+id/dropdown_button"
android:layout_height="match_parent"
android:layout_width="wrap_content"
android:layout_alignParentRight="true"
android:text="Remove"/>
</RelativeLayout>
Custom adapter code
public View getDropDownView(final int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.drop_down_item, parent, false);
TextView textView = (TextView) rowView.findViewById(R.id.dropdown_text);
textView.setText(mValues.get(position));
Button buttonView = (Button) rowView.findViewById(R.id.dropdown_button));
return rowView;
}
I create my spinner and adapter with this code:
spinner = (Spinner) findViewById(R.id.my_spinner);
MyAdapter adapter = new MyAdapter(getViewContext(), R.layout.spinner_item, values);
adapter.setDropDownViewResource(R.layout.drop_down_item);
spinner.setAdapter(adapter);
...
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
// Do something here - but this never runs
}
});
So I don't know why onItemSelected() is no longer called?
I was wondering if I need to put a click listener on the drop-down TextView which should in turn trigger onItemSelected() using maybe spinner.setSelection(pos)?
The Events is basically a interface that Activity implements to recieve the callBack by clicking on the LinearLayout of the DropDown View of Spinner.
public class MyArrayAdapter extends BaseAdapter {
String[] values;
int CustomResource;
Context context;
Events events;
public MyArrayAdapter(Context baseContext, int customspinnerview,
String[] stringArray, Events events) {
values = stringArray;
context = baseContext;
this.events = events;
CustomResource = customspinnerview;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return values.length;
}
#Override
public Object getItem(int position) {
if (position < values.length)
return values[position];
else {
return null;
}
}
#Override
public View getView(final int position, final View convertView,
ViewGroup parent) {
View rowView = convertView;
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (rowView == null) {
rowView = inflater.inflate(CustomResource, parent, false);
}
TextView textView = (TextView) rowView.findViewById(R.id.dropdown_text);
textView.setText(values[position]);
Button button = (Button) rowView.findViewById(R.id.Button_text);
return rowView;
}
#Override
public View getDropDownView(final int position, View convertView,
ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = convertView;`enter code here`
if (rowView == null) {
rowView = inflater.inflate(CustomResource, parent, false);
}
final LinearLayout parentRelative = (LinearLayout) rowView
.findViewById(R.id.parent);
final TextView textView = (TextView) rowView
.findViewById(R.id.dropdown_text);
textView.setText(values[position]);
Button button = (Button) rowView.findViewById(R.id.Button_text);
rowView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
events.onItemSelectedLister(
(AdapterView<?>) parentRelative.getParent(),
parentRelative, position, (long) 0);
}
});
// Button buttonView = (Button)
// rowView.findViewById(R.id.dropdown_button);
return rowView;
}
Events Inteface Its a interface that the Activity implement in order to recieve the callbacks from the Adapter.
import android.view.View;
import android.widget.AdapterView;
public interface Events {
public void onItemSelectedLister(AdapterView<?> parent, View view,
int position, long id);
}
Activity Implementation.
onItemSelected Implementation is the place where you can do your task.....
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import android.annotation.TargetApi;
import android.app.Activity;
import android.os.Build;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Spinner;
import com.example.adapter.MyArrayAdapter;
public class MainActivity extends Activity implements Events {
Spinner spinner;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
spinner = (Spinner) findViewById(R.id.spinner);
spinner.setAdapter(new MyArrayAdapter(getBaseContext(),
R.layout.customspinnerview, getResources().getStringArray(
R.array.values), this));
}
#Override
public void onItemSelectedLister(AdapterView<?> parent, View view,
final int position, long id) {
//perform your Task.......
Method method;
try {
method = Spinner.class.getDeclaredMethod("onDetachedFromWindow");
method.setAccessible(true);
try {
method.invoke(spinner);
} catch (IllegalAccessException | IllegalArgumentException
| InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
spinner.post(new Runnable() {
#Override
public void run() {
spinner.setSelection(position);
spinner.setSelected(true);
((MyArrayAdapter) spinner.getAdapter()).notifyDataSetChanged();
}
});
}
}
Activity xml File for setContentView
<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="com.example.customspinner.MainActivity" >
<Spinner
android:id="#+id/spinner"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</Spinner>
</RelativeLayout>
Spinner View which is passed to Adapter as layout file.
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#99000000"
android:id="#+id/parent"
android:orientation="horizontal">
<TextView
android:id="#+id/dropdown_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<Button
android:id="#+id/Button_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="remove"/>
</LinearLayout>
the Code works perfectly fine :) .I have the code perfectly running.
Solution is to set android:focusable="false" in the layout for both the TextView and the Button.
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/dropdown_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:focusable="false"
android:singleLine="true" />
<Button
android:id="#+id/dropdown_button"
android:layout_height="match_parent"
android:layout_width="wrap_content"
android:layout_alignParentRight="true"
android:focusable="false"
android:text="Remove"/>
</RelativeLayout>
Alternatively can also do this in the code:
textView.setFocusable(false);
buttonView.setFocusable(false);
Found the answer here. This works because the Spinner implementation only allows one focusable item in the view. That's why I wasn't able to select the item.
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 have been trying to implement a list view which has five image views in a single row of a list view. I found that it can be done with layout inflater but since I am new to android I could not exactly get how to make the best use of it. I want to get a view of this sort:
L,S,D,A,E are images and it should change accordingly for different users in the list view according to the data provided dynamically. Can anybody please help me with the code snippet for this, or just give me an idea on how to implement it?
Okay so your list view should inflate a layout of this type:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:orientation="horizontal"
android:id="#+id/layoutContainer" >
<ImageView
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:id="#+id/iv1" />
<ImageView
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:id="#+id/iv2" />
<ImageView
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:id="#+id/iv3" />
<ImageView
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:id="#+id/iv4" />
<ImageView
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:id="#+id/iv5" />
</LinearLayout>
Save it to row.xml located in your layout folder.
Next implement this in your activity's onCreate() method:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
CustomAdapter myAdapter = new CustomAdapter(getApplicationContext());
ListView mainListView = (ListView) findViewById(R.id.lv);
mainListView.setAdapter(myAdapter);
}
Finally, you need to create the CustomAdapter.java class, like this:
import android.content.Context;
import android.graphics.Bitmap;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
public class CustomAdapter extends BaseAdapter {
private Bitmap[][] data;
private int count;
private Context context;
public CustomAdapter(Context context) {
this.context = context;
data = new Bitmap[100][];
count = 0;
}
#Override
public int getCount() {
return count;
}
#Override
public Bitmap[] getItem(int position) {
// TODO Auto-generated method stub
return data[position];
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View adapterView = convertView;
if (adapterView == null) {
adapterView = inflater.inflate(R.layout.row, null);
}
ImageView imageView = (ImageView) adapterView.findViewById(R.id.iv1);
imageView.setImageBitmap(data[position][0]);
//Repeat the last two steps for all five images, changing the last index accordingly
return adapterView;
}
public void addBitmapArray (Bitmap[] newValue) {
data[++count] = newValue;
}
}
In row of the list add a linear layout LinearLayout1 then do something like fallowing in your adapter add dynamically images to the list item..
public View getView(final int position, View convertView, ViewGroup parent)
{
// System.out.println(" inside KeyvalueAdapter..");
ViewHolder holder = null;
if (convertView == null)
{
LayoutInflater mInflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = mInflater.inflate(R.layout.new_row, null);
holder = new ViewHolder();
holder.tv_title = (TextView) convertView.findViewById(R.id.titleTextView);
ImageView imageView = new ImageView(context);
imageView.setImageResource(resId);
LinearLayout linearLayout = (LinearLayout) findViewById(R.id.LinearLayout1);
linearLayout.addView(imageView);
convertView.setTag(holder);
}
else holder = (ViewHolder) convertView.getTag();
holder.tv_title.setText(notifList.get(position));
return convertView;
}
If you want to load different image you have to extend your listview adapter:
example if i understand correctly your question.
Check out this thread:
Android custom Row Item for ListView
You have to write your own xml with 5 imageviews
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.