How to create a Dynamic GridView - java

I create a Dynamic GridView with ArrayList Items and I want to create the Controls for shapes Some thing like this GridView GridView Example
and This Is my Code
This ArrayList
ArrayList<String> alphabets1;
alphabets1 = new ArrayList<String>();
alphabets1.add(rs.getString("Name"));
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, alphabets1);
and this is My Grid View
final GridView gridView = new GridView(this);
gridView.setVerticalSpacing(3);
gridView.setHorizontalSpacing(3);
gridView.setLayoutParams(new GridView.LayoutParams(WindowManager.LayoutParams.FILL_PARENT, WindowManager.LayoutParams.FILL_PARENT));
gridView.setNumColumns(4);
gridView.setAdapter(adapter);
gridView.setLayoutParams(linearLayoutParams);
this is my GridView enter image description here

GridView is used to display data in two dimension. In this tutorial we are going to show you how to implement custom GridView in Android with Images and Text.
Creating Layout:
The Main layout for our project is “activity_main” which has a GridView to display text with images.
activity_main.xml
<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"
tools:context=".MainActivity" >
<GridView
android:numColumns="auto_fit"
android:gravity="center"
android:columnWidth="100dp"
android:stretchMode="columnWidth"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/grid"
/>
</LinearLayout>
Next step is to create a layout for the grid item that is to be displayed in GridView. Create the layout as grid_single.xml which has a TextView to display the text which is stored in the Array and a ImageView to display set of images in each grid item.
grid_single.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="5dp" >
<ImageView
android:id="#+id/grid_image"
android:layout_width="50dp"
android:layout_height="50dp">
</ImageView>
<TextView
android:id="#+id/grid_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="15dp"
android:textSize="9sp" >
</TextView>
</LinearLayout>
Creating Activity:
Before Creating the MainActivity we must create a CustomGrid class for our custom GridView which is extended to BaseAdapter.
CustomGrid.java
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class CustomGrid extends BaseAdapter{
private Context mContext;
private final String[] web;
private final int[] Imageid;
public CustomGrid(Context c,String[] web,int[] Imageid ) {
mContext = c;
this.Imageid = Imageid;
this.web = web;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return web.length;
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View grid;
LayoutInflater inflater = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
grid = new View(mContext);
grid = inflater.inflate(R.layout.grid_single, null);
TextView textView = (TextView) grid.findViewById(R.id.grid_text);
ImageView imageView = (ImageView)grid.findViewById(R.id.grid_image);
textView.setText(web[position]);
imageView.setImageResource(Imageid[position]);
} else {
grid = (View) convertView;
}
return grid;
}
}
MainActivity.java
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.Toast;
public class MainActivity extends Activity {
GridView grid;
String[] web = {
"Google",
"Github",
"Instagram",
"Facebook",
"Flickr",
"Pinterest",
"Quora",
"Twitter",
"Vimeo",
"WordPress",
"Youtube",
"Stumbleupon",
"SoundCloud",
"Reddit",
"Blogger"
} ;
int[] imageId = {
R.drawable.image1,
R.drawable.image2,
R.drawable.image3,
R.drawable.image4,
R.drawable.image5,
R.drawable.image6,
R.drawable.image7,
R.drawable.image8,
R.drawable.image9,
R.drawable.image10,
R.drawable.image11,
R.drawable.image12,
R.drawable.image13,
R.drawable.image14,
R.drawable.image15
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
CustomGrid adapter = new CustomGrid(MainActivity.this, web, imageId);
grid=(GridView)findViewById(R.id.grid);
grid.setAdapter(adapter);
grid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(MainActivity.this, "You Clicked at " +web[+ position], Toast.LENGTH_SHORT).show();
}
});
}
}
reference link https://www.learn2crack.com/2014/01/android-custom-gridview.html

same as we create listview just use gridView instead of list view in xml

Related

How do I set variables to true/false from a Listview of Checkboxes?

I created a listview with a custom adapter that allows me to have a list of items with checkboxes next to each item.
So I would like to look at the checkbox for the corresponding item in the list and see if it is checked and if it is, then set the value of boolean whiskey = false to true and so on for the other booleans.
It is very possible I have code in the wrong class or xml file, I've been trying to piece together things I've found on the internet. I'm new to android studio so its proving very difficult. I do have about a years worth of java experience though. I have all my code written in a working program on Eclipse, I am just having a hell of a time figuring out how to implement it into a working app.
Thanks in advance.
customAdapter.java
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.TextView;
import java.util.ArrayList;
public class customAdapter extends BaseAdapter {
private ArrayList<String> list = new ArrayList<String>();
private Context context;
public customAdapter(ArrayList<String> list, Context context) {
this.list = list;
this.context = context;
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int pos) {
return list.get(pos);
}
public void setChecked(boolean isChecked){
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View view = convertView;
if (view == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.activity2_listview, null);
}
//Handle TextView and display string from your list
TextView label = (TextView)view.findViewById(R.id.label);
label.setText(list.get(position));
//Handle buttons and add onClickListeners
CheckBox callchkbox = (CheckBox) view.findViewById(R.id.cb);
callchkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
//update isChecked value to model class of list at current position
list.get(position).setChecked(isChecked);
}
});
return view;
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
Main2Activity.java
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.Arrays;
import android.widget.CheckBox;
public class Main2Activity extends AppCompatActivity {
boolean Whiskey, Bourbon, Rum, Gin, Vodka, Tequila = false;
String [] userIngredients = {"Whiskey", "Bourbon", "Rum", "Gin", "Vodka", "Tequila", "Club Soda", "Lemon-Lime Soda",
"Ginger ale", "Cola", "Still mineral water", "Tonic Water", "Orange Juice", "Cranberry Juice", "Grapefruit Juice",
"Tomato Juice", "Cream or Half and Half", "Milk", "Ginger Beer", "PineApple Juice", "Lemons", "Limes", "Oranges"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
ListView listView = (ListView) findViewById(R.id.userIngredients);
ArrayList<String> list = new ArrayList<String>(Arrays.asList(userIngredients));
listView.setAdapter(new customAdapter(list, Main2Activity.this));
}
}
activity_main2.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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=".Main2Activity"
android:id="#+id/linearLayout">
<ListView
android:layout_width="419dp"
android:layout_height="558dp"
android:id="#+id/userIngredients"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/textView2"
tools:layout_conversion_absoluteHeight="731dp"
tools:layout_conversion_absoluteWidth="411dp" />
<TextView
android:id="#+id/textView2"
android:layout_width="374dp"
android:layout_height="60dp"
android:layout_marginStart="8dp"
android:layout_marginLeft="8dp"
android:layout_marginTop="16dp"
android:layout_marginEnd="8dp"
android:layout_marginRight="8dp"
android:text="Check Your Ingredients"
android:textSize="24sp"
app:fontFamily="#font/cinzel"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
activity2_listview.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/label"
android:layout_width="323dp"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:text="ingredient"
android:textSize="20sp" />
<CheckBox
android:id="#+id/cb"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
i think you can do it with a BaseAdapter as well, but i suggest to use a RecyclerView instead.
I used support-v4 and recyclerview-v7 libs as following:
(Make sure that you are not developing AndroidX - check your gradle.properties of the entire project. It is very similar but uses other libraries though.)
build.gradle
android {
compileSdkVersion 28
buildToolsVersion '28.0.3'
...
dependencies {
implementation 'com.android.support:appcompat-v7:28.0.0'
implementation 'com.android.support:support-v4:28.0.0'
implementation 'com.android.support:design:28.0.0'
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
implementation 'com.android.support:recyclerview-v7:28.0.0'
...
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.widget.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">
<TextView
android:id="#+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Check Your Ingredients"
android:textAlignment="center" />
<android.support.v7.widget.RecyclerView
android:id="#+id/recycler_chooser"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:scrollbars="vertical"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" >
</android.support.v7.widget.RecyclerView>
</android.widget.RelativeLayout>
In the activity2_listview you might want to do more design to the xml. It looks very basic now.
activity2_listview.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/listviewtextlabel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:text="ingredient"
android:textSize="20sp" />
<CheckBox
android:id="#+id/listviewcheckbox"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
In the main class we implement a callback-listener for our custom onItemAction function. We pass the listener with adapter.setActionListener(this); and add the adapter to the RecyclerViewer.
MainActivity.java
public class MainActivity extends AppCompatActivity implements CustomAdapter.ItemActionListener {
boolean Whiskey, Bourbon, Rum, Gin, Vodka, Tequila = false;
String [] userIngredients = {"Whiskey", "Bourbon", "Rum", "Gin", "Vodka", "Tequila", "Club Soda", "Lemon-Lime Soda",
"Ginger ale", "Cola", "Still mineral water", "Tonic Water", "Orange Juice", "Cranberry Juice", "Grapefruit Juice",
"Tomato Juice", "Cream or Half and Half", "Milk", "Ginger Beer", "PineApple Juice", "Lemons", "Limes", "Oranges"};
CustomAdapter adapter;
RecyclerView.LayoutManager layoutManager;
RecyclerView recyclerListView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
recyclerListView = (RecyclerView) findViewById(R.id.recycler_chooser);
ArrayList<String> list = new ArrayList<>();
list.addAll(Arrays.asList(userIngredients));
// use this setting to improve performance if you know that changes
// in content do not change the layout size of the RecyclerView
recyclerListView.setHasFixedSize(false);
layoutManager = new LinearLayoutManager(this);
recyclerListView.setLayoutManager(layoutManager);
System.out.println("list.size() " + list.size());
adapter = new CustomAdapter(list,MainActivity.this);
adapter.setActionListener(this);
recyclerListView.setAdapter(adapter);
} catch (Exception e){
e.printStackTrace();
}
}
// callback listener for your items
#Override
public void onItemAction(View view, CustomAdapter.CustomActions customAction, int position) {
final String itemName = adapter.getItem(position);
System.out.println(customAction + ": You clicked " + itemName + " on row number " + position);
switch(itemName){
case "Whiskey":
if(customAction== CustomAdapter.CustomActions.CHECK){
Whiskey=true;
}
else{
Whiskey=false;
}
System.out.println("Whiskey set to: " + Whiskey);
break;
case "Bourbon":
if(customAction== CustomAdapter.CustomActions.CHECK){
Bourbon=true;
}
else{
Bourbon=false;
}
System.out.println("Bourbon set to: " + Bourbon);
break;
//case xyz
// and so on
default:
System.out.println("Not programmed yet: " + itemName);
}
}
}
As said above i removed the BaseAdapter and replaced it with the RecyclerView. We had to implement a custom ViewHolder-class that contains each row in our RecyclerViewList. Within the ViewHolder we can call the method on our listener whenever a checkbox-change event occurs.
CustomAdapter.java
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.TextView;
import java.util.ArrayList;
public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.CustomViewHolder> {
//------ helper class for the viewholder
enum CustomActions{
CHECK,UNCHECK
}
// Provide a reference to the views for each row
public class CustomViewHolder extends RecyclerView.ViewHolder {
// each data item is just a string in this case
public TextView mTextView;
public CheckBox mCheckBox;
public CustomViewHolder(View v) {
super(v);
// the view element v is the whole linear layout element
CheckBox.OnCheckedChangeListener checkboxListenerForOneEntry = new CheckBox.OnCheckedChangeListener(){
#Override
public void onCheckedChanged(CompoundButton view, boolean isChecked) {
if (mItemActionListener != null) {
if(isChecked){
// this compoundbutton view element will be the checkbox
mItemActionListener.onItemAction(view, CustomActions.CHECK, getAdapterPosition());
}else{
mItemActionListener.onItemAction(view, CustomActions.UNCHECK, getAdapterPosition());
}
}
}
};
mTextView = v.findViewById(R.id.listviewtextlabel);
mCheckBox = v.findViewById(R.id.listviewcheckbox);
mCheckBox.setOnCheckedChangeListener(checkboxListenerForOneEntry);
}
}
//------
private ArrayList<String> list;
private Context context;
private LayoutInflater mInflater;
private ItemActionListener mItemActionListener;
public CustomAdapter(ArrayList<String> list, Context context) {
this.list = list;
this.context = context;
this.mInflater = LayoutInflater.from(this.context);
}
// allows clicks events to be caught
void setActionListener(ItemActionListener itemActionListener) {
this.mItemActionListener = itemActionListener;
}
// parent activity will implement this method to respond to click events
public interface ItemActionListener {
void onItemAction(View view, CustomActions customAction, int position);
}
// Create new views (invoked by the layout manager)
#Override
public CustomViewHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
// create a new view
View v = mInflater.inflate(R.layout.activity2_listview, parent, false);
return new CustomViewHolder(v);
}
// Replace the contents of a view (invoked by the layout manager)
#Override
public void onBindViewHolder(CustomViewHolder holder, int position) {
// - get element from your dataset at this position
// - replace the contents of the view with that element
holder.mTextView.setText(list.get(position));
}
#Override // Return the size of your dataset (invoked by the layout manager)
public int getItemCount() {
return getCount();
}
public int getCount() {
return list.size();
}
public String getItem(int pos) {
return list.get(pos);
}
}
Feel free to use the code as you like.
For more info about the RecyclerView see the google docs: https://developer.android.com/guide/topics/ui/layout/recyclerview

How to change the image in the row clicked in recyclerview?

I have a recyclerview with each row containing an icon. When the image is clicked, I want the image to be gone, and a progress bar to appear. The way I'm doing it, the problem is, the image for all rows disappears, and a progressbar for all rows appear. Here's the relevant code:
#Override
public void onBindViewHolder(SubmissionViewHolder holder, int position) {
switch(value){
case 0:
holder.smoothProgressBar.setVisibility(View.VISIBLE);
holder.downloadIcon.setVisibility(View.GONE);
break;
case 4:
holder.smoothProgressBar.setVisibility(View.INVISIBLE);
holder.downloadIcon.setVisibility(View.VISIBLE);
break;
case 8:
holder.smoothProgressBar.setVisibility(View.GONE);
holder.downloadIcon.setVisibility(View.VISIBLE);
break;
default:
holder.smoothProgressBar.setVisibility(View.GONE);
holder.downloadIcon.setVisibility(View.VISIBLE);
}
}
public void setDownloadBar(int value, int position){
this.value = value;
notifyItemChanged(position);
}
Based on the following links you can build up your solution
https://gist.github.com/grantland/cd70814fe4ac369e3e92
Get clicked item and its position in RecyclerView
http://www.littlerobots.nl/blog/Handle-Android-RecyclerView-Clicks/
So basically you need to check if the certain item of the recyclerview is onclicked. If yes just flip the visibility of the progressbar and the image.
You have a recyclerview similar to this one, let's assume on the activity_main layout:
<android.support.v7.widget.RecyclerView
android:id="#+id/myRecyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
</android.support.v7.widget.RecyclerView>
in MainActivity's onCreate add:
MainAdapter mainAdapter = new MainAdapter(new String[] {"apple", "banana", "coconut"});
RecyclerView myRecyclerView = (RecyclerView) findViewById(R.id.myRecyclerView);
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
myRecyclerView.setLayoutManager(layoutManager);
myRecyclerView.setAdapter(mainAdapter);
create a row_recycler_list under the layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ProgressBar
android:id="#+id/myProgressBar"
android:layout_width="100dp"
android:layout_height="100dp"
android:visibility="gone"
/>
<ImageView
android:id="#+id/myImage"
android:src="#mipmap/ic_launcher"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TextView
android:id="#+id/myText"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
your viewholder implements the View.OnClickListener like this one:
package com.example.jana.recyclerimage;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
public class MainAdapter extends RecyclerView.Adapter<MainAdapter.ViewHolder> {
private String[] dataSet;
public MainAdapter(String[] dataSet) {
this.dataSet = dataSet;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater
.from(parent.getContext())
.inflate(R.layout.row_recycler_list, parent, false);
ViewHolder vh = new ViewHolder(v);
return vh;
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.textView.setText(dataSet[position]);
}
#Override
public int getItemCount() {
return dataSet.length;
}
public class ViewHolder
extends RecyclerView.ViewHolder
implements View.OnClickListener {
public TextView textView;
public ViewHolder(View itemView) {
super(itemView);
itemView.setOnClickListener(this);
this.textView = (TextView)itemView.findViewById(R.id.myText);
}
#Override
public void onClick(View v) {
ImageView imageView = (ImageView) v.findViewById(R.id.myImage);
ProgressBar progressBar = (ProgressBar) v.findViewById(R.id.myProgressBar);
imageView.setVisibility(View.GONE);
progressBar.setVisibility(View.VISIBLE);
}
}
}
and basically you're done. Of course you can extend and/or polish it according to your needs.

Show listView with custom list adapter inside Fragment

I am facing problem to show custom listView inside Fragment with Tabbed Activity.
Here is my java and xml files
Section2Fragment.java
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
/**
* A placeholder fragment containing a simple view.
*/
public class Section2Fragment extends Fragment {
public Section2Fragment() {
}
ListView list;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_section2, container, false);
Log.d(getFragmentManager().toString(), "Fragment Section 2");
final String[] itemname = {
"Safari",
"Camera",
"Global",
"FireFox",
"UC Browser",
"Android Folder",
"VLC Player",
"Cold War"
};
Integer[] imgid = {
R.drawable.ic_launcher,
R.drawable.ic_launcher,
R.drawable.ic_launcher,
R.drawable.ic_launcher,
R.drawable.ic_launcher,
R.drawable.ic_launcher,
R.drawable.ic_launcher,
R.drawable.ic_launcher,
};
CustomListAdapter adapter = new CustomListAdapter(getActivity(), itemname, imgid);
list = (ListView) view.findViewById(R.id.section2listView);
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
String Slecteditem = itemname[+position];
Toast.makeText(getActivity(), Slecteditem, Toast.LENGTH_SHORT).show();
}
});
return inflater.inflate(R.layout.fragment_section2, container, false);
}
}
CustomListAdapter.java
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;
public class CustomListAdapter extends ArrayAdapter<String> {
private final Activity context;
private final String[] itemname;
private final Integer[] imgid;
public CustomListAdapter(Activity context, String[] itemname, Integer[] imgid) {
super(context, R.layout.listview_item, itemname);
// TODO Auto-generated constructor stub
this.context = context;
this.itemname = itemname;
this.imgid = imgid;
}
public View getView(int position, View view, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View rowView = inflater.inflate(R.layout.listview_item, null, true);
TextView txtTitle = (TextView) rowView.findViewById(R.id.item);
ImageView imageView = (ImageView) rowView.findViewById(R.id.icon);
TextView extratxt = (TextView) rowView.findViewById(R.id.textView1);
txtTitle.setText(itemname[position]);
imageView.setImageResource(imgid[position]);
extratxt.setText("Description " + itemname[position]);
return rowView;
}
}
fragment_section2.xml
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:background="#ff8720"
android:id="#+id/section2container">
<ListView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/section2listView">
</ListView>
</LinearLayout>
</RelativeLayout>
listview_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#d7d7d7"
android:orientation="horizontal">
<ImageView
android:id="#+id/icon"
android:layout_width="60dp"
android:layout_height="60dp"
android:padding="5dp" />
<LinearLayout android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="#+id/item"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Medium Text"
android:textAppearance="?android:attr/textAppearanceMedium"
android:layout_marginLeft="10dp"
android:layout_marginTop="5dp"
android:padding="2dp"
android:textColor="#33CC33" />
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#2c7bff"
android:text="TextView"
android:layout_marginLeft="10dp"/>
</LinearLayout>
</LinearLayout>
My question is why the list items are not appearing on screen?
What should I have to do to solve the problem?
The problem is in your onCreateView. You inflate a layout using
View view = inflater.inflate(R.layout.fragment_section2, container, false);
get a reference to the listview and instead of returning this inflated layout you return a new inflated layout.
Replace your
return inflater.inflate(R.layout.fragment_section2, container, false);
with
return view;
in your onCreateView().

Android Custom ListView with ArrayList How do I open a second activity

I have this Custom ListView with ArrayList and I am trying to Open second Activity Using
the Icon Used is in the folder drawable
setOnItemClickListener(new OnItemClickListener() {}
but it force closes the app when I click on the ListItem
CbMain.java
package com.frostistudios.circuitbasicspro;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;
public class CbMain extends Activity {
String[] listItems = {"Menu One","Menu Two","Menu Three"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cb_main);
ListView lv = (ListView) findViewById(R.id.listView); //listview in xml file
List<ListViewItem> items = new ArrayList<CbMain.ListViewItem>();
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position,
long id) {
if(position == 0){
//call to custom method for opening activity
openItemOneActivity();
}
else if(position == 1){
openItemTwoActivity();
}
else if(position == 2){
openItemThreeActivity();
}
}
});
items.add(new ListViewItem()
{{
ThumbnailResource = R.drawable.ic_action_call;
Title = listItems[0];
SubTitle = "";
}});
items.add(new ListViewItem()
{{
ThumbnailResource = R.drawable.ic_action_call;
Title = listItems[1];
SubTitle = "";
}});
items.add(new ListViewItem()
{{
ThumbnailResource = R.drawable.ic_action_call;
Title = listItems[2];
SubTitle = "";
}});
CustomListViewAdapter adapter = new CustomListViewAdapter(this, items);
lv.setAdapter(adapter);
}
//custom methods to open another activity
public void openItemOneActivity(){
Intent intent = new Intent(this,ItemOneActivity.class);
startActivity(intent);
}
public void openItemTwoActivity(){
Intent intent = new Intent(this,ItemTwoActivity.class);
startActivity(intent);
}
public void openItemThreeActivity(){
Intent intent = new Intent(this,ItemThreeActivity.class);
startActivity(intent);
}
class ListViewItem {
public int ThumbnailResource;
public String Title;
public String SubTitle;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// TODO Auto-generated method stub
//getMenuInflater().inflate(R.menu.actionbar, menu);
//return super.onCreateOptionsMenu(menu);
return true;
}
}
CustomListViewAdapter.java
this is the custom list adapter file
package com.frostistudios.circuitbasicspro;
import java.util.List;
import com.frostistudios.circuitbasicspro.CbMain.ListViewItem;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
public class CustomListViewAdapter extends BaseAdapter
{
LayoutInflater inflater;
List<ListViewItem> items;
public CustomListViewAdapter(Activity context, List<ListViewItem> items) {
super();
this.items = items;
this.inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return items.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ListViewItem item = items.get(position);
View vi=convertView;
if(convertView==null)
vi = inflater.inflate(R.layout.item_row, null);
ImageView imgThumbnail = (ImageView) vi.findViewById(R.id.imgThumbnail);
TextView txtTitle = (TextView) vi.findViewById(R.id.txtTitle);
TextView txtSubtitle = (TextView) vi.findViewById(R.id.txtSubTitle);
imgThumbnail.setImageResource(item.ThumbnailResource);
txtTitle.setText(item.Title);
txtSubtitle.setText(item.SubTitle);
return vi;
}
}
and this is the XML File that holds the ListView Design
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
<ImageView
android:id="#+id/imgThumbnail"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:src="#drawable/ic_action_call"
android:layout_marginLeft="10dp"
android:layout_marginTop="2dp"/>
<TextView
android:id="#+id/txtTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/imageView1"
android:layout_toRightOf="#+id/imageView1"
android:text="Large Text"
android:layout_marginLeft="60dp"
android:layout_marginTop="6dp"/>
<TextView
android:id="#+id/txtSubTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/imageView1"
android:layout_alignLeft="#+id/textView1"
android:layout_below="#+id/textView1"
android:text="" />
<ImageView
android:id="#+id/imageView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_below="#+id/textView1"
android:src="#drawable/arrow" />
</RelativeLayout>
Looking from your log cat, the error seems because the theme you used is not from the compat. Check your manifest, and make sure you use the compat theme.
Example (for ALL acitivities in your apps) :
<application
//other code
android:theme="#style/Theme.AppCompat.Light" >
Or if you only use the action bar on particular activity :
<Activity
//other code
android:theme="#style/Theme.AppCompat.Light" >
TIPS :
Always pay attention to the log cat, especially the caused by. I know the problem from there.
It would help a lot if you posted the error output. Are your other Activities declared in your manifest? You already have a context in the adapter, so you could set it there and try. I also think that View vi is unecessary, you can use convertView.

get edittext value which present outside the listview, get edittext value inside OnItemClick

I am new to android apps development,
I want to get edittext value which present outside the listview, and I want to get value inside OnItemClick. when user enter text and click list item I need to get both list item selected and edittext text value.
I Created main layout containing one edittext and listview. I want to get edittext value in listview OnItemClick event.
I tried I can't get it. Please guide me.
Here I list out my sample program.
MainActivity.java
import java.util.ArrayList;
import android.app.Activity;
import android.os.Bundle;
import android.widget.EditText;
import android.widget.ListView;
public class MainActivity extends Activity {
ArrayList<String> listVal = new ArrayList<String>();
public EditText searchKey;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
searchKey = (EditText) findViewById(R.id.searchKey);
ListView spinner = (ListView) findViewById(R.id.listView1);
listVal.add("Apple");
listVal.add("Avocado");
listVal.add("Banana");
listVal.add("Blueberry");
listVal.add("Coconut");
listVal.add("Durian");
listVal.add("Guava");
listVal.add("Kiwifruit");
listVal.add("Jackfruit");
ListAdapter listAdapter = new ListAdapter(getApplicationContext(), R.layout.list, listVal);
spinner.setAdapter(listAdapter);
spinner.setOnItemClickListener(listAdapter);
}
}
ListAdapter.java
import java.util.ArrayList;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import android.widget.Toast;
public class ListAdapter extends ArrayAdapter<String> implements OnItemClickListener {
private final Context context;
private final ArrayList<String> values;
int layoutResourceId;
public ListAdapter(Context context, int layoutResourceId, ArrayList<String> values) {
super(context, layoutResourceId, values);
this.context = context;
this.layoutResourceId = layoutResourceId;
this.values = values;
}
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(layoutResourceId, parent, false);
TextView textView = (TextView) rowView.findViewById(R.id.listItem);
textView.setText(values.get(position));
return rowView;
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
TextView message = (TextView)arg1.findViewById(R.id.listItem);
Toast.makeText(context, message.getText().toString(), Toast.LENGTH_SHORT).show();
}
}
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:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<EditText
android:id="#+id/searchKey"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="text"
android:ems="10" >
<requestFocus />
</EditText>
<ListView
android:id="#+id/listView1"
android:layout_below="#+id/searchKey"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true" >
</ListView>
</RelativeLayout>
list.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/listItem"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="15dip"
android:textColor="#000000" />
</LinearLayout>
you can use this also, it may help some others..
spinner.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> arg0, View v, int pos,
long id) {
// TODO Auto-generated method stub
int p = values.get(pos);
String key = searchKey.getText().toString().trim();
Log.v("listitem_value",p);
Log.v("EditTextValue",key);
Toast.makeText(context, "listitem_value:"+p+"\nEditTextValue:"+key, Toast.LENGTH_SHORT).show();
}
});
Try this..
public class MainActivity extends Activity {
ArrayList<String> listVal = new ArrayList<String>();
public EditText searchKey;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
searchKey = (EditText) findViewById(R.id.searchKey);
ListView spinner = (ListView) findViewById(R.id.listView1);
listVal.add("Apple");
listVal.add("Avocado");
listVal.add("Banana");
listVal.add("Blueberry");
listVal.add("Coconut");
listVal.add("Durian");
listVal.add("Guava");
listVal.add("Kiwifruit");
listVal.add("Jackfruit");
ListAdapter listAdapter = new ListAdapter(getApplicationContext(), R.layout.list, listVal);
spinner.setAdapter(listAdapter);
spinner.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> arg0, View v, int pos,
long id) {
// TODO Auto-generated method stub
Log.v("listitem_value",values.get(pos));
Log.v("EditTextValue",searchKey.getText().toString().trim());
Toast.makeText(context, "listitem_value:"+values.get(pos)+"\nEditTextValue:"+searchKey.getText().toString().trim(), Toast.LENGTH_SHORT).show();
}
});
}
}
and also remove implements OnItemClickListener and onItemClick method in ListAdapter
spinner.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> arg0, View v, int pos,
long id) {
// TODO Auto-generated method stub
TextView message = (TextView)arg1.findViewById(R.id.listItem);
Toast.makeText(context, message.getText().toString(), Toast.LENGTH_SHORT).show();
Log.v("EditText",searchKey.getText().toString().trim());
}
});

Categories

Resources