I'm trying to make it so when the user taps an image, a Toast pops up with the relevant name. I think I need to do this with a switch statement since I have an array, but am unsure if that's actually the correct way.
Here's my code:
public class MainActivity extends AppCompatActivity {
Integer[] Family = {R.drawable.angelica, R.drawable.dad, R.drawable.enzoandbully, R.drawable.enzokathyalex, R.drawable.ernesto, R.drawable.gale, R.drawable.joel, R.drawable.lorenzo};
ImageView pic;
Integer member;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
GridView grid = (GridView) findViewById(R.id.gridView);
final ImageView pic = (ImageView) findViewById(R.id.imgFamily);
grid.setAdapter(new ImageAdapter(this));
grid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getBaseContext(), " " + (position + 1), Toast.LENGTH_SHORT).show( );
pic.setImageResource(Family[position]);
}
});
}
public class ImageAdapter extends BaseAdapter {
private Context context;
public ImageAdapter(Context c) {
context = c;
}
#Override
public int getCount() {
return Family.length;
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
pic = new ImageView(context);
pic.setImageResource(Family[position]);
pic.setScaleType(ImageView.ScaleType.FIT_XY);
pic.setLayoutParams(new GridView.LayoutParams(330,300));
return pic;
}
}
}
Edit: Forgot XML Code:
<GridLayout 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:paddingLeft="16dp"
android:paddingRight="16dp"
android:paddingTop="16dp"
android:paddingBottom="16dp" tools:context=".MainActivity">
<GridView
android:layout_width="wrap_content"
android:layout_height="300dp"
android:id="#+id/gridView"
android:numColumns="2"
android:columnWidth="160dp"
android:horizontalSpacing="10dp"
android:verticalSpacing="10dp"
android:gravity="center" />
<ImageView
android:id="#+id/imgFamily"
android:layout_width="128dp"
android:layout_height="128dp"
android:layout_gravity="center_horizontal"
android:contentDescription="#string/imgFamily"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_row="12"
android:layout_column="0" />
</GridLayout>
Hope this should work.
Create a model class that will hold the name and image of the family member like this one -
public class FamilyMember {
private String name;
private int imageResource;
public FamilyMember(String name, int imageResource) {
this.name = name;
this.imageResource = imageResource;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getImageResource() {
return imageResource;
}
public void setImageResource(int imageResource) {
this.imageResource = imageResource;
}
}
And your activity should like this one -
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.Toast;
// please use the correct R
import com.sample.R;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends Activity {
List<FamilyMember> members = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
members = getFamilyMember();
setContentView(R.layout.activity_main);
GridView grid = (GridView) findViewById(R.id.gridView);
final ImageView pic = (ImageView) findViewById(R.id.imgFamily);
grid.setAdapter(new ImageAdapter(this));
grid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
FamilyMember member = members.get(position);
Toast.makeText(MainActivity.this, member.getName(), Toast.LENGTH_SHORT).show( );
pic.setImageResource(member.getImageResource());
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public class ImageAdapter extends BaseAdapter {
private Context context;
public ImageAdapter(Context c) {
context = c;
}
#Override
public int getCount() {
return members.size();
}
#Override
public Object getItem(int position) {
return members.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
FamilyMember member = (FamilyMember) getItem(position);
pic = new ImageView(context);
pic.setImageResource(member.getImageResource());
pic.setScaleType(ImageView.ScaleType.FIT_XY);
pic.setLayoutParams(new GridView.LayoutParams(330,300));
return pic;
}
}
private List<FamilyMember> getFamilyMember() {
List<FamilyMember> members = new ArrayList<>();
members.add(new FamilyMember("Angelica", R.drawable.R.drawable.angelica));
members.add(new FamilyMember("Dad", R.drawable.R.drawable.dad));
// like the above add the family members here
return members;
}
}
int id = item.getItemId();
switch (item.getItemId()) {
case R.id.action_add_faculty:
// EITHER CALL THE METHOD HERE OR DO THE FUNCTION DIRECTLY
Toast.makeText(Cureent.this,"You clicked yes button",Toast.LENGTH_LONG).show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
Change according to your requirement .hope it will work.
Do it this way:
public class MainActivity extends AppCompatActivity {
int[] Family = {R.drawable.angelica, R.drawable.dad, R.drawable.enzoandbully, R.drawable.enzokathyalex, R.drawable.ernesto, R.drawable.gale, R.drawable.joel, R.drawable.lorenzo};
ImageView pic;
int member;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
GridView grid = (GridView) findViewById(R.id.gridView);
final ImageView pic = (ImageView) findViewById(R.id.imgFamily);
grid.setAdapter(new ImageAdapter(this));
grid.setOnItemClickListener(this);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
int iden = view.getId();
switch(iden) {
case R.id.gridView:
Toast.makeText(MainActivity.this, String.valueOf(position + 1), Toast.LENGTH_SHORT).show();
pic.setImageResource(Family[position]);
break;
default:
break;
}
}
public class ImageAdapter extends BaseAdapter {
private Context context;
public ImageAdapter(Context c) {
context = c;
}
#Override
public int getCount() {
return Family.length;
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
pic = new ImageView(context);
pic.setImageResource(Family[position]);
pic.setScaleType(ImageView.ScaleType.FIT_XY);
pic.setLayoutParams(new GridView.LayoutParams(330,300));
return pic;
}
}
}
Hope this helps. Please comment if you have any questions.
Related
I'm trying to create an ExpandibleListView with intents that switch to new classes. When using only one switch, there is no problem, but when I want different parents to switch diffent classes, only one of them works, the other one stays like empty (Its arrows turn up and down but nothing happens). How can I make them work together?
Here is my codes:
ExpandibleListAdapter.java
import android.graphics.Typeface;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import java.util.HashMap;
import java.util.List;
import android.content.Context;
import android.widget.TextView;
public class ExpandableListAdapter extends BaseExpandableListAdapter {
private Context context;
private List<String> listDataHeader;
private HashMap<String,List<String>> listHashMap;
public ExpandableListAdapter(Context context, List<String> listDataHeader, HashMap<String, List<String>> listHashMap) {
this.context = context;
this.listDataHeader = listDataHeader;
this.listHashMap = listHashMap;
}
#Override
public int getGroupCount() {
return listDataHeader.size();
}
#Override
public int getChildrenCount(int i) {
return listHashMap.get(listDataHeader.get(i)).size();
}
#Override
public Object getGroup(int i) {
return listDataHeader.get(i);
}
#Override
public Object getChild(int i, int i1) {
return listHashMap.get(listDataHeader.get(i)).get(i1); // i = group item , i1= ChildItem
}
#Override
public long getGroupId(int i) {
return i;
}
#Override
public long getChildId(int i, int i1) {
return i1;
}
#Override
public boolean hasStableIds() {
return false;
}
#Override
public View getGroupView(int i, boolean b, View view, ViewGroup ViewGroup) {
String headerTitle = (String)getGroup(i);
if(view == null)
{
LayoutInflater inflater = (LayoutInflater)this.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.list_group,null);
}
TextView lblListHeader = (TextView)view.findViewById(R.id.lblListHeader);
lblListHeader.setTypeface(null, Typeface.BOLD);
lblListHeader.setText(headerTitle);
return view;
}
#Override
public View getChildView(int i, int i1, boolean b, View view, ViewGroup ViewGroup) {
final String childText = (String)getChild(i,i1);
if(view == null)
{
LayoutInflater inflater = (LayoutInflater)this.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.list_item,null);
}
TextView txtListChild = (TextView)view.findViewById(R.id.lblListItem);
txtListChild.setText(childText);
return view;
}
#Override
public boolean isChildSelectable(int i, int i1) {
return true;
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity
{
private ExpandableListView listView;
private ExpandableListAdapter listAdapter;
private List<String> listDataHeader;
private HashMap<String,List<String>> listHash;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ExpandableListView)findViewById(R.id.lvExp);
initData();
listAdapter = new ExpandableListAdapter(this,listDataHeader,listHash);
listView.setAdapter(listAdapter);
}
private void initData() {
listDataHeader = new ArrayList<>();
listHash = new HashMap<>();
listDataHeader.add("Line One");
listDataHeader.add("Line Two");
List<String> genel = new ArrayList<>();
**//The problem starts here**
listView.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
#Override
public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) {
final String selected = (String) listAdapter.getGroup(groupPosition);
Intent intent;
switch (selected) {
case "Line One":
intent = new Intent(MainActivity.this,LineOne.class);
startActivity(intent);
break;
}
return false; //return true doesn't let the other parents to open.
}
});
List<String> terims = new ArrayList<>();
listView.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
#Override
public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) {
final String terims = (String) listAdapter.getGroup(groupPosition);
Intent niyet;//I used "intent" instead of "niyet" as same above but nothing has changed.
switch (terims) {
case "Line Two":
niyet = new Intent(MainActivity.this, LineTwo.class);
startActivity(niyet);
break;
}
return false;
}
});
listHash.put(listDataHeader.get(0),genel);
listHash.put(listDataHeader.get(1),terims);
}
}
You cannot set 2 OnGroupClickListeners. The second one cancels the first one. You should set one listener and then check for both sets of conditions in the one listener.
I have one table in SQLite database which has two fields one is "b" and another is "n" "b" represent book number and "n" represent book names I am successfully fetching all "n" field in my list view now I want when any user click particular list item show book b number which in my database, for example, I have book n=Genesis when anyone click on Genesis it show book number like b=1;
here my code an database structure
*/
public class Bookname extends Fragment {
private ListView listView;
private ArrayList<String> stringArrayList;
private ArrayAdapter<String> adapter;
private DatabaseHelper mDBHelper;
private SQLiteDatabase mDb;
boolean book;
public Bookname() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_bookname, container, false);
setData();
listView = view.findViewById(R.id.list);
adapter = new ListViewAdapter((MainActivity) getContext(), R.layout.item_listview, stringArrayList);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
}
});
return view;
}
private void setData() {
stringArrayList = new ArrayList<>();
mDBHelper = new DatabaseHelper(getContext());
mDb = mDBHelper.getReadableDatabase();
Cursor cursor = mDb.rawQuery("SELECT b, n FROM key_english;", new String[]{});
if (cursor.getCount() == 0) {
Toast.makeText(getContext(), "NO DATA FOUND", Toast.LENGTH_SHORT).show();
} else {
while (cursor.moveToNext()) {
stringArrayList.add(cursor.getString(1));
}
}
}
}
Myadopter class
package bible.swordof.God;
import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.amulyakhare.textdrawable.TextDrawable;
import com.amulyakhare.textdrawable.util.ColorGenerator;
import java.util.List;
public class ListViewAdapter extends ArrayAdapter<String> {
private MainActivity activity;
private List<String> friendList;
public ListViewAdapter(MainActivity context, int resource, List<String> objects) {
super(context, resource, objects);
this.activity = context;
this.friendList = objects;
}
#Override
public int getCount() {
return friendList.size();
}
#Override
public String getItem(int position) {
return friendList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
LayoutInflater inflater = (LayoutInflater) activity.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
// If holder not exist then locate all view from UI file.
if (convertView == null) {
// inflate UI from XML file
convertView = inflater.inflate(R.layout.item_listview, parent, false);
// get all UI view
holder = new ViewHolder(convertView);
// set tag for holder
convertView.setTag(holder);
} else {
// if holder created, get tag from view
holder = (ViewHolder) convertView.getTag();
}
holder.friendName.setText(getItem(position));
//get first letter of each String item
String firstLetter = String.valueOf(getItem(position).charAt(0));
ColorGenerator generator = ColorGenerator.MATERIAL; // or use DEFAULT
// generate random color
int color = generator.getColor(getItem(position));
TextDrawable drawable = TextDrawable.builder()
.buildRound(firstLetter, color); // radius in px
holder.imageView.setImageDrawable(drawable);
return convertView;
}
private class ViewHolder {
private ImageView imageView;
private TextView friendName;
public ViewHolder(View v) {
imageView = (ImageView) v.findViewById(R.id.image_view);
friendName = (TextView) v.findViewById(R.id.text);
}
}
}
[My database structure][1]
[1]: https://i.stack.imgur.com/7aXut.png
Create model
Like:
public class BookData {
private String bookNo;
private String bookName;
BookData(String bookNo, String bookName){
this.bookNo = bookNo;
this.bookName = bookName;
}
public String getBookNo() {
return bookNo;
}
public void setBookNo(String bookNo) {
this.bookNo = bookNo;
}
public String getBookName() {
return bookName;
}
public void setBookName(String bookName) {
this.bookName = bookName;
} }
Create ArrayList object like:
ArrayList<BookData> stringArrayList = new ArrayList<>();
Store your data in model
stringArrayList.add(new BookData(cursor.getString(0),cursor.getString(1)));
And retrieve data using:
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String bookNo = stringArrayList.get(position).getBookNo();
Log.e("BookNo : ", bookNo);
}
});
I'm currently developing an App where I want to use a bottom Navigation with multiple dynamically created Fragments.
Therefore I set up a test app to get used to these funtions.
The problem is now, if I create the ListFragment by a static XML the ListView is created correctly, but If I create it dynamically the ListView does not get displayed, only the BottomNavigation is displayed, nothing else.
Main Activity:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addFragment();
}
private void addFragment() {
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
MyListFragment myListFragment = new MyListFragment();
fragmentTransaction.add(R.id.fragmentContainer, myListFragment);
fragmentTransaction.commit();
}
}
Layout:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/fragmentContainer"
android:layout_margin="5dp"
android:layout_alignTop="#+id/bottom_nav"/>
<android.support.design.widget.BottomNavigationView
android:layout_width="match_parent"
android:layout_height="48dp"
android:id="#+id/bottom_nav"
app:menu="#menu/menu_bottom_nav"
android:background="#808080"
android:layout_alignParentBottom="true"/>
</RelativeLayout>
ListFragment:
public class MyListFragment extends ListFragment implements AdapterView.OnItemClickListener {
CustomerAdapter customerAdapter;
ListView listView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
Customer customer = new Customer("Testcustomer","123456", "654321");
customerAdapter = new CustomerAdapter(Objects.requireNonNull(getActivity()),R.layout.list_pack_item);
listView = new ListView(getActivity());
listView.setAdapter(customerAdapter);
customerAdapter.add(customer);
listView.setOnItemClickListener(this);
return listView;
}
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
//do stuff
}
}
CustomerAdapter:
public class CustomerAdapter extends ArrayAdapter {
List list = new ArrayList();
public CustomerAdapter(#NonNull Context context, int resource ) {
super(context, resource);
}
public void add( #Nullable Customer object ) {
super.add(object);
list.add(object);
}
#Override
public int getCount() {
return list.size();
}
#Nullable
#Override
public Object getItem(int position ) {
return list.get(position);
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent ) {
View row;
row = convertView;
CustomerHolder customerHolder;
if (row == null) {
LayoutInflater layoutInflater = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = layoutInflater.inflate(R.layout.list_pack_item, parent, false);
customerHolder = new CustomerHolder();
customerHolder.tx_name = row.findViewById(R.id.tx_name);
customerHolder.tx_intern = row.findViewById(R.id.tx_intern);
customerHolder.tx_extern = row.findViewById(R.id.tx_extern);
row.setTag(customerHolder);
} else {
customerHolder = (CustomerHolder) row.getTag();
}
Customer customer = (Customer) this.getItem(position);
customerHolder.tx_name.setText(customer.getName());
customerHolder.tx_intern.setText("Internal Number: " + customer.getMyCustomerNumber());
customerHolder.tx_extern.setText("Supplier Number: " + customer.getSupplierNumber());
return row;
}
static class CustomerHolder {
TextView tx_name, tx_intern, tx_extern;
}
}
Customer Class
public class Customer {
private String name;
private String supplierNumber;
private String myCustomerNumber;
public Customer(String name, String supplierNumber, String myCustomerNumber) {
this.name = name;
this.supplierNumber = supplierNumber;
this.myCustomerNumber = myCustomerNumber;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSupplierNumber() {
return supplierNumber;
}
public void setSupplierNumber(String supplierNumber) {
this.supplierNumber = supplierNumber;
}
public String getMyCustomerNumber() {
return myCustomerNumber;
}
public void setMyCustomerNumber(String myCustomerNumber) {
this.myCustomerNumber = myCustomerNumber;
}
}
If there is any further information or code needed please let me know!
Additionally: I need to create the fragments dynamically in order to replace them, am I correct?
im really newbie android.
Now i try to create a simple custom listview with Header section.
But after i run my program, the listview item isn't clickable.
Here is my code :
MainActivity.java
package io.hidayat.headerlistview;
import android.app.Activity;
import android.os.Bundle;
import android.widget.ListView;
public class MainActivity extends Activity {
private CustomAdapter mAdapter;
ListView listView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView)findViewById(R.id.list_header_detail);
mAdapter = new CustomAdapter(this);
mAdapter.addSectionHeaderItem("Section #1");
for (int i = 1; i < 30; i++) {
mAdapter.addItem("Row Item #" + i);
if (i % 4 == 0) {
mAdapter.addSectionHeaderItem("Section #" + i);
}
}
listView.setAdapter(mAdapter);
}
}
CustomAdapter.java
package io.hidayat.headerlistview;
import java.util.ArrayList;
import java.util.TreeSet;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
class CustomAdapter extends BaseAdapter {
private static final int TYPE_ITEM = 0;
private static final int TYPE_SEPARATOR = 1;
private ArrayList<String> mData = new ArrayList<String>();
private TreeSet<Integer> sectionHeader = new TreeSet<Integer>();
private LayoutInflater mInflater;
public CustomAdapter(Context context) {
mInflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public void addItem(final String item) {
mData.add(item);
notifyDataSetChanged();
}
public void addSectionHeaderItem(final String item) {
mData.add(item);
sectionHeader.add(mData.size() - 1);
notifyDataSetChanged();
}
#Override
public int getItemViewType(int position) {
return sectionHeader.contains(position) ? TYPE_SEPARATOR : TYPE_ITEM;
}
#Override
public int getViewTypeCount() {
return 2;
}
#Override
public int getCount() {
return mData.size();
}
#Override
public String getItem(int position) {
return mData.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
int rowType = getItemViewType(position);
if (convertView == null) {
holder = new ViewHolder();
switch (rowType) {
case TYPE_ITEM:
convertView = mInflater.inflate(R.layout.row, parent, false);
holder.textView = (TextView) convertView.findViewById(R.id.text);
break;
case TYPE_SEPARATOR:
convertView = mInflater.inflate(R.layout.header, parent, false);
holder.textView = (TextView) convertView.findViewById(R.id.textSeparator);
break;
}
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.textView.setText(mData.get(position));
return convertView;
}
public static class ViewHolder {
public TextView textView;
}
}
Header and Row XML is simillar.
<?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="wrap_content"
android:gravity="center_vertical"
android:descendantFocusability="blocksDescendants" >
<TextView
android:id="#+id/text"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#FFF"
android:gravity="center_vertical"
android:padding="5dp"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#FF000000" />
</LinearLayout>
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<ListView
android:id="#+id/list_header_detail"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="16dip"
android:paddingBottom="16dip"
android:clipToPadding="false"
android:divider="#null"/>
</LinearLayout>
I'm sory, but here the screenshoot of my aplication : screenshoot
You have not applied the OnItemClickListener. Thats the problem. No worries. You can see the example below to change your code as required.
First implement your Class with OnItemClickListener like
public class MainActivity extends Activity implements OnItemClickListener
Then attach the OnItemClickListener to your list
listView.setOnItemClickListener(YourClassName.this);
Then override the onItemClick method to implement your functionality at the position being clicked.
#Override
public void onItemClick(AdapterView<?> adapter, View arg1, int position, long arg3) {
// TODO Auto-generated method stub
String item = adapter.getItemAtPosition(position).toString();
Toast.makeText(Test.this, "CLICK: " + item, Toast.LENGTH_SHORT).show();
}
Please let me know, if you face any trouble. Thanks.
invoke the below method on your listview
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(MainActivity.this, "clicked", Toast.LENGTH_SHORT).show();
}
});
The row item must have a param like android:descendantFocusability="blocksDescendants". use this for your row item parent .. It works perfectly for a listview that has CustomAdapter..
I have problems with implementation of my custom PagerAdapter and using it with a ViewPager.
This sample PagerAdapter has 10 items, every item is a button with it's index as text.
When I run my program, I see a button with text '1' insted of '0'. And when I swipe to other items I get only blank views. When I swipe backwards sometimes I see a button with some number, but it disappears (maybe it is destroying and I remove it from the container), and sometimes I see a button with a number, but the number changes after the swipe (I think I create a new Button and I add it to the container, and for some reasons the viewpager shows this new button).
How can I fix this implementation? I haven't seen difference in examples.
My PagerAdapter implementation:
public class MyPagerAdapter extends PagerAdapter {
#Override
public int getCount() {
return 10;
}
#Override
public boolean isViewFromObject(View view, Object o) {
return o.getClass()==view.getClass();
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
Button button = new Button(container.getContext());
ViewGroup.LayoutParams params = new ActionBar.LayoutParams(-1,-1);
button.setLayoutParams(params);
button.setText(String.valueOf(position));
container.addView(button);
return button;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((Button)object);
}
}
And my Activity:
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ViewPager pager = (ViewPager) findViewById(R.id.pager);
pager.setAdapter(new MyPagerAdapter());
}
}
Here is complete code:
xml layout:
<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:orientation="vertical"
tools:context="com.example.androidviewpagerapp.MainActivity" >
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
MyPagerAdapter class:
import android.support.v4.view.PagerAdapter;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;
public class MyPagerAdapter extends PagerAdapter {
#Override
public int getCount() {
return 10;
}
#Override
public boolean isViewFromObject(View view, Object o) {
return o==view;
}
#Override
public Object instantiateItem(final ViewGroup container, int position) {
Button button = new Button(container.getContext());
ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
button.setLayoutParams(params);
button.setText(String.valueOf(position));
final int page = position;
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(container.getContext(), "You clicked: " + page + ". page.", Toast.LENGTH_SHORT).show();
}
});
container.addView(button);
return button;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((Button)object);
}
}
MainActivity:
import android.support.v4.view.ViewPager;
import android.app.Activity;
import android.os.Bundle;
public class MainActivity extends Activity {
ViewPager viewPager;
MyPagerAdapter myPagerAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewPager = (ViewPager)findViewById(R.id.pager);
myPagerAdapter = new MyPagerAdapter();
viewPager.setAdapter(myPagerAdapter);
}
}
You will see that Buttons are full screen. To avoid that you need to create some layout (like LinearLayout) and add button to that layout.
Example:
import android.support.v4.view.PagerAdapter;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.Toast;
public class MyPagerAdapter extends PagerAdapter {
#Override
public int getCount() {
return 10;
}
#Override
public boolean isViewFromObject(View view, Object o) {
return o==view;
}
#Override
public Object instantiateItem(final ViewGroup container, int position) {
Button button = new Button(container.getContext());
ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
button.setLayoutParams(params);
button.setText(String.valueOf(position));
LinearLayout layout = new LinearLayout(container.getContext());
layout.setOrientation(LinearLayout.VERTICAL);
ViewGroup.LayoutParams layoutParams = new ViewGroup.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
//add buton to layout
layout.addView(button);
final int page = position;
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(container.getContext(), "You clicked: " + page + ". page.", Toast.LENGTH_SHORT).show();
}
});
//to container add layout instead of button
container.addView(layout);
//return layout instead of button
return layout;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
//cast to LinearLayout
container.removeView((LinearLayout)object);
}
}
if you want to inflate views in pager you must have to implement two methods.
instantiateItem and destroyItem
public class DialogPagerAdapter extends PagerAdapter {
private Context mContext;
//view inflating..
#Override
public Object instantiateItem(ViewGroup collection, int position) {
LayoutInflater inflater = LayoutInflater.from(mContext);
ViewGroup layout = (ViewGroup) inflater.inflate(R.layout.account_dialog_signin_viewpagers,
collection, false);
TextView tvLabel = (TextView) layout.findViewById(R.id.textView);
switch (position) {
case 0:
tvLabel.setText("Log In");
tvLabel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
break;
case 1:
tvLabel.setText("Sign Up");
tvLabel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
break;
case 2:
tvLabel.setText("Send Reset Link");
tvLabel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//onOptionClickForgot.OnOptionClick();
}
});
break;
}
collection.addView(layout);
return layout;
}
#Override
public void destroyItem(ViewGroup collection, int position, Object view) {
collection.removeView((View) view);
}
#Override
public int getCount() {
return 3;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
}
Simply call it like
viewPager.setAdapter(new DialogPagerAdapter);
xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="#dimen/dialog_button_height"
android:paddingLeft="#dimen/dimen_2"
android:paddingRight="#dimen/dimen_2"
android:minHeight="#dimen/dialog_button_height">
<TextView
android:id="#+id/textView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_centerInParent="true"
android:gravity="center"
android:text="#string/app_name"
android:textColor="#color/white"
android:textSize="#dimen/text_size_medium" />
</RelativeLayout>
Here i post ViewPagerAdapter that attached between TabLayout to ViewPager
public class ViewPagerAdapter extends FragmentPagerAdapter {
ArrayList<String> titleList = new ArrayList<>();
List<Fragment> fragment = new ArrayList<>();
public void addFragment(String title, Fragment fragment) {
this.titleList.add(title);
this.fragment.add(fragment);
}
public ViewPagerAdapter(FragmentManager fm) {
super(fm);
}
#NonNull
#Override
public Fragment getItem(int position) {
return fragment.get(position);
}
#Override
public int getCount() {
return titleList.size();
}
public CharSequence getPageTitle(int position) {
return titleList.get(position);
}
}
How to use ViewPagerAdapter.
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment("TAB 1", new YOUR_FRAGMENT1());
adapter.addFragment("TAB 2", new YOUR_FRAGMENT2());
// Keep adding fragments.
viewPager.setAdapter(adapter);
tabLayout.setupWithViewPager(viewPager);