I have a gridview with 8 buttons, 2 rows and 4 columns. I am trying to delete a button or even a row..a row might be better..I want this deletion to take place when I click on a button..any button. I am having trouble with this. I will show you code so far:
Mainactivity:
public class MainActivity extends Activity {
private TextView text;
private GridView gridView;
private TextView timerValue;
private Boolean firstclick = false;
private long startTime = 0L;
private Handler customHandler = new Handler();
private Button buttonclicked;
Random r = new Random();
//private int[] rannumbers_array = new int[32];
private int[] shuffle_array = new int[4];
private String[] items = new String[8];
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text = (TextView) findViewById(R.id.feedback);
timerValue = (TextView) findViewById(R.id.timerValue);
timerValue.setTextColor(Color.GREEN);
int j = 0;
int k = 0;
int ranval = 0;
for(int i = 0; i < 8; i++)
{
if ( (i % 4) == 0)
{
for(int x = 0; x < 4; x++)
{
shuffle_array[x] = 0;
}
do {
ranval = r.nextInt(100);
} while((ranval % 2) != 0);
}
else
{
do {
ranval = r.nextInt(100);
} while((ranval % 2) == 0);
}
shuffle_array[j] = ranval;
j++;
if(j >= 4)
{
j = 0;
shuffle(shuffle_array);
do {
items[k] = Integer.toString(shuffle_array[j]);
k++;
j++;
} while(k <= i);
j = 0;
}
//rannumbers_array[i] = r.nextInt(100);
//items[i] = Integer.toString(rannumbers_array[i]);
}
k = 0;
gridView = (GridView) this.findViewById(R.id.myGridView);
final CustomGridAdapter gridAdapter = new CustomGridAdapter(MainActivity.this, items);
gridView.setAdapter(gridAdapter);
buttonclicked = gridAdapter.getbutton();
gridView.post(new Runnable() {
public void run() {
gridView.setSelection(gridView.getCount() - 1);
}
});
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if(!firstclick)
{
customHandler.postDelayed(updateTimerThread, 0);
firstclick = true;
}
buttonclicked.setVisibility(view.GONE);
my CustomGridAdapter:
public class CustomGridAdapter extends BaseAdapter {
private Context context;
private String[] items;
private Button button;
LayoutInflater inflater;
public CustomGridAdapter(Context context, String[] items) {
this.context = context;
this.items = items;
inflater = (LayoutInflater) this.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = inflater.inflate(R.layout.cell, null);
}
button = (Button) convertView.findViewById(R.id.grid_item);
button.setHeight(175);
button.setText(items[position]);
return convertView;
}
#Override
public int getCount() {
return items.length;
}
#Override
public Object getItem(int position) {
return items[position];
}
#Override
public long getItemId(int position) {
return position;
}
public Button getbutton()
{
return button;
}
}
cell.xml:
<?xml version="1.0" encoding="utf-8"?>
<Button xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/grid_item"
android:layout_gravity="center"
android:maxHeight="175dip"
android:layout_marginLeft="20dip"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="05"
android:textSize="25sp"
android:clickable="false"
android:focusable="false"/>
activitymain.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
tools:ignore="MergeRootFrame" >
<TextView
android:id="#+id/timerValue"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="2dp"
android:text="#string/timerVal"
android:textColor="#ffffff"
android:textSize="30sp" />
<GridView
android:id="#+id/myGridView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:columnWidth="90dp"
android:horizontalSpacing="0dp"
android:numColumns="4"
android:verticalSpacing="0dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:id="#+id/feedback"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true" />
The buttonclicked.setVisibility(view.GONE); did not work, gave me an error I think. I am trying to have a button or item be clicked and have that item and/or the row the item is in to be deleted..how can I do this? What am I missing? After the deletion occurs I will need to redraw the grid to have less items in it too. Those are the two things that I am stumped on now
Use the view parameter on the OnItemClick implementation, this function give to you the position of the grid, the cell view and the id of the custom item on your adapter.
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if(!firstclick)
{
customHandler.postDelayed(updateTimerThread, 0);
firstclick = true;
}
//buttonclicked.setVisibility(view.GONE);
view.findViewById(R.id.grid_item).setVisibility(view.GONE);
}
}
Try to change the location of the declared input to OnCreate with final.
Related
i have seen many answers and i changed my code accordingly. now i am stuck with my own problem.after running this adapter , i am getting one value from list1 and only two values from list2 where both have three values.the layouts are coming fine.i don't know what is causing it and i am also not that much familiar with arrayadapter. it will be a great help. thanks in advance.
public class AxisAdapter extends ArrayAdapter<String> {
private ArrayList<String> list1 = new ArrayList<String>();
private ArrayList<String> list2 = new ArrayList<String>();
private Context context;
private final int view1 = 0;
private final int view2 = 1;
public MyAdapter(Context context, ArrayList<String> records,ArrayList<String> records1) {
super(context, 0, records);
this.context = context;
list1=records;
list2=records1;
}
public int getViewTypeCount() {
return 2;
}
public int getItemViewType(int position) {
return (position == 0) ? view1 : view2;
}
#Override
public View getView(final int position, #Nullable View convertView, #NonNull ViewGroup parent) {
int viewType = getItemViewType(position);
switch (viewType) {
case view1: {
final String item = list1.get(position);
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.abc_layout, parent, false);
}
final TextView list_Txt = (TextView) convertView.findViewById(R.id.txtDef);
Button list_But = (Button) convertView.findViewById(R.id.btnCall);
list_Txt.setText(item.replaceAll("[^A-Za-z]", " "));
list_But.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String number = item.replaceAll("[A-Za-z]", "");
Intent i = new Intent(Intent.ACTION_VIEW,
Uri.parse("tel:" + number));
context.startActivity(i);
}
});
}
break;
case view2: {
final String item = list2.get(position);
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.url_layout, parent, false);
}
final TextView list_Txt = (TextView) convertView.findViewById(R.id.txtDetail);
Button list_But = (Button) convertView.findViewById(R.id.btnVisit);
list_Txt.setText(item.replaceAll("[^A-Za-z]", " "));
list_But.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String number = item.replaceAll("[A-Za-z]", "");
Intent i = new Intent(Intent.ACTION_VIEW,Uri.parse("tel:12345"));
context.startActivity(i);
}
});
}
break;
}
return convertView;
}
}
in my activity class
public class AnActivity extends AppCompatActivity {
Toolbar toolbar;
AxisAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_axis);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
if(getSupportActionBar()!= null){
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
}
ListView list = (ListView) findViewById(R.id.axisList);
String[] ussd = getResources().getStringArray(R.array.axisCode);
String[] links = getResources().getStringArray(R.array.axisLink);
ArrayList<String> myData = new ArrayList<String>();
ArrayList<String> myLinks = new ArrayList<String>();
for(int i = 0; i<ussd.length;i++) {
myData.add(ussd[i]);
}
for(int i =0;i<links.length;i++){
myLinks.add(links[i]);
}
adapter = new AxisAdapter(this,myData,myLinks);
list.setAdapter(adapter);
//adapter= new AxisAdapter(this,myLinks);
//list.setAdapter(adapter);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home)
finish();
return super.onOptionsItemSelected(item);
}
}
and in my both layout class, there is one button and one text box.
<?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">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:padding="5dp"
android:background="#color/textboxColor">
<TextView
android:id="#+id/txtDef"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="start"
android:layout_marginLeft="2dp"
android:layout_weight="1"
android:fontFamily="#font/roboto_slab"
android:padding="5dp"
android:text="TextView"
android:textAppearance="#style/TextAppearance.AppCompat.Large"
android:textSize="20sp" />
<Button
android:id="#+id/btnCall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="2dp"
android:layout_weight="0"
android:fontFamily="#font/roboto_slab_bold"
android:text="Call"
android:theme="#style/PrimaryButton" />
</LinearLayout>
</LinearLayout>
another one:
<?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">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:padding="5dp"
android:background="#color/textboxColor">
<TextView
android:id="#+id/txtDetail"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="start"
android:layout_marginLeft="2dp"
android:layout_weight="1"
android:fontFamily="#font/roboto_slab"
android:padding="5dp"
android:text="TextView"
android:textAppearance="#style/TextAppearance.AppCompat.Large"
android:textSize="20sp" />
<Button
android:id="#+id/btnVisit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="2dp"
android:layout_weight="0"
android:fontFamily="#font/roboto_slab_bold"
android:text="Visit"
android:theme="#style/PrimaryButton" />
</LinearLayout>
</LinearLayout>
Try to send some string like in below case a string to determine the type, what you are actually trying to switch between, in my case it was monthly,yearly and so on, based on that string you can use different views or maybe show alternative layouts easily.
public class incomeadapter extends ArrayAdapter {
private List<Incomemodel> getdatas;
private int resource;
String incometype;
private LayoutInflater inflater;
Context context;
public incomeadapter(Context context, int resource, List<Incomemodel> getdata, String type) {
super(context, resource, getdata);
this.context = context;
getdatas = getdata;
incometype = type;
this.resource = resource;
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
TextView t1, t2;
if (convertView == null) {
if (incometype.equals("monthly")) {
convertView = inflater.inflate(R.layout.incomemonthly_item, null);
t1 = (TextView) convertView.findViewById(R.id.text2);
t2 = (TextView) convertView.findViewById(R.id.text1);
t1.setText(getdatas.get(position).getMonths());
t2.setText(getdatas.get(position).getIncome());
}
if (incometype.equals("yearly")) {
convertView = inflater.inflate(R.layout.incomeyearly_item, null);
t1 = (TextView) convertView.findViewById(R.id.text2);
t2 = (TextView) convertView.findViewById(R.id.text1);
t1.setText(getdatas.get(position).getYear());
t2.setText(getdatas.get(position).getIncome());
}
}
return convertView;
}
}
PS. Try using recyclerview with multiple viewholders, that will make it easy i guess
Your concern:
i am getting one value from list1 and only two values from list2 where
both have three values
The problem you are facing lies in these places:
private final int view1 = 0;
private final int view2 = 1;
...
public int getItemViewType(int position) {
return (position == 0) ? view1 : view2;
}
And then you call getItemViewType method in the getView() method:
int viewType = getItemViewType(position);
The value of position ranges from 0 to the number of items in the list minus 1. So the getItemViewType() method always return 0 (view1) if position = 0, and return 1 (view2) if position = 1, 2, 3...
You then write:
switch (viewType) {
case view1: {
final String item = list1.get(position);
...
}
break;
case view2: {
final String item = list2.get(position);
...
}
break;
}
In the case view1, it is simply indicating the first item in your list with position = 0. There is only 1 item staying at position 0, so final String item = list1.get(position); is only called once, that is why it returns 1 value.
In the case view2, it is simply indicating the items at position 1, 2, 3... As you said there are 3 items in the list, the adapter will generate 3 items for the list view and case view2 will be equal to position 1 and 2. So final String item = list2.get(position); is called twice, that is why it returns 2 values.
I dont know what your next step would be because I don't understand what you expect.
Update: specific solution:
public class AxisAdapter extends ArrayAdapter<String> {
private ArrayList<String> list1;
private ArrayList<String> list2;
private Context context;
public AxisAdapter(Context context, ArrayList<String> records,ArrayList<String> records1) {
super(context, 0);
this.context = context;
list1=records;
list2=records1;
}
#Override
public int getCount() {
return list1.size() + list2.size();
}
public int getViewTypeCount() {
return 2;
}
#Override
public View getView(final int position, #Nullable View convertView, #NonNull ViewGroup parent) {
if (position < list1.size()) {
final String item = list1.get(position);
convertView = LayoutInflater.from(getContext()).inflate(R.layout.abc_layout, parent, false);
final TextView list_Txt = (TextView) convertView.findViewById(R.id.txtDef);
Button list_But = (Button) convertView.findViewById(R.id.btnCall);
list_Txt.setText(item.replaceAll("[A-Za-z]", ""));
list_But.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String number = item.replaceAll("[A-Za-z]", "");
Intent i = new Intent(Intent.ACTION_VIEW,
Uri.parse("tel:" + number));
context.startActivity(i);
}
});
}
else {
final String item = list2.get(position - list1.size());
convertView = LayoutInflater.from(getContext()).inflate(R.layout.url_layout, parent, false);
final TextView list_Txt = (TextView) convertView.findViewById(R.id.txtDetail);
Button list_But = (Button) convertView.findViewById(R.id.btnVisit);
list_Txt.setText(item.replaceAll("[A-Za-z]", ""));
list_But.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String number = item.replaceAll("[A-Za-z]", "");
Intent i = new Intent(Intent.ACTION_VIEW,Uri.parse("tel:12345"));
context.startActivity(i);
}
});
}
return convertView;
}
}
I have two button at bottom i.e after listview ends.
I am using a custom listview which display list items with alternate colors.
how to set setOnClickListener for both button at bottom?
public class PieMainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mRes = getResources();
new Random(new Date().getTime());
solbtn = (Button)findViewById(R.id.solution);
String recive ;
Bundle b = getIntent().getExtras();
final int piewrong=b.getInt("piewrong");
final int pieright=b.getInt("pieright");
final int pieunclick=b.getInt("pieunclick");
setContentView(R.layout.piechart_result);
recive = pieright+"/20";
mPie.setUnit(recive);
data1 = new ArrayList<String>();
fillData() ;
listtotal =getIntent().getStringArrayListExtra("listtotal");
timeuse =getIntent().getStringArrayListExtra("timeused");
adapter1 = new ListAdapter(this, data1, listtotal,timeuse);
ListView lvMain = (ListView) findViewById(R.id.list);
lvMain.setAdapter(adapter1);
lvMain.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
int questionno = position+1;
Bundle b = new Bundle();
b.putInt("questionno",questionno);
b.putInt("piewrong",piewrong);
b.putInt("pieright",pieright);
b.putInt("pieunclick",pieunclick);
Intent in=new Intent(PieMainActivity.this,Solution.class);
in.putStringArrayListExtra("listtotal", (ArrayList<String>) listtotal);
in.putStringArrayListExtra("timeused", (ArrayList<String>) timeuse);
in.putExtras(b);
startActivity(in);
finish();
}
});
}
void fillData() {
for (int i = 1; i <= 20; i++) {
data1.add("Question " + i);
}
}
void fillcmp() {
for (int i = 1; i <= 20; i++) {
cmp.add("cmp " + i);
}
}
}
xml file
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:custom="http://schemas.android.com/apk/res/com.staritsolutions.apptitude"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_horizontal"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1.0"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="5dp"
android:layout_weight="1.0">
<ListView
android:id="#+id/list"
android:layout_height="wrap_content"
android:layout_width="match_parent"
>
</ListView>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="40dp"
android:layout_marginBottom="10dp"
android:layout_marginTop="5dp"
android:orientation="horizontal"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp">
<Button
android:id="#+id/home"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_gravity="bottom|center_horizontal"
android:layout_marginLeft="6dp"
android:layout_marginRight="3dp"
android:textSize="12dp"
android:layout_weight="1"
android:clickable="true"
android:gravity="center"
android:text="Main Menu"
android:background="#drawable/btn_blue"
android:textColor="#fff"
android:textStyle="bold" />
<Button
android:id="#+id/solution"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_gravity="bottom|center_horizontal"
android:layout_marginLeft="6dp"
android:layout_marginRight="3dp"
android:textSize="12dp"
android:layout_weight="1"
android:clickable="true"
android:gravity="center"
android:text="Solutions"
android:background="#drawable/btn_blue"
android:textColor="#fff"
android:textStyle="bold" />
</LinearLayout>
</LinearLayout>
BaseAdapter file
public class ListAdapter extends BaseAdapter{
Context ctx;
LayoutInflater lInflater;
List<String> data1;
List<String> cmp;
List<String> timeused;
ListAdapter(Context context, List<String> data1 ,List<String> cmp ,List<String> timeused) {
ctx = context;
this.data1 = data1;
this.cmp = cmp;
this.timeused = timeused;
lInflater = (LayoutInflater) ctx
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return data1.size();
}
public int getCount1() {
return cmp.size();
}
#Override
public Object getItem(int position) {
return data1.get(position);
}
public Object getItem1(int position1) {
return cmp.get(position1);
}
#Override
public long getItemId(int position) {
return position;
}
public long getItemId1(int position1) {
return position1;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if (view == null) {
view = lInflater.inflate(R.layout.listitem, parent, false);
}
/*if (position % 2 == 0) {
view.setBackgroundResource(R.drawable.artists_list_backgroundcolor);
} else {
view.setBackgroundResource(R.drawable.artists_list_background_alternate);
}*/
TextView text = (TextView) view.findViewById(R.id.heading);
int no = position;
if(cmp.get(position).equals("GREEN"))
{
text.setTextColor(Color.parseColor("#00D50E"));
}else if(cmp.get(position).equals("RED"))
{
text.setTextColor(Color.parseColor("#e84040"));
}else
{
text.setTextColor(Color.parseColor("#B441E9"));
}
((TextView) view.findViewById(R.id.heading)).setText(data1.get(position));
((TextView) view.findViewById(R.id.duration)).setText(timeused.get(position));
return view;
//String.valueOf(value);
}
}
So these buttons are not part of your ListView? Well, than in your onCreate do something like:
solbtn = (Button)findViewById(R.id.solution);
solbth.setOnClickListener( toolbar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
yourMethod();
}
});
And the same goes for the second button.
Or you can make your Activity implement View.OnClickListener, after doing this you can set your click listeners like this:
//this two lines in your OnCreate
button1.setOnClickListener(this);
button2.setOnClickListener(this);
//somewhere later in the code
#Override
public void onClick(View v) {
//do something
}
Just add the clickListeners in your onCrete() method:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
.....
solbtn = (Button) findViewById(R.id.home);
homebtn = (Button) findViewById(R.id.solution);
solbtn.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
// do stuff for solution button
}
});
homebtn.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
// do stuff for home button
}
});
.....
}
I divide my screen in two parts, one of the parts contain five buttons and another part contain seven ImageView with images. Now I want that ImageView rotate infinite,means, after last image, again images start to come. My XML is
<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="horizontal"
android:baselineAligned="true"
tools:context="in.example.splitapp.MainActivity" >
<ScrollView
android:id="#+id/scrollView"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:layout_weight="1"
>
<RelativeLayout
android:id="#+id/linearLayout1"
android:orientation="vertical"
android:layout_weight="1"
android:layout_height="fill_parent"
android:layout_width="fill_parent"
android:background="#android:color/holo_green_dark">
<Button android:id="#+id/button1"
android:layout_width="match_parent"
android:layout_height="100dp"
android:layout_centerHorizontal="true"
android:text="DOG"/>
<Button android:id="#+id/button2"
android:layout_width="match_parent"
android:layout_height="100dp"
android:layout_centerHorizontal="true"
android:layout_below="#id/button1"
android:text="CAT"/>
<Button android:id="#+id/button3"
android:layout_width="match_parent"
android:layout_height="100dp"
android:layout_centerHorizontal="true"
android:layout_below="#id/button2"
android:text="COW"/>
<Button android:id="#+id/button4"
android:layout_width="match_parent"
android:layout_height="100dp"
android:layout_centerHorizontal="true"
android:layout_below="#id/button3"
android:text="RAT"/>
<Button android:id="#+id/button5"
android:layout_width="match_parent"
android:layout_height="100dp"
android:layout_centerHorizontal="true"
android:layout_below="#id/button4"
android:text="PARROT"/>
</RelativeLayout>
</ScrollView>
<ScrollView
android:id="#+id/scrollView2"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:layout_weight="1"
>
<RelativeLayout
android:id="#+id/linearLayout2"
android:orientation="horizontal"
android:layout_weight="1"
android:layout_height="fill_parent"
android:layout_width="fill_parent"
android:background="#android:color/holo_purple"
>
<ImageView android:id="#+id/imageView1"
android:layout_width="match_parent"
android:layout_height="100dp"
android:layout_centerHorizontal="true"
android:background="#drawable/dog"
android:text="DOG"/>
<ImageView android:id="#+id/imageView2"
android:layout_width="match_parent"
android:layout_height="100dp"
android:layout_centerHorizontal="true"
android:layout_below="#id/imageView1"
android:background="#drawable/cat"
android:text="CAT"/>
<ImageView android:id="#+id/imageView3"
android:layout_width="match_parent"
android:layout_height="100dp"
android:layout_centerHorizontal="true"
android:layout_below="#id/imageView2"
android:background="#drawable/cow"
android:text="COW"/>
<ImageView android:id="#+id/imageView4"
android:layout_width="match_parent"
android:layout_height="100dp"
android:layout_centerHorizontal="true"
android:layout_below="#id/imageView3"
android:background="#drawable/rat"
android:text="RAT"/>
<ImageView android:id="#+id/imageView5"
android:layout_width="match_parent"
android:layout_height="100dp"
android:layout_centerHorizontal="true"
android:layout_below="#id/imageView4"
android:background="#drawable/parrot"
android:text="PARROT"/>
<ImageView android:id="#+id/imageView6"
android:layout_width="match_parent"
android:layout_height="100dp"
android:layout_centerHorizontal="true"
android:layout_below="#id/imageView5"
android:background="#drawable/horse"
android:text="HORSE"/>
<ImageView android:id="#+id/imageView7"
android:layout_width="match_parent"
android:layout_height="100dp"
android:layout_centerHorizontal="true"
android:layout_below="#id/imageView6"
android:background="#drawable/fish"
android:text="FISH"/>
</RelativeLayout>
</ScrollView>
</LinearLayout>
I want that ImageView side scrolling infinite means these five images repeated always.
This is my MainActivity:
public class MainActivity extends Activity implements OnScrollListener {
List<String> animalNameList = new ArrayList<String>();
ArrayList<Integer> animalImageList = new ArrayList<Integer>();
ImageAdapter imageAdapter;
NameAdapter nameAdapter = null;;
boolean flag = false;
ListView listView;
ListView listView1;
ListView upperListView;
RelativeLayout parentLayout;
LinearLayout childLayout;
int index = 0;
UpdateAdapter updateAdapter = null;
ArrayList<DataSplit> array = new ArrayList<DataSplit>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
animalNameList.add("CAT");
animalNameList.add("DOG");
animalNameList.add("COW");
animalNameList.add("RAT");
animalNameList.add("PARROT");
animalNameList.add("HORSE");
animalNameList.add("FISH");
animalImageList.add(R.drawable.horse);
animalImageList.add(R.drawable.parrot);
animalImageList.add(R.drawable.fish);
animalImageList.add(R.drawable.rat);
animalImageList.add(R.drawable.dog);
animalImageList.add(R.drawable.cat);
animalImageList.add(R.drawable.cow);
parentLayout = (RelativeLayout)findViewById(R.id.parentRelative);
childLayout = (LinearLayout)findViewById(R.id.childLinearLayout);
nameAdapter = new NameAdapter(MainActivity.this,
-1, animalNameList);
listView = (ListView)findViewById(R.id.listView1);
listView.setAdapter(nameAdapter);
imageAdapter = new ImageAdapter(MainActivity.this, -1, animalImageList);
listView1 = (ListView)findViewById(R.id.listView2);
CircularListAdapter circularAdapter = new CircularListAdapter(imageAdapter);
listView1.setDivider(null);
listView1.setAdapter(circularAdapter);
listView1.setOnScrollListener(this);
upperListView = (ListView)findViewById(R.id.upperListView);
listView.setOnScrollListener(new OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
// TODO Auto-generated method stub
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
// TODO Auto-generated method stub
if(flag)
{
}
}
});
}
class NameAdapter extends BaseAdapter {
private List<String> animalName;
private Activity context;
public NameAdapter(Activity context, int textViewResourceId,
List<String> animalName) {
super();
this.animalName = animalName;
this.context = context;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater inflater=context.getLayoutInflater();
convertView = inflater.inflate(R.layout.animalname, parent, false);
Button button=(Button)convertView.findViewById(R.id.button);
button.setId(position);
button.setText(animalName.get(position));
}
return convertView;
}
public int getCount()
{
int size = animalName.size();
return 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;
}
}
class ImageAdapter extends ArrayAdapter<Integer> {
private ArrayList<Integer> animalImage;
private Activity context;
public ImageAdapter(Activity context, int textViewResourceId,
ArrayList<Integer> animalImage) {
super(context, textViewResourceId);
this.animalImage = animalImage;
this.context = context;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if(view == null) {
view = new View(MainActivity.this);
}
view.setId(position);
//view.setBackgroundResource(animalImage[position]);
view.setBackgroundResource(animalImage.get(position));
return view;
}
public int getCount()
{
int size = animalImage.size();
return size;
}
}
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
int childInt = view.getChildAt(0).getId();
//String img1Text = this.getResources().getResourceEntryName(animalImage[childInt]);
String img1Text = this.getResources().getResourceEntryName(animalImageList.get(childInt));
//String buttonText = animalName[index];
String buttonText = animalNameList.get(index);
if(img1Text.equalsIgnoreCase(buttonText))
{
final String name = animalNameList.get(index);
int image = animalImageList.get(childInt);
DataSplit data = new DataSplit();
data.setAnimalName(name);
data.setAnimalImage(image);
array.add(data);
index++;
flag = true;
if(array.size() == 1)
{
updateAdapter = new UpdateAdapter(MainActivity.this,-1,array);
upperListView.setAdapter(updateAdapter);
upperListView.setVisibility(View.VISIBLE);
}
else
{
updateAdapter.notifyDataSetChanged();
}
listView.post(new Runnable() {
#Override
public void run() {
animalNameList.remove(name);
nameAdapter.notifyDataSetChanged();
}
});
}
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
}
class UpdateAdapter extends ArrayAdapter<Integer> {
ArrayList<DataSplit> dataSplit;
private Activity context;
public UpdateAdapter(Activity context, int textViewResourceId,
ArrayList<DataSplit> dataSplit) {
super(context, textViewResourceId);
this.dataSplit = dataSplit;
this.context = context;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater inflater=context.getLayoutInflater();
convertView = inflater.inflate(R.layout.addeddata, parent, false);
Button button=(Button)convertView.findViewById(R.id.button);
ImageView imageView=(ImageView)convertView.findViewById(R.id.imageView);
String animalName = dataSplit.get(position).getAnimalName();
int imageName = dataSplit.get(position).getAnimalImage();
button.setText(dataSplit.get(position).getAnimalName());
imageView.setBackgroundResource(dataSplit.get(position).getAnimalImage());
}
return convertView;
}
public int getCount()
{
int size = dataSplit.size();
return size;
}
}
}
I created activity_main.xml which contains a parent RelativeLayout and under this a ListView named upperListView and initially set visibility gone. Below this I created a LinearLayout and for this I created two ListView for Name DataSet and Image DataSet. When data matches I create a UpdateAdapter in which I use addeddata.xml, in which a button and ImageView created and when it is a successful match then hidden list view visibility becomes Visible and this "addeddata.xml" loaded in listview. This I perform. It will work perfectly.But when first matches,i.e, CAT name match with the Cat image, data is not deleted from both of listview and CAT name again shown in below the new ListView.
How to manage to complete matches if the application crashes.
This has been discussed in the past, with using circular Listviews:
How to create a closed (circular) ListView?
Closed or circular Horizontal ListView Android
I just want when I scroll ImageView part then if Dog image matches with the right end side Dog name then image stick with the Dog Name Button and rest of the images remain scrolling.
For this here is what you could try:
after scrolling items in list1 and list2, iterate over each item in the shortest listview and check if item1(position) [tag] = item2(position) [tag] (so, if you have a match)
if true:
redraw screen like this: add a new listview at the bottom of the screen (below both listviews). This listview with contain both item1 and item2 (so it's litviewitem xml will be a linear layout with other two linear layouts, one containing the matched pet name and the other the matched pet picture)
remove item1(position) and item2(position) from listview1, listview2 (which means you have to remove, for example, dog name from listview pet names datasource, and dog image from listview pet pictures datasource and reset adapters to listviews)
this way you will continue to be able to scroll and match items from listview1 and listview2 - without the already matching items-, and also have a bottom listview with all the matching elements that cannot be matched any more
Hope this helps!
After spend couple of days I found the perfect solution for my question. I dynamically created the ImageView and also the ListView. Image data are populating in the ListView. After matching the text with right Image, I take that ImageView from the List and set in dynamically created ImageView. Following is my code.
public class MainActivity extends Activity implements OnScrollChangedListener, OnScrollListener{
int index = 0;
ImageView imageView1;
List<Integer> spectrum = new ArrayList<Integer>();
String[] animalName;
ImageView[] imageArray;
Button[] buttonArray;
ListView listView;
SpectrumAdapter spectrumAdapter;
ListView animalImage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
animalName = new String[]{"CAT","DOG","COW","RAT","PARROT","HORSE","FISH"};
imageArray = new ImageView[animalName.length];
buttonArray = new Button[animalName.length];
LinearLayout inner1 = (LinearLayout)findViewById(R.id.innerLayout1);
LinearLayout inner2 = (LinearLayout)findViewById(R.id.innerLayout2);
ListView animalList = (ListView)findViewById(R.id.animalList);
NameAdapter nameAdapter = new NameAdapter(MainActivity.this,
-1, animalName);
animalList.setAdapter(nameAdapter);
for(int i=0;i<animalName.length;i++)
{
ImageView imageView = new ImageView(this);
imageView.setId(i);
RelativeLayout.LayoutParams params1 = new RelativeLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,150);
imageView.setTag(i);
imageView.setLayoutParams(params1);
imageView.setVisibility(View.GONE);
imageArray[i] = imageView;
inner1.addView(imageView);
}
ListView listView = new ListView(this);
LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
listView.setLayoutParams(param);
inner2.addView(listView);
spectrum.add(R.drawable.horse);
spectrum.add(R.drawable.rat);
spectrum.add(R.drawable.cow);
spectrum.add(R.drawable.dog);
spectrum.add(R.drawable.fish);
spectrum.add(R.drawable.parrot);
spectrum.add(R.drawable.cat);
spectrumAdapter = new SpectrumAdapter(MainActivity.this,
-1, spectrum);
CircularListAdapter circularAdapter = new CircularListAdapter(spectrumAdapter);
listView.setAdapter(circularAdapter);
listView.setOnScrollListener(this);
}
class NameAdapter extends BaseAdapter {
private String[] animalName;
private Activity context;
public NameAdapter(Activity context, int textViewResourceId,
String[] animalName) {
super();
this.animalName = animalName;
this.context = context;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater inflater=context.getLayoutInflater();
convertView = inflater.inflate(R.layout.animalname, parent, false);
}
Button button=(Button)convertView.findViewById(R.id.button);
button.setText(animalName[position]);
return convertView;
}
public int getCount()
{
int size = animalName.length;
return 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;
}
}
class SpectrumAdapter extends ArrayAdapter<Integer> {
private List<Integer> spectrum;
public SpectrumAdapter(Context context, int textViewResourceId,
List<Integer> spectrum) {
super(context, textViewResourceId, spectrum);
this.spectrum = spectrum;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if(view == null) {
view = new View(MainActivity.this);
}
view.setId(position);
view.setBackgroundResource(spectrum.get(position));
return view;
}
public int getCount()
{
int size = spectrum.size();
return size;
}
}
#Override
public void onScrollChanged() {
// TODO Auto-generated method stub
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
}
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
// TODO Auto-generated method stub
int childInt = view.getChildAt(0).getId();
String img1Text = this.getResources().getResourceEntryName(spectrum.get(childInt));
String bb = animalName[index];
if(bb.equalsIgnoreCase(img1Text))
{
ImageView img = imageArray[index];
img.setBackgroundResource(spectrum.get(childInt));
img.setVisibility(View.VISIBLE);
index++;
}
else
{
}
}
}
This is the perfect solution for the question. Thanks all for the suggestion.
I'm using gridview inside a Listview, but I have a focusable problem.
I have set the width of the gridview, but I fill some items of gridview, on the left space of gridview (which is blank) means items not fill of gridview in listview. If I click on it, it does not perform a listitem click
As given in the image, I want to perform a listview item click if it is clicked anywhere in the list item. I want to get a listitem click.
But when I click on ListView item, that is, GridView then the ListItem click is not working...
public class History extends Activity {
String name, id, description, count, total;
ArrayList<String> TAG_ID = new ArrayList<String>();
ArrayList<String> TAG_COFFEESHOP_NAME = new ArrayList<String>();
ArrayList<String> TAG_COUNT = new ArrayList<String>();
ArrayList<String> TAG_TOTAL = new ArrayList<String>();
Context context;
JSONArray CoffeeUser = null;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listlayout);
ListView listView = (ListView) findViewById(R.id.listnew);
listView.setAdapter(new MyCustomAdapter());
listView.setTextFilterEnabled(true);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
public void onItemClick(AdapterView<?> paramAnonymousAdapterView, View paramAnonymousView, int paramAnonymousInt, long paramAnonymousLong)
{
Intent intent = new Intent();
intent.putExtra("coffeeshopid", ((TextView)paramAnonymousView.findViewById(R.id.hlcoffeeshopid)).getText() );
intent.setClass(getParent(), Stamps.class);
HistoryStack hisStack = (HistoryStack) getParent();
hisStack.push("Stamps", intent);
}
});
}
class MyCustomAdapter extends BaseAdapter {
Context ctx;
public MyCustomAdapter() {
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
SharedPreferences prfs = getSharedPreferences("GUID_FILE_NAME", Context.MODE_PRIVATE);
JSONObject json = jParser.methodhistory("http://api.com");
try {
// Getting Array of Employee
CoffeeUser = json.getJSONArray("CoffeeUser");
// Looping of List
for (int i = 0; i < CoffeeUser.length(); i++) {
JSONObject c = CoffeeUser.getJSONObject(i);
// Storing each json item in variable
id = c.getString("CS_Id");
name = c.getString("ShopName");
count = c.getString("totalstamps");
total = c.getString("threshholdcount");
// Adding all get values into array
if (name != "null") {
TAG_COFFEESHOP_NAME.add(name);
TAG_ID.add(id);
TAG_TOTAL.add(total);
TAG_COUNT.add(count);
}
}
}
catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public int getCount() {
return TAG_COFFEESHOP_NAME.size();
}
#Override
public Object getItem(int paramInt) {
return TAG_COFFEESHOP_NAME.get(paramInt);
}
#Override
public long getItemId(int paramInt) {
return paramInt;
}
public class MyCustomHolder {
public GridView localGrid;
public TextView CoffeeShopName,coffeeshopsdescription,coffeeshopid;
}
#Override
public View getView(int paramInt, View paramView,ViewGroup paramViewGroup) {
View localView = paramView;
MyCustomHolder holder = null;
if (localView == null) {
LayoutInflater inflater = (LayoutInflater) History.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
localView = inflater.inflate(R.layout.historylist, null);
holder = new MyCustomHolder();
holder.CoffeeShopName = (TextView) localView.findViewById(R.id.hlcoffeeshopname);
holder.coffeeshopid = (TextView) localView.findViewById(R.id.hlcoffeeshopid);
holder.localGrid = (GridView) localView.findViewById(R.id.gridViewdistorylist);
localView.setTag(holder);
}
else {
holder = (MyCustomHolder) localView.getTag();
}
holder.CoffeeShopName.setText(TAG_COFFEESHOP_NAME.get(paramInt));
holder.coffeeshopid.setText(TAG_ID.get(paramInt));
holder.localGrid.setAdapter(new GridAdapterA(History.this, TAG_TOTAL.get(paramInt), TAG_COUNT.get(paramInt)));
holder.localGrid.setFocusable(false);
holder.localGrid.setFocusableInTouchMode(false);
holder.CoffeeShopName.setFocusable(false);
holder.CoffeeShopName.setFocusableInTouchMode(false);
localView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent();
intent.putExtra("coffeeshopid", ((TextView)v.findViewById(R.id.hlcoffeeshopid)).getText() );
intent.setClass(getParent(), Stamps.class);
HistoryStack hisStack = (HistoryStack) getParent();
hisStack.push("Stamps", intent);
}
});
return localView;
}
}
public class GridAdapterA extends BaseAdapter {
private Context context;
String total,count;
public GridAdapterA(Context context) {
this.context = context;
}
public GridAdapterA(Context context, String total, String count) {
// TODO Auto-generated constructor stub
this.context = context;
this.total = total;
this.count = count;
}
public boolean areAllItemsEnabled()
{
return false;
}
public boolean isEnabled(int position)
{
return false;
}
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View gridView;
if (convertView == null) {
gridView = new View(context);
gridView = inflater.inflate(R.layout.customgrid_row, null);
gridView.setFocusable(false);
ImageView imageView = (ImageView) gridView.findViewById(R.id.grid_item_image);
imageView.setFocusable(false);
int i = 0;
if(count!="null")
i = Integer.parseInt(count);
if (position<i ) {
//imageView.setImageResource(R.drawable.ii);
// textView.setText(gridlist[position]);
}
else {
imageView.setImageResource(R.drawable.changedcup);
// textView.setText("");
}
}
else {
gridView = (View) convertView;
}
/*gridView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent();
intent.putExtra("coffeeshopid", ((TextView)v.findViewById(R.id.hlcoffeeshopid)).getText() );
intent.setClass(getParent(), Stamps.class);
HistoryStack hisStack = (HistoryStack) getParent();
hisStack.push("Stamps", intent); }
});*/
return gridView;
}
#Override
public int getCount() {
int j=0;
if(total!="null"){
j = Integer.parseInt(total);
}
return j;
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
}
}
historylist
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#drawable/list_selector"
android:orientation="horizontal"
android:padding="5dip" >
<LinearLayout
android:id="#+id/thumbnail"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_marginRight="5dip"
android:background="#drawable/image_bg"
android:padding="3dip" >
<ImageView
android:id="#+id/list_image"
android:layout_width="50dip"
android:layout_height="50dip"
android:src="#drawable/rcup" />
</LinearLayout>
<!-- hlcoffeeshopname Of Song -->
<TextView
android:id="#+id/hlcoffeeshopname"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/thumbnail"
android:layout_toRightOf="#+id/thumbnail"
android:text="Rihanna Love the way lie"
android:textColor="#040404"
android:textSize="20dip"
android:textStyle="bold"
android:typeface="sans" />
<TextView
android:id="#+id/hlcoffeeshopid"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="gone"
/>
<GridView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/gridViewdistorylist"
android:layout_width="wrap_content"
android:layout_height="40dp"
android:layout_below="#+id/hlcoffeeshopname"
android:layout_toRightOf="#+id/thumbnail"
android:columnWidth="20dp"
android:background="#null"
android:descendantFocusability="blocksDescendants"
android:focusable="false"
android:focusableInTouchMode="false"
android:numColumns="10"
android:stretchMode="none" >
</GridView>
</RelativeLayout>
New GetView
#Override
public View getView(int paramInt,
View paramView,
ViewGroup paramViewGroup) {
View localView = paramView;
MyCustomHolder holder = null;
if (localView == null) {
LayoutInflater inflater = (LayoutInflater) CopyOfHistory.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
localView = inflater.inflate(R.layout.copyhistorylist, null);
holder = new MyCustomHolder();
holder.coffeeShopName = (TextView) localView.findViewById(R.id.hlcoffeeshopname);
holder.coffeeshopid = (TextView) localView.findViewById(R.id.hlcoffeeshopid);
localView.setTag(holder);
}
else {
holder = (MyCustomHolder) localView.getTag();
}
holder.coffeeShopName.setText(TAG_COFFEESHOP_NAME.get(paramInt));
holder.coffeeshopid.setText(TAG_ID.get(paramInt));
int looplimit = Integer.parseInt(TAG_TOTAL.get(paramInt));
for (int i = 0; i < looplimit; i++) {
Log.e("loop", String.valueOf(looplimit));
ImageView imageView = new ImageView(CopyOfHistory.this);
if (i < Integer.parseInt(TAG_COUNT.get(paramInt))) {
imageView.setImageDrawable(getResources().getDrawable(R.drawable.ii));
} else {
imageView.setImageDrawable(getResources().getDrawable(R.drawable.iii));
}
RelativeLayout layout = (RelativeLayout) localView.findViewById(R.id.hlrlayout);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(30,30);
params.setMargins(i*40, 0, 0, 0);
imageView.setLayoutParams(params);
layout.addView(imageView);
//holder.relativeLayout = new RelativeLayout();
}
holder.coffeeShopName.setFocusable(false);
holder.coffeeShopName.setFocusableInTouchMode(false);
localView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent();
intent.putExtra("coffeeshopid", ((TextView) v
.findViewById(R.id.hlcoffeeshopid)).getText());
intent.setClass(getParent(), Stamps.class);
HistoryStack hisStack = (HistoryStack) getParent();
hisStack.push("Stamps", intent);
}
});
return localView;
}
You might have solved it, but I have another solution that may help someone.
Use android:descendantFocusability="beforeDescendants" in the root layout of your list_cell XML.
Order to have lists within other lists. You must generate a custom view. If you want one the simple, consisting of a Java class and an XML file, then in the code you only have to instantiate it and add it to a linear layout.
Here I leave a small example.
XML
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical" >
<TextView
android:id="#+id/txtAltaPropinaTextoAyudaTipo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="5dp"
android:layout_marginTop="5dp"
android:gravity="center_vertical"
android:text="-"
android:textColor="#000000"
android:textSize="18sp"
android:textStyle="bold" />
<TextView
android:id="#+id/txtListadoZonasNombreZona"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginRight="5dp"
android:layout_marginTop="5dp"
android:layout_toLeftOf="#+id/txtAltaPropinaTextoAyudaTipo"
android:layout_toRightOf="#+id/txtAltaPropinaTextoAyudaTipo"
android:singleLine="true"
android:text="TextView"
android:textColor="#000000" />
</RelativeLayout>
Java code
public class CVTexto extends RelativeLayout {
public TextView txtTexto;
public int idCv;
public CVTexto(Context context) {
super(context);
// TODO Auto-generated constructor stub
IniciarCuadro();
}
public CVTexto(Context context, AttributeSet attrs) {
super(context, attrs);
IniciarCuadro();
}
public CVTexto(Context context, AttributeSet attrs, int defStyle) {
super( context, attrs, defStyle );
IniciarCuadro();
}
private void IniciarCuadro()
{
//Utilizamos el layout 'control_login' como interfaz del control
String infService = Context.LAYOUT_INFLATER_SERVICE;
LayoutInflater li =
(LayoutInflater)getContext().getSystemService(infService);
li.inflate(R.layout.ll_adapter_listado_zonas_asignadas_usuario, this, true);
AsignarElemetos();
//Obtenemoslas referencias a los distintos control
//Asociamos los eventos necesarios
// asignarEventos();
}
private void AsignarElemetos(){
txtTexto = (TextView)findViewById(R.id.txtListadoZonasNombreZona);
}
}
Add to linearlayout:
cvTextp objCV = new cvTexto(context);
LinearLayout.addView(objCv);
And delete views:
LinearLayout.removeallViews;
I got this answer by changing the grid layout to LinearLayout. I added items dynamically into linearLayout, and then my problem was solved.
I have done research on it and I get to know that inside a scrollable widget which uses an adapter you should not use any other widget which is scrollable which also uses an adapter such as gridview inside listview because of touch events complexity.
So I think you should move to another approach for this. In your case, you can add a linear layout and can add cup images dynamically into that layout by setting parameters. I hope this helped you.
I don't know how your below code is working, but if I would like handle each on-click listener of each then I would do something like below.
for (int i = 0; i < looplimit; i++) {
Log.e("loop", String.valueOf(looplimit));
ImageView imageView = new ImageView(CopyOfHistory.this);
if (i < Integer.parseInt(TAG_COUNT.get(paramInt))) {
imageView.setImageDrawable(getResources().getDrawable(R.drawable.ii));
}
else {
imageView.setImageDrawable(getResources().getDrawable(R.drawable.iii));
}
RelativeLayout layout = (RelativeLayout) localView.findViewById(R.id.hlrlayout);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(30,30);
params.setMargins(i*40, 0, 0, 0);
imageView.setLayoutParams(params);
layout.addView(imageView);
//holder.relativeLayout = new RelativeLayout();
// Handle your each on-click of dynamic added view while they added in getview() method
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Do what is necessary
}
});
}
I don't know how your below code is working, but if I would like handle each on-click listener of each then I would do something like below.
for (int i = 0; i < looplimit; i++) {
Log.e("loop", String.valueOf(looplimit));
ImageView imageView = new ImageView(CopyOfHistory.this);
if (i < Integer.parseInt(TAG_COUNT.get(paramInt))) {
imageView.setImageDrawable(getResources().getDrawable(R.drawable.ii));
}
else {
imageView.setImageDrawable(getResources().getDrawable(R.drawable.iii));
}
RelativeLayout layout = (RelativeLayout) localView.findViewById(R.id.hlrlayout);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(30,30);
params.setMargins(i*40, 0, 0, 0);
imageView.setLayoutParams(params);
layout.addView(imageView);
//holder.relativeLayout = new RelativeLayout();
// Handle your each on-click of dynamic added view while they added in getview() method
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Do what is necessary
}
});
}
I have a class witch holds some variables...eg
int yellow = 0xffffff66;
int green = 0xff00EE76;
int red = 0xffff4342;
int blue = 0xff42c3ff;
int purple = 0xff9932CC;
int white = 0xffffffff;
ArrayList<Integer>nextColorArray = new ArrayList<Integer>();
int total_count = 0;
in my onCreate method:
GridView gridview2 = (GridView) findViewById(R.id.colorNext);
gridview2.setAdapter(new ImageAdapter(this));
nextColorArray.add(blue);
nextColorArray.add(green);
nextColorArray.add(red);
nextColorArray.add(yellow);
nextColorArray.add(purple);
from my adapter i add elements to the grid view to produce 5 colors the show in the gridview UI no problem... o.k
i have a button onclick(not in onCreate) event that increments total_count by 1 each time i click the button...o.k when the total_count is greater than ten i want to add a new element to the array..ok
if (action == MotionEvent.ACTION_DOWN) {
if(total_Count > 10){
nextColorArray.add(0, white);
}...ok
my problem is that the UI gridview is not updating the ui to show the new color...any ideas on how i can update the adapter when a new color is added to the list????
Edit: Since i am not sure how many edit's i made to my post. i edited the question and added the answer here. This works .
public class MainActivity extends Activity {
int yellow = 0xffffff66;
int green = 0xff00EE76;
int red = 0xffff4342;
int blue = 0xff42c3ff;
int purple = 0xff9932CC;
int white = 0xFFFFFFFF;
int total_Count = 0;
int colorPosition = 0;
int colorPickerStart = 0;
Button button;
ImageView imageView;
ImageAdapter ia;
GridView gridview2;
ArrayList<Integer>nextColorArray = new ArrayList<Integer>(10);
ArrayList<Integer>colorPicker = new ArrayList<Integer>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
nextColorArray.add(blue);
nextColorArray.add(green);
nextColorArray.add(red);
nextColorArray.add(yellow);
nextColorArray.add(purple);
//set adapters
GridView gridview = (GridView) findViewById(R.id.gridview);
gridview.setAdapter(new ButtonAdapter(this));
button = (Button) findViewById(R.id.button1);
gridview2 = (GridView) findViewById(R.id.gridview2);
ia = new ImageAdapter(this, nextColorArray);
gridview2.setAdapter(ia);
button.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View arg0) {
nextColorArray.add(Color.BLACK);
ia.notifyDataSetChanged();
}
});
//next color elements
}
public class ImageAdapter extends BaseAdapter {
private Context mContext;
ArrayList<Integer> a;
public ImageAdapter(Context c, ArrayList<Integer> a) {
mContext = c;
this.a = a;
}
public int getCount() {
return a.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return 0;
}
/*create a new ImageView for each item referenced by the Adapter*/
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {/*if it's not recycled, initialize some attributes*/
imageView = new ImageView(mContext);
imageView.setLayoutParams(new GridView.LayoutParams(50, 45));
imageView.setBackgroundColor(nextColorArray.get(colorPosition));
if(colorPosition < 9) colorPosition++;
} else {
imageView = (ImageView) convertView;
}
return imageView;
}
}
/*button adapter*/
public class ButtonAdapter extends BaseAdapter {
private Context mContext;
public ButtonAdapter(Context c) {
mContext = c;
}
public int getCount() {
return nextColorArray .size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return 0;
}
// create a new button for each item referenced by the Adapter
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
button = new Button(mContext);
button.setLayoutParams(new GridView.LayoutParams(128, 128));
total_Count++;
button.setText(""+total_Count);
} else {
button = (Button) convertView;
}
return button;
}// end get view
}// end button adapter
activity_main
<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" >
<GridView
android:id="#+id/gridview"
android:layout_width="fill_parent"
android:layout_height="150dp"
android:columnWidth="0dp"
android:gravity="center"
android:numColumns="2"
android:horizontalSpacing="20dp"
android:padding="40dp"
android:verticalSpacing="20dp" />
<GridView
android:id="#+id/gridview2"
android:layout_width="fill_parent"
android:layout_height="150dp"
android:layout_above="#+id/button1"
android:layout_alignParentRight="true"
android:layout_marginBottom="74dp"
android:columnWidth="0dp"
android:gravity="center"
android:horizontalSpacing="20dp"
android:numColumns="2"
android:padding="40dp"
android:verticalSpacing="20dp" >
</GridView>
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:text="Button" />
</RelativeLayout>
You have to call notifyDataSetChanged() on your adapter in order to refresh its content.
ImageAdapter ia;
GridView gridview2 = (GridView) findViewById(R.id.colorNext);
ia = new ImageAdapter(this);
gridview2.setAdapter(ia);
....
if (action == MotionEvent.ACTION_DOWN) {
if(total_Count > 10){
nextColorArray.add(0, white);
ia.notifyDataSetChanged(); // call notifyDataSetChanged to update your gridview
}
public void notifyDataSetChanged ()
Notifies the attached observers that the underlying data has been changed and any View reflecting the data set should refresh itself.
Example:
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" >
<GridView
android:id="#+id/gridview"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:columnWidth="0dp"
android:gravity="center"
android:numColumns="2"
android:horizontalSpacing="20dp"
android:padding="40dp"
android:verticalSpacing="20dp" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:text="Button" />
</RelativeLayout>
MainActivity
public class MainActivity extends Activity {
ImageAdapter im;
ImageView imageView;
GridView gd;
ArrayList<Integer>nextColorArray = new ArrayList<Integer>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
int yellow = 0xffffff66;
int green = 0xff00EE76;
int red = 0xffff4342;
int blue = 0xff42c3ff;
int purple = 0xff9932CC;
final int white = 0xffffffff;
nextColorArray.add(blue);
nextColorArray.add(green);
nextColorArray.add(red);
nextColorArray.add(yellow);
nextColorArray.add(purple);
gd= (GridView) findViewById(R.id.gridview);
im = new ImageAdapter(this,nextColorArray);
gd.setAdapter(im);
Button b= (Button) findViewById(R.id.button1);
b.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
nextColorArray.add(Color.BLACK);
im.notifyDataSetChanged();
}
});
}
}
ImageAdapter
public class ImageAdapter extends BaseAdapter{
Context mContext;
ArrayList<Integer> a;
public ImageAdapter(Context context,ArrayList<Integer> a) {
mContext=context;
this.a= a;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return a.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(final int position, View arg1, ViewGroup arg2) {
ImageView imageView;
if (arg1 == null) {
imageView = new ImageView(mContext);
imageView.setPadding(0, 20, 0, 0);
} else {
imageView = (ImageView) arg1;
}
imageView.setBackgroundColor(a.get(position));
return imageView;
}
}
As and when you click black color appears on the screen.
SnapShot