I'm making an Activity with a ListView. Each row is made of two TextView and one CheckBox. The problem is that if I add the background attribute to the checkbox, it doesn't show in the row (not because it's transparent).
Does anybody have an explanation?
Actually it works fine either way on API 19, but the tests are made on the emulator with API 11 and I want to target API 8+.
Thank you in advance.
Image without the background attribute.
Image with the background attribute (You can see the strings going till the end of the frame):
[can't load images because of my reputation...]
The code is following.
Thank You in advance.
MainActivity:
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView listView = (ListView) findViewById(R.id.lvListaMyLocationSalvate);
ArrayList<String[]> array = new ArrayList<String[]>();
array.add(new String[]{"asdasdasdasdasdasdasdasdasdasdasdasdasd","asdasdasdasdasdasdasdasdasdasdasdasdasd"});
array.add(new String[]{"asdasdasdasdasdasdasdasdasdasdasdasdasd","asdasdasdasdasdasdasdasdasdasdasdasdasd"});
Adapter arAdapter = new Adapter(this, array);
listView.setAdapter(arAdapter);
}
}
Adapter:
public class Adapter extends ArrayAdapter<String[]>{
Activity context;
ArrayList<String[]> array;
public Adapter(Activity activity, ArrayList<String[]> array) {
super(activity, R.layout.row, array);
this.context = activity;
this.array = array;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View view = convertView;
if(view == null) {
view = context.getLayoutInflater().inflate(R.layout.row, null);
}
TextView tv1 = (TextView) view.findViewById(R.id.tvRow1);
TextView tv2 = (TextView) view.findViewById(R.id.tvRow2);
CheckBox cb = (CheckBox) view.findViewById(R.id.cb);
tv1.setText(((String[])(array.get(position)))[0]);
tv2.setText(((String[])(array.get(position)))[1]);
cb.setChecked(false);
return view;
}
}
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/lvListaMyLocationSalvate"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
</RelativeLayout>
row.xml (CheckBox background attribute makes the difference)
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:focusable="false"
android:focusableInTouchMode="false"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<CheckBox
android:id="#+id/cb"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_centerInParent="true"
android:background="#000000"
android:focusable="false"
android:focusableInTouchMode="false" />
<TextView
android:id="#+id/tvRow1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:focusable="false"
android:focusableInTouchMode="false"
android:textAppearance="?android:attr/textAppearanceLarge"
android:layout_toLeftOf="#id/cb"
android:textStyle="bold" />
<TextView
android:id="#+id/tvRow2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:focusable="false"
android:focusableInTouchMode="false"
android:textAppearance="?android:attr/textAppearanceSmall"
android:layout_below="#id/tvRow1"
android:layout_toLeftOf="#id/cb" />
</RelativeLayout>
The default background for the CheckBox is #android:drawable/btn_check_label_background. If you look at the drawable in your \platforms\android-11\data\res\drawable-hdpi folder, you'll find a nine-patch image that effectively defines the minimum height and width of your CheckBox and adds some left padding for the text such that the check box part of your CheckBox doesn't run into the text. By changing the background to a color (and not defining any text) there's no minimum height or width anymore, effectively hiding your CheckBox.
If you want a black background, you'll want to copy the btn_check_label_background image over to your res\drawable-hdpi folder, and modify it so that the bits you want black are black. See http://developer.android.com/guide/topics/graphics/2d-graphics.html#nine-patch for more details about how nine-patch drawables work.
Related
I'm new here so i will try to explain my problems as good as i can.
I am trying to inflate a ListView into a View in my main activity. My main activity has some buttons and texts on the top of the Activity and there is enough space left for the listView. The listview is consisted of categories, represented as an imageView and a textview.
The problem im facing is that when i inflate the category_list_activity, the activity i created for the category list, two things happen:
The ListView takes over all the screen, which means i cannot touch neither the buttons nor the edittext, and also the ListView is empty.
I have created the Adapters needed and i have searched for some info here in stackof but i couldn't find any right answer.
Edit: due to solving the problem when the list was taking over the whole screen i remove the parts of code that is not needed.
The solution was to change the inflated activity's (activity_category_list.xml) height from "fill_parent" to "wrap_content". I also restricted the show code to the parts i think there is the problem about not loading the categories.
here is the parts of code i wrote:
MainActivity.java
public class MainActivity extends ActionBarActivity {
Activity a;
Button toogle_button;
Button go_button;
Button login_button;
EditText search_text;
View inflating_view;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
a = this;
inflating_view = findViewById(R.id.inflating_view);
ViewGroup parent =(ViewGroup) inflating_view.getParent();
int index = parent.indexOfChild(inflating_view);
parent.removeView(inflating_view);
inflating_view = getLayoutInflater().inflate(R.layout.activity_category_list, parent, false);
parent.addView(inflating_view, index);
inflating_view.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Toast t = Toast.makeText(getApplicationContext(), "ListView clicked", Toast.LENGTH_SHORT);
t.show();
}
});
}
CategoryAdapter.java
private class Viewholder{
TextView category_text;
ImageView image;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Viewholder holder = null;
Category category = categories.get(position);
if (convertView == null){
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = (View) inflater.inflate(R.layout.activity_category, null);
holder = new Viewholder();
holder.category_text = (TextView) convertView.findViewById(R.id.category_text);
holder.image = (ImageView) convertView.findViewById(R.id.category_image);
convertView.setTag(holder);
}else{
holder = (Viewholder) convertView.getTag();
}
holder.category_text.setText(category.getName());
holder.image.setImageURI(category.getImageUri());
return convertView;
}
}
CategoryListActivity.java
public class CategoryListActivity extends ActionBarActivity {
ListView category_list_view;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_category_list);
Log.d("Category List View", "Category list view is called");
category_list_view = (ListView) findViewById(R.id.category_list_view);
CategoryAdapter ca = new CategoryAdapter(getApplicationContext(),
TestValues.categories);
category_list_view.setAdapter(ca);
category_list_view.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast toast = Toast.makeText(getApplicationContext(),
"Clicked Category" + parent.getItemIdAtPosition(position), Toast.LENGTH_LONG);
toast.show();
}
});
Log.d("Category List View", "Everything is loaded");
}
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#000000"
style="#android:style/Theme.Black.NoTitleBar"
tools:context="com.example.aggro.activities.MainActivity" >
<Button
android:id="#+id/toggle_button"
android:layout_width="50dp"
android:layout_height="30dp"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:text="#string/toogle_list_en"
android:textSize="10dp"
/>
<TextView
android:id="#+id/search_text_view"
android:layout_toRightOf="#+id/toggle_button"
android:layout_alignParentTop="true"
android:text="#string/search_text_en"
android:layout_height="30dp"
android:paddingTop="7dp"
android:textSize="10dp"
android:textColor="#FFFFFF"
android:layout_width="wrap_content"/>
<EditText
android:id="#+id/search_text"
android:layout_width="150dp"
android:layout_height="30dp"
android:layout_alignParentTop="true"
android:textColor="#FFFFFF"
android:textSize="15dp"
android:background="#000000"
android:layout_toLeftOf="#+id/search_go"
android:layout_toRightOf="#+id/search_text_view" />
<Button
android:id="#+id/search_go"
android:layout_width="wrap_content"
android:layout_height="30dp"
android:layout_toLeftOf="#+id/login_button"
android:layout_alignParentTop="true"
android:text="#string/search_go_en"
android:textSize="10dp" />
<Button
android:id="#+id/login_button"
android:layout_width="50dp"
android:layout_height="30dp"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:text="#string/login_en"
android:textSize="10dp" />
<View
android:id="#+id/inflating_view"
android:layout_below="#+id/toggle_button"
android:layout_width="fill_parent"
android:layout_height="fill_parent"/>
</RelativeLayout>
I have checked the CategoryListActivity.java alone and it works as it was supposed to, so i think the adapter works right.
If you need any other information please let me know.
Thanks in advance.
Why are you using View instead of ListView in your activity_main.xml?
Change this part of activity_main.xml
<View
android:id="#+id/inflating_view"
android:layout_below="#+id/toggle_button"
android:layout_width="fill_parent"
android:layout_height="fill_parent"/>
by
<ListView
android:id="#+id/category_list_view"
android:layout_below="#+id/toggle_button"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
In your adapter replace
convertView = (View) inflater.inflate(R.layout.activity_category, null);
by
convertView = inflater.inflate(R.layout.activity_category, null);
No need to cast it.
Remove activity_category_list.xml and CategoryListActivity.java.
Initialize & use ListView & Adapter in MainActivity.java
Try this it will surely work.
In this case what you can do is, create a empty layout in your main activity xml. Set a ID for that. While inflating the listview, inflate it to that layout.
In activity_main.xml include a relative layout as follows. Your parent layout is relative_layout. Add another layout like this.
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView1"
android:layout_below="#+id/login_button" > //make sure you use this property to tell where you want to place the view in the screen. This should be below your last button.
</RelativeLayout>
Since login_button is last button in your view, i have recommended,
android:layout_below="#+id/login_button"
I am facing EXTREMELY PECULIAR problem with my android application. I see not a single similar solution anywhere, either on google or on SO.
Here is my screenshot of the app:
This is normal expected output. But when I exit the app and resume again from launcher, often(say 2 out of 5 times) I happen to get the white components(list view and EditText) like this:
In this image, I have touched the first element of listview while taking screenshot so that its shown that the listview items are having actual content and not empty.
Here is my layout resource file main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/ll"
android:cacheColorHint="#00000000"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent" android:weightSum="15" android:background="#android:color/white">
<EditText
android:layout_width="match_parent"
android:layout_height="0dp"
android:id="#+id/edittext" android:layout_weight="2" android:background="#ffffff"
android:textColor="#android:color/black" android:gravity="center" android:hint="Enter Your Text Here"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp" android:layout_weight="2"
android:weightSum="12" android:gravity="center">
<Button android:layout_width="0dp"
android:layout_height="match_parent"
android:text="Tweet"
android:id="#+id/tweetbtn"
android:background="#drawable/mybutton"
android:layout_weight="6"/>
<Button
android:layout_width="0dp"
android:layout_height="match_parent"
android:text="Search"
android:background="#drawable/mybutton"
android:id="#+id/searchbtn"
android:layout_weight="6"/>
</LinearLayout>
<TextView
android:layout_width="match_parent"
android:layout_height="0dp"
android:text="Most Frequently Tweeted"
android:id="#+id/listviewlabel" android:layout_weight="1" android:gravity="center" android:background="#adadad"
android:textColor="#android:color/black"/>
<ListView
android:cacheColorHint="#00000000"
android:background="#ffffff"
android:layout_width="match_parent"
android:layout_height="0dp"
android:id="#+id/listView" android:layout_gravity="center_horizontal" android:layout_weight="10"
android:choiceMode="singleChoice"/>
</LinearLayout>
Please someone help me out with this. Atleast help me resolve the white EditText issue first. That will give me alteast a clue to solve the listview issue.
EDIT:
The listview is dynamically populated by elements. Here is my onStart() method:
#Override
public void onStart(){
super.onStart();
handleFrequentMenuSelected();
}
Here is the handleFrequentMenuSelected():
private void handleFrequentMenuSelected() {
if(!isAccountAdded()){
showToast("Add an account first to get started! Goto Menu and select account.");
}else{
List<StatusElement>aList=getStatusElementsFromSQLiteDatabase();
HashMap<String,Integer> hMap=new HashMap<String, Integer>();
for(StatusElement s:aList){
String tokens[]=s.toString().split(" ");
String outText="";
if(tokens.length>1){
if(tokens[0].contains("/")){
String tokens2[]=tokens[0].split("/");
try{
long l=Long.parseLong(tokens2[0]);
for(int i=1;i<tokens.length;i++){
outText=outText+tokens[i]+" ";
}
}catch(Exception e){
outText=s.toString();
}
}else{
try{
long l=Long.parseLong(tokens[0]);
for(int i=1;i<tokens.length;i++){
outText=outText+tokens[i]+" ";
}
}catch(Exception e){
outText=s.toString();
}
}
}else{
outText=s.toString();
}
outText=outText.trim();
if(hMap.containsKey(outText)){
int cnt=hMap.get(outText);
cnt++;
hMap.put(outText,cnt);
}else{
hMap.put(outText,1);
}
}
hMap= (HashMap<String, Integer>) StaticConstants.sortByValue(hMap);
ArrayList<String>tweets=new ArrayList<String>();
ArrayList<Integer>frequencies=new ArrayList<Integer>();
ArrayAdapter<String>adapter;
int count=0;
for(String s:hMap.keySet()){
tweets.add(s);
frequencies.add(hMap.get(s));
count++;
if(count==50)
break;
}
adapter=new MyCustomFrequentArrayAdapter(this,tweets,frequencies);
listView.setAdapter(adapter);
listViewLabel.setText("Most Frequent Tweets");
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, final View view,
int position, long id) {
final String item = (String) parent.getItemAtPosition(position);
editText.setText(System.currentTimeMillis()+" "+item);
}
});
}
}
Here is my MyCustomFrequentArrayAdapter:
class MyCustomFrequentArrayAdapter extends ArrayAdapter<String> {
private final Context context;
private final ArrayList<String> values;
private final ArrayList<Integer>frequencies;
public MyCustomFrequentArrayAdapter(Context context, ArrayList<String> values,ArrayList<Integer>frequencies) {
super(context, R.layout.customlistview, values);
this.context = context;
this.values = values;
this.frequencies=frequencies;
}
#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.customlistview, parent, false);
TextView textView1 = (TextView) rowView.findViewById(R.id.firstLine);
TextView textView2 = (TextView) rowView.findViewById(R.id.secondLine);
Log.d("Position",""+position);
//Extracting first six words
String s=values.get(position);
String tokens[]=s.split(" ");
String dispText="";
if(tokens.length>6){
for(int i=0;i<6;i++){
dispText=dispText+tokens[i]+" ";
}
}else{
dispText=s;
}
textView2.setText(dispText);
textView1.setText("Frequency:"+frequencies.get(position));
return rowView;
}
}
Referencing a blog post by Romain Guy - Why Is My List Black
ListView has top and bottom fading edges to indicate it is scrollable.
Creating the fading edge has performance issues so ListView has an optimization to improve performance. Unfortunately the optimization causes problems if the background of the ListView is set to something other than the default.
The optimization can be disabled by setting android:cacheColorHint="#00000000" as you are doing BUT quoting from the blog post...
To fix this issue, all you have to do is either disable the cache color hint optimization, if you use a non-solid color background, or set the hint to the appropriate solid color value.
In other words using android:cacheColorHint="#00000000" should only be used for a "non-solid color" (one which is transparent / translucent).
In your case you are using #ffffff which is an RGB value and by default that means its 'A' component (the alpha) will be ff making it fully opaque, i.e., "solid".
So referring to the last part of the above quote...
...set the hint to the appropriate solid color value.
This suggests you should use android:cacheColorHint="#ffffff" to fix the ListView problem.
I need to create a custom ListPreference dialog so that I can add some header text (a TextView) above the List (ListView).
I've created MyListPreference class that extends ListPreference and overrides onCreateDialogView():
#Override
protected View onCreateDialogView() {
LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = (View) inflater.inflate(R.layout.dialog_preference_list, null);
return v;
}
My XML layout dialog_preference_list.xml contains:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView" />
<ListView
android:id="#android:id/list"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:drawSelectorOnTop="false"
android:scrollbarAlwaysDrawVerticalTrack="true" />
</LinearLayout>
Problem: The TextView is displayed below the ListView instead of above. I need the TextView to be above. I've tried both with LinearLayout and RelativeLayout (using "below" or "above" attributes) with no success: I can't find a way to put the TextView above the ListView... The layout is pretty simple and I cannot see why the list stays above...
Also, note that the problem occurs on both a real device (Nexus 4, Android 4.2.2) and the emulator. However, when looking at the layout rendered in Eclipse's graphical layout, the layout is correct! See both attached pictures.
Any idea on how to solve this?
Layout rendered on the device (incorrect):
Layout rendered on Eclipse (correct):
Edit with solution 10.07.2013
As suggested by the accepted answer, the problem comes from the use of builder.setSingleChoiceItems() in ListPreference's onPrepareDialogBuilder().
I've fixed it by extending ListPreference and overriding onCreateDialogView() to build the Dialog without the builder so that I can create a custom View showing the header text above the list items.
GPListPreference.java:
public class GPListPreference extends ListPreference {
...
#Override
protected void onPrepareDialogBuilder(AlertDialog.Builder builder) {
builder.setNegativeButton(null, null);
builder.setPositiveButton(null, null);
}
private int getValueIndex() {
return findIndexOfValue(getValue());
}
#Override
protected View onCreateDialogView() {
LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
ListView lv = (ListView) inflater.inflate(R.layout.dialog_preference_list, null);
TextView header = (TextView) inflater.inflate(R.layout.dialog_preference_list_header, null);
header.setText(getDialogMessage()); // you should set the header text as android:dialogMessage in the preference XML
lv.addHeaderView(header);
ArrayAdapter<CharSequence> adapter = new ArrayAdapter<CharSequence>(getContext(), R.layout.dialog_preference_list_singlechoice, getEntries());
lv.setAdapter(adapter);
lv.setClickable(true);
lv.setEnabled(true);
lv.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
lv.setItemChecked(getValueIndex() + 1, true);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
setValueIndex(position - 1);
getDialog().dismiss();
}
});
return lv;
}
}
dialog_preference_list.xml:
<?xml version="1.0" encoding="utf-8"?>
<ListView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#android:id/list"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:drawSelectorOnTop="false"
android:scrollbarAlwaysDrawVerticalTrack="true" />
dialog_preference_list_singlechoice.xml
<?xml version="1.0" encoding="utf-8"?>
<CheckedTextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#android:id/text1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:checkMark="?android:attr/listChoiceIndicatorSingle"
android:ellipsize="marquee"
android:gravity="center_vertical"
android:minHeight="?android:attr/listPreferredItemHeight"
android:paddingBottom="2dip"
android:paddingLeft="10dip"
android:paddingRight="10dip"
android:paddingTop="2dip"
android:textAppearance="?android:attr/textAppearanceMedium" />
dialog_preference_list_header.xml
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dip"
android:textAppearance="?android:attr/textAppearanceSmall">
</TextView>
I think the problem is with the way ListPreference works. ListPreference uses Builder.setSingleChoiceItems() to create the rows with the RadioButtons, and it has preference over the custom layout you are trying to add (in your case a TextView and a ListView inside a LinearLayout. The solution is extending DialogPreference instead. Here is a link to a GitHub where I created a custom DialogPreference that does what you need. I haven't coded the RadioButton logic.
I guess it's a theming issue. Try changing the theme of your dialog inside the constructor make it something like setStyle(STYLE_NO_TITLE, R.style.AppTheme). Your base app theme with no_title style.
If this is not the issue than it might be related with the ListPreference class itself. It might be overriding your layout for consistency in theming the preference views. However, I have not used ListPreference before, so its just a guess.
Can you reproduce the same result by playing with the themes in XML graphical layout preview?
Another option you can try is to add the TextView as a header to the ListView like this:
TextView textView = new TextView(getActivity());
ListView listView = new ListView(getActivity());
listView.addHeaderView(textView);
The addHeaderView takes a View so you theoretically have anything you want to be the header, but I have only used a TextView.
The link above is broken. On this solution the idea is overriding the ListPreference, and inflating your own listview, with the data defined on the ListPreference.
#Override
protected View onCreateDialogView() {
LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
ListView lv = new ListView(getContext());
// Inflate the view into the header only if a message was set
if (getDialogMessage() != null && ! getDialogMessage().equals("") ) {
TextView header = (TextView) inflater.inflate(R.layout.dialog_preference_list_header, null);
header.setText(getDialogMessage());
lv.addHeaderView(header, null, false);
}
// Create a new adapter and a list view and feed it with the ListPreference entries
ArrayAdapter<CharSequence> adapter = new ArrayAdapter<CharSequence>(getContext(),
R.layout.custom_dialog_single_choice_list_adapter, getEntries());
lv.setAdapter(adapter);
lv.setClickable(true);
lv.setEnabled(true);
lv.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
lv.setItemChecked(getValueIndex() + 1, true);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
setValueIndex(position - 1);
getDialog().dismiss();
}
});
return lv;
}
Another important thing is to call onPrepareDialogBuilder and not calling super in it. This will avoid that the listview appears twice.
#Override
protected void onPrepareDialogBuilder(AlertDialog.Builder builder) {
// Not calling super, to avoid having 2 listviews
// Set the positive button as null
builder.setPositiveButton(null, null);
}
private int getValueIndex() {
return findIndexOfValue(getValue());
}
Where dialog_preference_list_header is in my case only a TestView, but it could be a more complex view, and custom_dialog_single_choice_list_adapter could be something like this:
<?xml version="1.0" encoding="utf-8"?>
<CheckedTextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#android:id/text1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:checkMark="?android:attr/listChoiceIndicatorSingle"
android:ellipsize="marquee"
android:gravity="center_vertical"
android:minHeight="?android:attr/listPreferredItemHeight"
android:paddingBottom="2dip"
android:paddingLeft="10dip"
android:paddingRight="10dip"
android:paddingTop="2dip"
android:textAppearance="?android:attr/textAppearanceMedium" />
I'd like to implement a Listview in android in which I have the possibility to enable a delete mode, in which the user can select the entries to delete. It should be similar to the message application in android.
I already have a ListActivity which has an icon on the left and text on the right side. I now like to add a CheckBox floating on the right side of the list entry. The ListActivity is listed in another question by a friend of mine: android listactivity background color .
The layout should be:
Left Picture
Center List item
Right Checkbox for delete selection
How can I achieve this? Is there a standard ListView item in the framework I could use?
I guess you want a CheckBox to appear(only) when is time to delete items from the ListView. Assuming you use the layout from the other question:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="5dp"
android:background="#color/darkbluelogo" >
<ImageView android:id="#+id/list_image"
android:layout_width="48dip"
android:layout_height="48dip"
android:contentDescription="#id/list_image"
/>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="fill_parent"
android:padding="5dp"
android:background="#color/darkbluelogo"
android:scrollingCache="false"
android:cacheColorHint="#00000000" >
<TextView
android:id="#+id/title"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#+id/title" >
</TextView>
<TextView
android:id="#+id/datetime"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#+id/datetime" >
</TextView>
</LinearLayout>
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="gone" />
</LinearLayout>
When the ListView starts the CheckBox will not be present and the content TextViews will occupy all the space. Add a flag in the getView method of your adapter that will signal that the CheckBox must be shown(here you will set the CheckBox's visibility from the layout to visible). When its time to delete items modify the flag and then call notifyDataSetChanged() so the ListView redraws its children, this time with the CheckBox present.
Note:
You'll have to store the status of the CheckBoxes yourself.
First of all you need a custom layout for your list entries. A simple RelativeLayout including an ImageView , a TextView and a CheckBox should be enough.
Then you might want to build your own custom adapter which can extend BaseAdapter (or SimpleAdapter or CursorAdapter or ArrayAdapter or...). The adapter will bind the list's data to your custom layout. If for example your data is contained in a Cursor it will look like:
private class MyCustomAdapter extends CursorAdapter {
public MyCustomAdapter(Context context) {
super(context, null);
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
//Return a list item view
return getLayoutInflater().inflate(R.layout.my_custom_list_item_layout, parent, false);
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
//Get views from layout
final ImageView imageView = (ImageView) view.findViewById(R.id.list_item_image);
final TextView textView = (TextView) view.findViewById(R.id.list_item_text);
final CheckBox checkBox = (CheckBox) view.findViewById(R.id.list_item_checkbox);
//Get data from cursor
final String text = cursor.getString(...);
//Add listener to the checkbox
checkBox.setOnClickListener(new OnClickListener() {...});
//Bind data
textView.setText(text);
}
}
I have an Activity that retrieves data from a web service. This data is presented in a ListView via an ArrayAdapter which inflates a RelativeLayout with three TextViews inside, nothing fancy and it work fine.
Now I want to implement a Details Activity that should be called when a user clicks an item in the ListView, sounds easy but I can't for the life of me get the onItemClickListener to work on my ArrayAdapter.
This is my main Activity:
public class Schema extends Activity {
private ArrayList<Lesson> lessons = new ArrayList<Lesson>();
private static final String TAG = "Schema";
ListView lstLessons;
Integer lessonId;
// called when the activity is first created.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// can we use the custom titlebar?
requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
// set the view
setContentView(R.layout.main);
// set the title
getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.titlebar);
// listview called lstLessons
lstLessons = (ListView)findViewById(R.id.lstLessons);
// load the schema
new loadSchema().execute();
// set the click listeners
lstLessons.setOnItemClickListener(selectLesson);
}// onCreate
// declare an OnItemClickListener for the AdapterArray (this doesn't work)
private OnItemClickListener selectLesson = new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View v, int i, long l) {
Log.v(TAG, "onItemClick fired!");
}
};
private class loadSchema extends AsyncTask<Void, Void, Void> {
private ProgressDialog progressDialog;
// ui calling possible
protected void onPreExecute() {
progressDialog = ProgressDialog.show(Schema.this,"", "Please wait...", true);
}
// no ui from this one
#Override
protected Void doInBackground(Void... arg0) {
// get some JSON, this works fine
}
#Override
protected void onPostExecute(Void result) {
progressDialog.dismiss();
// apply to list adapter
lstLessons.setAdapter(new LessonListAdapter(Schema.this, R.layout.list_item, lessons));
}
My ArrayAdapter code:
// custom ArrayAdapter for Lessons
private class LessonListAdapter extends ArrayAdapter<Lesson> {
private ArrayList<Lesson> lessons;
public LessonListAdapter(Context context, int textViewResourceId, ArrayList<Lesson> items) {
super(context, textViewResourceId, items);
this.lessons = items;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.list_item, null);
}
Lesson o = lessons.get(position);
TextView tt = (TextView) v.findViewById(R.id.titletext);
TextView bt = (TextView) v.findViewById(R.id.timestarttext);
TextView rt = (TextView) v.findViewById(R.id.roomtext);
v.setClickable(true);
v.setFocusable(true);
tt.setText(o.title);
bt.setText(o.fmt_time_start);
rt.setText(o.room);
return v;
}
}// LessonListAdapter
The main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout android:id="#+id/main"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="fill_parent" android:layout_width="fill_parent"
android:screenOrientation="portrait"
>
<!-- student name -->
<TextView
android:id="#+id/schema_view_student"
android:text="Name" android:padding="4dip"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:gravity="center_vertical|center_horizontal"
style="#style/schema_view_student"
/>
<!-- date for schema -->
<TextView
android:id="#+id/schema_view_title"
android:layout_height="wrap_content"
android:layout_margin="0dip"
style="#style/schema_view_day"
android:gravity="center_vertical|center_horizontal"
android:layout_below="#+id/schema_view_student"
android:text="Date" android:padding="6dip"
android:layout_width="fill_parent"
/>
<!-- horizontal line -->
<View
android:layout_width="fill_parent"
android:layout_height="1dip"
android:background="#55000000"
android:layout_below="#+id/schema_view_title"
/>
<!-- list of lessons -->
<ListView
android:id="#+id/lstLessons"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:layout_below="#+id/schema_view_title"
/>
</RelativeLayout>
The list_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="60px"
android:padding="12dip">
<TextView
android:id="#+id/timestarttext"
android:text="09:45"
style="#style/LessonTimeStartText"
android:layout_width="60dip"
android:layout_alignParentTop="true"
android:layout_alignParentBottom="true"
android:layout_height="fill_parent" android:gravity="center_vertical|right" android:paddingRight="6dip"/>
<TextView
android:id="#+id/titletext"
android:text="Test"
style="#style/LessonTitleText"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_toRightOf="#+id/timestarttext"
android:layout_alignParentTop="true"
android:layout_alignParentBottom="true" android:gravity="center_vertical|center_horizontal"/>
<TextView
android:id="#+id/roomtext"
android:text="123"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
style="#style/LessonRoomText"
android:layout_alignParentTop="true"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:gravity="center_vertical" />
</RelativeLayout>
Been messing with this for the last couple of hours and I can't seem to get my head around what the problem is. My problem looks very similar to this question, but I'm not extending ListActivity, so I still don't know where my onListClickItem() should go.
UPDATE: Now I've puzzled with this for several days and still can't find the issue.
Should I rewrite the activity, this time extending ListActivity instead of Activity? Because it provides the onItemClick method itself and is probably easier to overwrite.
Or, should I bind a listener directly in each getView() in my ArrayAdapter? I believe I have read this is bad practice (I should do as I tried and failed in my post).
Found the bug - it seems to be this issue. Adding android:focusable="false" to each of the list_item.xml elements solved the issue, and the onclick is now triggered with the original code.
I've encountered the same issue and tried your fix but couldn't get it to work. What worked for me was adding android:descendantFocusability="blocksDescendants" to the <RelativeLayout> from the item layout xml, list_item.xml in your case. This allows onItemClick() to be called.
What worked for me :
1) Adding android:descendantFocusability="blocksDescendants" to Relative Layout tag.
The result is shown below :
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:descendantFocusability="blocksDescendants" >
2) Adding android:focusable="false" to every element in in list_item.xml
example :
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView"
android:focusable="false" />
Once I had a similar problem. Every list item had a text view and a checkbox, and just because the checkbox, the whole listitem wasn't 'enabled' to fire the event. I solved it by making a little trick inside the adapter when I was getting the view.
Just before returning the view I put:
v.setOnClickListener(listener);
(The object listener is an onItemClickListener I gave to the Adapter's constructor).
But I have to tell you, the problem is because the platform, it is a bug.
I had the same problem and I tried to solve it by adding
android:focusableInTouchMode="false"
android:clickable="false"
android:focusable="false"
to my item.xml but it still doesn't work !!! Infact I found the issue in the relative layout witch contains
android:focusableInTouchMode="true" android:focusable="true"
And when I removed it All things is ok
protected void onPostExecute(Void result) {
progressDialog.dismiss(); stLessons.setAdapter(new LessonListAdapter(Schema.this, R.layout.list_item, lessons));
//add this
ListView lv = getListView(); lv.setOnItemClickListener(new ListView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> a, View v, int i, long l) {
//do stuff
}
});
}