Sorry if I ask silly question, but so far had no luck in figuring out this one. I have form with 2 radio buttons that decide layout and used components of layout bellow them. Here is one of the layouts
<?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="fill_parent">
<TextView
android:id="#+id/arrival_date_label"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/arrival_date_label"/>
<EditText
android:id="#+id/arrival_date"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/arrival_date_label"
android:hint="10/05/2012"/>
<Spinner
android:id="#+id/arrival_time_spinner"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/arrival_date"/>
<TextView
android:id="#+id/return_date_label"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/return_date_label"
android:layout_below="#id/arrival_time_spinner"/>
<EditText
android:id="#+id/return_date"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/return_date_label"
android:hint="10/05/2012"/>
<Spinner
android:id="#+id/return_time_spinner"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/return_date"/>
</RelativeLayout>
and Java class to initialize some of the components used
public class ReturnFixedDays extends RelativeLayout {
private EditText arrivalDate;
private Spinner arrivalTime;
private EditText returnDate;
private Spinner returnTime;
private final String pattern = "dd/MM/yyyy";
public ReturnFixedDays(Context context, AttributeSet attrs) {
super(context, attrs);
LayoutInflater inflater = LayoutInflater.from(context);
View view = inflater.inflate(R.layout.return_fixed_days, null);
arrivalDate = (EditText) view.findViewById(R.id.arrival_date);
arrivalDate.setText(arrivalDate());
arrivalTime = (Spinner) view.findViewById(R.id.arrival_time_spinner);
ArrayAdapter adapter = new ArrayAdapter(context, R.array.travel_time_entries,android.R.layout.simple_spinner_item);
arrivalTime.setAdapter(adapter);
returnDate = (EditText) view.findViewById(R.id.return_date);
returnDate.setText(returnDate());
returnTime = (Spinner) view.findViewById(R.id.return_time_spinner);
ArrayAdapter adapter2 = new ArrayAdapter(context, R.array.travel_time_entries,android.R.layout.simple_spinner_item);
returnTime.setAdapter(adapter2);
}
private String arrivalDate(){
return dateToString(today());
}
private String returnDate(){
return dateToString(weekLater());
}
private String dateToString(Date date){
return formatter().format(date);
}
private SimpleDateFormat formatter(){
return new SimpleDateFormat(pattern);
}
private Date weekLater(){
return adjustDateBy(today(), 7);
}
private Date today(){
return Calendar.getInstance().getTime();
}
private Date adjustDateBy(Date currentDate, int numOfDays) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(currentDate);
calendar.add(Calendar.DATE, numOfDays);
return calendar.getTime();
}
}
Now to add this layout to view I do as following in xml
<RelativeLayout
android:id="#+id/dates_layout"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#id/flight_layout">
<TextView
android:id="#+id/date_label"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="#string/dates_label"
style="#style/Label"/>
<RadioGroup
android:id="#+id/dates_radio_group"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_below="#id/date_label">
<RadioButton
android:id="#+id/flexible_dates_radio"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/flexible_dates_label"
style="#style/Label"/>
<RadioButton
android:id="#+id/fixed_dates_radio"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="true"
android:text="#string/fixed_dates_label"
style="#style/Label"/>
</RadioGroup>
</RelativeLayout>
<RelativeLayout
android:id="#+id/stub_container"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#id/dates_layout">
<com.flyweekend.android.date.view.ReturnFixedDays
android:id="#+id/return_fixed_days_stub"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout="#layout/return_fixed_days"/>
<com.flyweekend.android.date.view.ReturnFlexibleDays
android:id="#+id/return_flexible_days_stub"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout="#layout/return_flexible_days"/>
</RelativeLayout>
FlightView.java
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
context = getActivity();
dateTypeRadioGrp = dateTypeRadioGroup(view);
returnFixedDays = (RelativeLayout) view.findViewById(R.id.return_fixed_days_stub);
updateDatesVisibility();
return view;
}
private RadioGroup dateTypeRadioGroup(View view){
RadioGroup group = (RadioGroup)view.findViewById(R.id.dates_radio_group);
group.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
public void onCheckedChanged(RadioGroup radioGroup, int selected) {
if(selected == R.id.flexible_dates_radio){
Log.i(TAG, "Flexible dates selected");
updateDatesVisibility();
}else{
Log.i(TAG, "Fixed dates selected");
updateDatesVisibility();
}
}
});
return group;
}
private void updateDatesVisibility(){
if(dateTypeRadioGrp.getCheckedRadioButtonId() == R.id.fixed_dates_radio){
returnFixedDays.setVisibility(View.VISIBLE);
} else{
returnFixedDays.setVisibility(View.INVISIBLE);
}
}
However neither group is ever visible. I guess I need extra pair of eyes to spot where I'm going wrong in adding these layouts dynamically.
With this:
View view = inflater.inflate(R.layout.return_fixed_days, null);
you've just inflated a layout file, you didn't actually attached it to your custom view ReturnFixedDays. To attach that inflated layout to your custom view you have to pass this as the second parameter(representing the parent of the newly inflated view hierarchy):
View view = inflater.inflate(R.layout.return_fixed_days, this);
There could be other things wrong in your code, so check and see if this solves your problem.
Related
I am using a custom CursorAdapter and have values in DB but the problem is that the values are not displaying in the custom ListView. I searched in SO but could not find my answer.
By debugging I found out that the 2 methods in cursor adapter bindView() and the newView() are not executing but the constructor is executing.I am not sure what is happening overall. So my question is why are the ListView items not getting displayed ?
Here is my code and I am only posting relevant code so if there is any additional code needed please comment so that I will edit accordingly.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//a listview object
notesView = (ListView)findViewById(R.id.listView);
//an object of SQLiteOpenHelper class
dbhelper = new DataBaseHelper(this);
//cursor object
passCursor = dbhelper.fetchAllNotes();
// the custom cursor adapter class object
dataCursor = new CustomCursor(this,passCursor);
notesView.setAdapter(dataCursor);
notesView.setOnItemClickListener(this);
bar = (Toolbar)findViewById(R.id.toolbar);
setSupportActionBar(bar);
}
Here is the CursorAdapter source code:
public class CustomCursor extends CursorAdapter {
private static final String NOTE_TITLE = "title";
private static final String RECORD_ID = "_id";
private static final String RECORD_DATE = "date";
private static final String DELETE_FLAG="deleteflag";
LayoutInflater inflater;
TextView tv, recordID, dateET;
LinearLayout ll;
String getText, existsRecordID;
long datevalue;
SimpleDateFormat dateFormatter;
String listViewHeight;
Context cont;
int getDeleteFlag;
String listHeightValue;
LinearLayout.LayoutParams params;
Cursor getCursor;
CustomCursor(Context context, Cursor c) {
super(context, c, 0);
cont= context;
getCursor= c;
//inflater = LayoutInflater.from(context);
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
dateFormatter = new SimpleDateFormat("dd-MM-yyyy HH:mm");
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return inflater.inflate(R.layout.customlistview, parent, false);
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
getDeleteFlag = cursor.getInt(cursor.getColumnIndex(DELETE_FLAG));
ll = (LinearLayout)view.findViewById(R.id.listViewLayout);
setListViewHeight(ll,context);
getText = cursor.getString(cursor.getColumnIndex(NOTE_TITLE));
existsRecordID = cursor.getString(cursor.getColumnIndex(RECORD_ID));
datevalue = cursor.getLong(cursor.getColumnIndex(RECORD_DATE));
Date newdate = new Date(datevalue);
recordID = (TextView) view.findViewById(R.id.recordID);
tv = (TextView) view.findViewById(R.id.content);
dateET = (TextView) view.findViewById(R.id.date);
tv.setText(getText.trim());
recordID.setText(existsRecordID);
dateET.setText(dateFormatter.format(newdate));
}
}
EDIT 1
Here is the main layout,
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/fragplacement"
xmlns:android="http://schemas.android.com/apk/res/android">
<LinearLayout 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"
android:gravity="top|left"
android:descendantFocusability="blocksDescendants"
tools:context="com.random.simplenotes.MainActivity">
<android.support.v7.widget.Toolbar
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/toolbar"
>
</android.support.v7.widget.Toolbar>
<ListView
android:layout_width="match_parent"
android:clickable="true"
android:layout_height="match_parent"
android:id="#+id/listView"
android:scrollbars="vertical"
/>
</LinearLayout>
</FrameLayout>
Here is the layout for the listView item,
<?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="wrap_content"
android:descendantFocusability="blocksDescendants"
android:background="#color/PeachPuff"
android:id="#+id/listViewLayout"
android:layout_margin="7dp">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Here is the content.."
android:gravity="center"
android:id="#+id/content"
android:textColor="#color/black"
android:focusable="false"
android:ellipsize="end"
android:lines="1"
android:maxLines="1"
android:layout_gravity="center_horizontal" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#color/black"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="12/09/15"
android:layout_margin="10dp"
android:focusable="false"
android:id="#+id/date" />
<TextView
android:layout_width="1dp"
android:layout_height="1dp"
android:visibility="gone"
android:focusable="false"
android:id="#+id/recordID" />
</LinearLayout>
Code for the method setListViewHeight()
private void setListViewHeight(LinearLayout ll, Context con) {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(con);
listHeightValue = sp.getString(con.getResources().getString(R.string.listViewHeightkey),Constants.DEFAULT_VALUE_LISTVIEW_HEIGHT);
switch (listHeightValue)
{
case "Tiny":
params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,200);
ll.setLayoutParams(params);
break;
case "Medium":
params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,220);
ll.setLayoutParams(params);
break;
case "Large":
params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,250);
ll.setLayoutParams(params);
break;
default:
params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,150);
ll.setLayoutParams(params);
}
}
The problem is your haven't set the orientation of the LinearLayout in your main layout, so it defaults to horizontal.
This means the ListView is placed next to the Toolbar, but the width of the Toolbar is set to match_parent, so there is no room left for the ListView.
Add the following attribute to the LinearLayout in activity_main.xml, so the ListView will be placed below the Toolbar:
android:orientation="vertical"
Also, the following call might need to be removed from bindView():
setListViewHeight(ll,context);
The height of the ListView is already set properly in XML, this call might mess it up (i can only assume, since you haven't posted the implementation of setListViewHeight()).
Check if your Cursor is empty... if you are sure that it is not empty then for patching call the following code in the last line in out Activity -> onCreate() ...
dataCursor.notifyDataSetChanged();
I have used a TableLayout to produce the following cart activity output.
.
So the listview has 3 listviews(Item,Price,quantity) and a button (for delete)
I wanted to give a heading to the cart. So, I initalized the first item of the listview as the title ('Item Name','Price','Quantity','Delete')
Now The problem is, Whenever the user clicks on delete button (as circled in the pic), The title also gets deleted. (Since the onClickListener has been applied to all buttons by default in the adapter class)
How should i remove the onClickListener on the first Button and keep it as it is for the rest of the buttons ?
Extra: If you guys can suggest some awesome way to format this cart so that it doesnt look so naive, It'd be great. :) Happy Diwali and Thanks in Advance.
- Android newBee
cartlayout.xml file
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:stretchColumns="*"
android:background="#ffffff">
<TableRow>
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/cartlist_layout"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/t1"
android:textStyle="normal|bold"
android:padding="5dip"
android:layout_alignParentLeft="true"
android:layout_toLeftOf="#+id/t2"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/t2"
android:padding="5dip"
android:textStyle="normal|bold"
android:layout_centerHorizontal="true"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_toRightOf="#+id/t2"
android:id="#+id/t3"
android:textStyle="normal|bold" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/button6" />
</TableRow>>
</TableLayout>
The Java Code:
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view=inflater.inflate(R.layout.fragment_mycart,container,false);
this.getActivity().setTitle("AADESH");
cartlistview=(ListView)view.findViewById(R.id.listView1);
db=new DatabaseHelper(this.getContext());
db.onCreate();
Cursor res=db.onView();
int len=res.getCount();
listCartItems = new ArrayList<CartItems>();
listCartItems.add(new CartItems("Item Name", "Quantity", "Price","Delete"));
if(len==0)
{
Toast.makeText(this.getContext(),"Cart is Empty.",Toast.LENGTH_SHORT).show();
statusOfCart=false;
}
else {
while (res.moveToNext()) {
String itemname = res.getString(1).toString(); // 0 is id, 1 is name, 2 is qty, 3 price
String itemqty = Integer.toString(res.getInt(2));
String itemprice = Integer.toString(res.getInt(3)) ;
Toast.makeText(this.getContext(),itemname,Toast.LENGTH_SHORT).show();
listCartItems.add(new CartItems(itemname, itemqty, itemprice,"X"));
}
}
CartListAdapter cartListAdapter = new CartListAdapter(getContext(), R.layout.cartlist_layout, listCartItems);
cartlistview.setAdapter(cartListAdapter);
return view;
}
}
And the CartAdapter Java Code here:
public class CartListAdapter extends ArrayAdapter<CartItems> {
Context context;
int resLayout;
List<CartItems> listCartItems;
int pos;
public CartListAdapter(Context context,int resLayout,List <CartItems> listCartItems) {
super(context, resLayout, listCartItems);
this.context=context;
this.resLayout=resLayout;
this.listCartItems=listCartItems;
}
#NonNull
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View v=View.inflate(context,resLayout,null);
pos=position;
TextView name=(TextView)v.findViewById(R.id.t1);
TextView qty=(TextView)v.findViewById(R.id.t2);
TextView price=(TextView)v.findViewById(R.id.t3);
Button delete=(Button)v.findViewById(R.id.button6);
CartItems cartItems=listCartItems.get(position);
name.setText(cartItems.getItemname());
qty.setText(String.valueOf(cartItems.getQty()));
price.setText(String.valueOf(cartItems.getPrice()));
delete.setText(String.valueOf(cartItems.getDel()));
delete.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
listCartItems.remove(position);
notifyDataSetChanged();
}
}
);
return v;
}
}
execute listCartItems.remove(position); only when position > 0.
I have a ListView in one of my activities that I have bound to an ArrayList using a custom ArrayAdapter. I have set an OnItemClickListener to the ListView which should call a method that starts another activity. However, I find that when I click on the ListView items, it only sometimes works. Sometimes it will start the activity as it should; other times it seems to detect the click (the ripple effect appears on the list item) but does nothing; other times it doesn't even appear to detect the click (the ripple effect doesn't appear).
I've tried all the usual suggestions that I've come across: blocking descendants on the parent view item, setting clickable and focusable to false on all the components of the item views, setting isEnabled to return true in the custom adapter, etc, but the behavior remains the same. Any help appreciated. Here is the relevant code:
Activity containing the ListView:
public class ViewCollectionActivity extends AppCompatActivity {
private final String className = this.getClass().getSimpleName();
private CollectionHandler collectionHandler;
private Context context;
private ArrayList<Game> displayedCollection;
private GameCollectionAdapter collectionAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_collection);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
context = this;
collectionHandler = CollectionHandler.getInstance(this);
TextView view = null;
if (collectionHandler.getDisplayedCollection().size() > 0) {
view = (TextView) findViewById(R.id.no_items_textview);
view.setVisibility(View.GONE);
}
String currentDate = collectionHandler.getDateLastSynchronised();
view = (TextView) findViewById(R.id.last_updated_textview);
view.setText("Last synchronised: " + currentDate + " Total games: " + String.valueOf(collectionHandler.getDisplayedCollection().size()));
collectionAdapter = collectionHandler.getCollectionAdapter();
ListView listView = (ListView) findViewById(R.id.collection_list_view);
listView.setAdapter(collectionAdapter);
AdapterView.OnItemClickListener collectionItemClickListener = new AdapterView.OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
launchGameDetailsActivity(position);
}
};
listView.setOnItemClickListener(collectionItemClickListener);
}
public void launchGameDetailsActivity(int position){
Log.d(className,"Starting lauchGameDetailsActivity method");
collectionHandler.setSelectedGame(position);
Intent intent = new Intent(this,ViewGameDetailsActivity.class);
startActivity(intent);
Log.d(className, "Ending lauchGameDetailsActivity method");
}
The XML for the activity:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
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.bleachedlizard.ludome.viewcollection.ViewCollectionActivity">
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Synchronise Collection"
android:onClick="synchroniseCollection"/>
<TextView
android:id="#+id/last_updated_textview"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Last synchronised: "
android:textAlignment="center"
/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Display Collection"
android:visibility="gone"
android:onClick="displayCollection"/>
<ListView
android:id="#+id/collection_list_view"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1">
</ListView>
<TextView
android:id="#+id/no_items_textview"
android:layout_width="match_parent"
android:layout_height="50dp"
android:text="You have no items in your collection."
android:textAlignment="center"
android:textSize="20sp"/>
</LinearLayout>
The XML for the item views:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/collection_item_layout"
android:layout_width="match_parent"
android:layout_height="75dp"
android:orientation="horizontal"
android:clickable="false"
android:descendantFocusability="blocksDescendants"
android:focusable="false"
android:focusableInTouchMode="false">
<ImageView
android:id="#+id/collection_item_image"
android:layout_width="75dp"
android:layout_height="75dp"
android:src="#drawable/testimage"
android:focusable="false"
android:focusableInTouchMode="false"
android:clickable="false"
/>
<TextView
android:id="#+id/collection_item_name"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:gravity="center_vertical"
android:padding="16dp"
android:singleLine="false"
android:textColor="#android:color/darker_gray"
android:focusable="false"
android:focusableInTouchMode="false"
android:clickable="false"
android:textIsSelectable="false"/>
<TextView
android:id="#+id/collection_item_plays"
android:layout_width="100dp"
android:layout_height="match_parent"
android:gravity="center_vertical"
android:padding="8dp"
android:textColor="#android:color/darker_gray"
android:text="Plays: 0"
android:focusable="false"
android:focusableInTouchMode="false"
android:clickable="false"
android:textIsSelectable="false"/>
</LinearLayout>
The code for the custom adapter:
public class GameCollectionAdapter extends ArrayAdapter<Game> {
private ArrayList<Game> collection;
public GameCollectionAdapter(Context context, int resource, ArrayList<Game> collection){
super(context, resource, collection);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LinearLayout gameView = (LinearLayout) convertView;
LayoutInflater mInflater = LayoutInflater.from(getContext());
if (gameView == null) {
gameView = (LinearLayout) mInflater.inflate(R.layout.collection_item_view, null);
}
//Game game = collection.get(position);
Game game = super.getItem(position);
if (game != null) {
// This is how you obtain a reference to the TextViews.
// These TextViews are created in the XML files we defined.
TextView gameTitle = (TextView) gameView.findViewById(R.id.collection_item_name);
TextView numOfPlays = (TextView) gameView.findViewById(R.id.collection_item_plays);
ImageView thumbnail = (ImageView) gameView.findViewById(R.id.collection_item_image);
// check to see if each individual textview is null.
// if not, assign some text!
if (gameTitle != null){
gameTitle.setText(game.getTitle());
}
if (numOfPlays != null){
numOfPlays.setText("Plays: " + String.valueOf(game.getNumOfPlays()));
}
if (thumbnail != null){
thumbnail.setImageBitmap(game.getThumbnail());
}
}
// the view must be returned to our activity
return gameView;
}
#Override
public boolean isEnabled(int position) {
return true;
}
}
I discovered what was causing the problem: the way I had set up the array that backed the ListView meant that it was downloading and storing the Bitmaps for every element in the array all the time. Once I changed the implementation so that it only downloaded the images as the ListView required them, then that seemed to improve performance and the onClickListener started to work fine.
The implementation I used was the exact same one shown here:
http://developer.android.com/training/displaying-bitmaps/process-bitmap.html
I think the issue is due to the position of the item selection whenever you click you have an list position which is passed to your method launchGameDetailActivity(int position) check with log or toast on item click what all the position you are getting do the needful.
Here is my code try this like this if it helps.
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(RecipeClass.this, "Position is" + position, Toast.LENGTH_SHORT).show();
Intent intent = new Intent(RecipeClass.this, RecipeIngredients.class)
intent.putExtra("position", position);
startActivity(intent);
}
Check your arraylist value also whether they are not null.
This is my first app. I had been setting a preference in an activity (with a fragment), but I want to move the fragment to a DialogPreference. It migrated okay, except my text colors have gone weird. See picture. The text should just be black, not white and gray. Any idea what I got wrong?
(Sorry, I know this is pretty sloppy code)
How it looks now:
My xml...
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/relLay_dialog_semester_root"
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" >
<TextView
android:id="#+id/select_semester_prompt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/select_semester_prompt" />
<LinearLayout
android:id="#+id/linLayGradeSum"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/select_semester_prompt"
android:layout_centerHorizontal="true"
android:layout_marginTop="20dp" >
<Spinner
android:id="#+id/semester_spinner"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="3"
android:hint="#string/hint_editSemester" />
<Spinner
android:id="#+id/year_spinner"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="4" />
</LinearLayout>
<TextView
android:id="#+id/active_semesters_str"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/linLayGradeSum"
android:layout_below="#+id/linLayGradeSum"
android:text="#string/active_semester_str"
android:textAppearance="?android:attr/textAppearanceMedium" />
<LinearLayout
android:id="#+id/active_semesters_list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/active_semesters_str"
android:layout_below="#+id/active_semesters_str"
android:layout_marginTop="10dp"
android:orientation="vertical" >
</LinearLayout>
</RelativeLayout>
My extended DialogPreference class
public class SemesterDialogPreference extends DialogPreference {
SharedPreferences settings;
public static int YEAR_DEFAULT_VALUE = Activity_AddCourse.thisYear - Activity_AddCourse.baseYear;
public static int SEASON_DEFAULT_VALUE = Semester.getDefaultSemester().getSeasonInt();
public static int SEMESTER_DEFAULT_ID = 1;
String semester_id_key;
DBAdapter db;
// this is where I do everything view-related
#Override
public void onBindDialogView(View view){
settings = getSharedPreferences();
int curSemesterId = settings.getInt(semester_id_key, 1);
db = new DBAdapter(this.getContext().getApplicationContext());
db.open();
Semester curSemester = db.getSemester(curSemesterId);
db.close();
ArrayList<String> years = new ArrayList<String>();
for (int i = Activity_AddCourse.baseYear; i <= Activity_AddCourse.maxYear; i++)
{
years.add(Integer.toString(i));
}
ArrayAdapter<String> adapter_year = new ArrayAdapter<String>(this.getContext().getApplicationContext(),
android.R.layout.simple_spinner_item, years);
Spinner spinYear = (Spinner)view.findViewById(R.id.year_spinner);
adapter_year.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinYear.setAdapter(adapter_year);
spinYear.setSelection(curSemester.getYear() - Activity_AddCourse.baseYear);
Spinner spinner = (Spinner) view.findViewById(R.id.semester_spinner);
ArrayAdapter<CharSequence> adapter_spinner = ArrayAdapter.createFromResource(this.getContext().getApplicationContext(),
R.array.semester_spinner, android.R.layout.simple_spinner_item);
adapter_spinner.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter_spinner);
spinner.setSelection(Semester.seasonStringToInt(curSemester.getSeason()));
db = new DBAdapter(this.getContext().getApplicationContext());
db.open();
Semester[] s = db.getAllSemesters();
db.close();
String activeSem;
LinearLayout semesterList = (LinearLayout) view.findViewById(R.id.active_semesters_list);
if(s != null){
for(int i = 0; i < s.length; i++){
activeSem = s[i].getSemesterString();
TextView tv = (TextView) new TextView(this.getContext().getApplicationContext());
tv.setText(activeSem);
semesterList.addView(tv);
System.out.println(s[i].getSemesterString());
}
}
super.onBindDialogView(view);
}
public SemesterDialogPreference(Context context, AttributeSet attrs) {
super(context, attrs);
setDialogLayoutResource(R.layout.dialog_set_semester);
}
#Override
protected void onDialogClosed(boolean positiveResult) {
super.onDialogClosed(positiveResult);
persistBoolean(positiveResult);
}
}
UPDATE:
The DialogPreference pops up from my settings activity, as shown below.
public class SettingsActivity extends PreferenceActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.settings);
}
}
Also, I was able to get the spinner text to black by making my own xml layouts for them, just as Huy Tran suggested. However, I had to make one for each the spinner_item and the spinner_dropdown_item. See below.
ArrayAdapter<String> adapter_year = new ArrayAdapter<String>(this.getContext().getApplicationContext(),
R.layout.my_spinner_item, years);
Spinner spinYear = (Spinner)view.findViewById(R.id.year_spinner);
adapter_year.setDropDownViewResource(R.layout.my_spinner_dropdown_item);
Why did I have to do this? I don't know. Also, dropdown items are each now about 50% taller. I copied exactly from source code into my own xml and it still renders differently. Very weird.
Create a layout like below and use that layout in setDropDownViewResource instead of android.R.layout.simple_spinner_dropdown_item.
Create my_spinner_dropdown_item.xml in res/layout:
EDITED:
<?xml version="1.0" encoding="utf-8"?>
<CheckedTextView xmlns:android="http://schemas.android.com/apk/res/android"
style="?android:attr/spinnerDropDownItemStyle"
android:singleLine="true"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ellipsize="marquee"
android:textColor="#color/black"
/>
my_spinner_item
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#android:id/text1"
style="?android:attr/spinnerItemStyle"
android:singleLine="true"
android:textColor="#android:color/transparent"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ellipsize="marquee" />
Try using margin to change the size of each item.
And then in your SemesterDialogPreference:
setDropDownViewResource(R.layout.my_spinner_dropdown_item);
I recently upgraded my application to use ActionBarSherlock 4.1. Since the upgrade users running the app on Honeycomb experiance a force close due to a null pointer exception when setting a custom view on the actionbar.
I add a custom view containing two spinners to the actionbar this works on Android 4.0 & 4.1 but is not working on 3.2.
bar.setCustomView(R.layout.custom_action_bar);// spinners
actionBarViewHolder= new CustomActionBarViewHolder();
actionBarViewHolder.categorySpinner = (Spinner) findViewById(R.id.actionbar_catergory);
actionBarViewHolder.sortBySpinner = (Spinner) findViewById(R.id.actionbar_sortby);
On Android 3.2 the spinners can not be found yet on 4.0 and 4.1 they views are found and anything runs smoothly.
I have not tried the application on a 3.0 emulator but I image the problem persists.
Any ideas what could be the problem?
<LinearLayout android:id="#+id/linearLayout1"
android:layout_width="wrap_content" android:layout_height="match_parent"
android:gravity="center_vertical|center_horizontal"
android:layout_weight="0.5">
<TextView android:id="#+id/textView1" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:text="Category:" />
<Spinner android:id="#+id/actionbar_catergory"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:entries="#array/actionbar_spinner_catergory"
android:background="#drawable/spinner_background" />
</LinearLayout>
<LinearLayout android:id="#+id/linearLayout1"
android:layout_width="wrap_content" android:layout_height="match_parent"
android:gravity="center_vertical|center_horizontal"
android:layout_weight="0.5">
<TextView android:id="#+id/textView2" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:text="Sort By:" />
<Spinner android:id="#+id/actionbar_sortby"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:entries="#array/actionbar_spinner_sortby" android:background="#drawable/spinner_background" />
</LinearLayout>
Try this, its working fine on all devices or you can check the demo code here
getSupportActionBar().setCustomView(R.layout.actionbar_top); // load your layout
getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
Images
Try this:
final View view = inflater.inflate(R.layout.custom_action_bar, null);
bar.setCustomView(view);// spinners
actionBarViewHolder= new CustomActionBarViewHolder();
actionBarViewHolder.categorySpinner = (Spinner) view.findViewById(R.id.actionbar_catergory);
actionBarViewHolder.sortBySpinner = (Spinner) view.findViewById(R.id.actionbar_sortby);
Here is code how I create custom action bar with actiobBarSherlock
private void createCustomActionBar() {
List<SiteLink> links = new ArrayList<SiteLink>();
links.add(...)
LinksAdapter linkAdapter = new LinksAdapter(this, R.layout.external_link, links);
View customNav = LayoutInflater.from(this).inflate(R.layout.custom_show_action_bar, null);
IcsSpinner spinner = (IcsSpinner)customNav.findViewById(R.id.spinner);
spinner.setAdapter(linkAdapter);
ImageView refresh = (ImageView) customNav.findViewById(R.id.refresh);
refresh.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
...
}
});
ImageView settings = (ImageView) customNav.findViewById(R.id.settings);
settings.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
...
}
});
getSupportActionBar().setCustomView(customNav, new ActionBar.LayoutParams(Gravity.RIGHT));
getSupportActionBar().setDisplayShowCustomEnabled(true);
}
Adapter
private static class LinksAdapter extends ArrayAdapter<SiteLink> {
private List<SiteLink> strings;
private Context context;
private LinksAdapter(Context context, int textViewResourceId, List<SiteLink> objects) {
super(context, textViewResourceId, objects);
this.strings = objects;
this.context = context;
}
#Override
public int getCount() {
if (strings == null) return 0;
return strings.size();
}
#Override
public SiteLink getItem(int position) {
return super.getItem(position);
}
// return views of drop down items
#Override
public View getDropDownView(int position, View convertView, ViewGroup parent) {
final SiteLink siteLink = strings.get(position);
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// at 0 position show only icon
TextView site = (TextView) inflater.inflate(R.layout.external_link, null);
site.setText(siteLink.getName());
site.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(siteLink.getUrl()));
context.startActivity(i);
}
});
return site;
}
// return header view of drop down
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
return inflater.inflate(R.layout.icon, null);
}
}
Layout
<?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:gravity="right"
>
<com.actionbarsherlock.internal.widget.IcsSpinner
android:id="#+id/spinner"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:paddingRight="20dp"
android:layout_gravity="center"
/>
<ImageView android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:src="#drawable/ic_navigation_refresh"
android:paddingRight="20dp"
android:paddingLeft="10dp"
android:layout_gravity="center"
android:background="#drawable/action_buttons_background"
android:id="#+id/refresh"/>
<ImageView android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:src="#drawable/ic_action_settings"
android:paddingRight="20dp"
android:background="#drawable/action_buttons_background"
android:layout_gravity="center"
android:id="#+id/settings"/>
</LinearLayout>
Have you tried to put your two children LinearLayout's inside a main LinearLayout?. Also try to not repeat the id from the children LinearLayout's, because you're making your id's system cry. But I'm almost sure your problem is that you have more than one main Layouts in the XML file.
Use below code for setCustomView using actionbarsherlib.
It is worked in android 3.2 version also.
getSupportActionBar().setDisplayShowCustomEnabled(true);
View view = getLayoutInflater().inflate(R.layout.custom_view, null);
Button mybutton = (Button)view.findViewById(R.id.button1);
mybutton.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
/** Your click actions here. */
}
});
getSupportActionBar().setCustomView(view);
This is my code.here I added Sherlock bar library to my project.then, I used here for set my Title on header(Top). like this..
just try this like.. Set target SDK to Android 3.2(Version 14) or above..
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
getSupportActionBar().setCustomView(R.layout.header_sherlock_xmllayout);
header_tvleft = (TextView) findViewById(R.id.header_tvleft);
header_tvleft.setText("Back");
try this method....