There was already someone else with a similar problem, but I couldn't understand the anwser and I wasn't able to add a coment to receive
more informations. So please help me!
This is my main JavaClass
package ch.androidnewcomer.muckenfangfinal;
import android.app.Activity;
import android.app.Dialog;
import android.os.Bundle;
import android.os.Handler;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.Date;
import java.util.Random;
public class GameActivity extends Activity implements View.OnClickListener, Runnable{
public static final int DELAY_MILLIS = 1000;
public static final int ZEITSCHEIBEN = 60;
public float massstab;
private int runde;
private int punkte;
private int muecken;
private int gefangeneMuecken;
private int zeit;
private static final long HOECHSTALTER_MS = 2000;
private Random zufallsgenerator = new Random();
private ViewGroup spielbereich;
private Handler handler = new Handler();
private boolean spielLaeuft;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
massstab = getResources().getDisplayMetrics().density;
spielbereich = (ViewGroup)findViewById(R.id.spielbereich);
spielStarten();
}
private void spielStarten() {
spielLaeuft = true;
runde = 0;
punkte = 0;
starteRunde();
}
private void bildschirmAktualisieren() {
TextView tvPunkte = (TextView)findViewById(R.id.points);
tvPunkte.setText(Integer.toString(punkte));
TextView tvRunde = (TextView)findViewById(R.id.round);
tvRunde.setText(Integer.toString(runde));
TextView tvTreffer = (TextView)findViewById(R.id.hits);
tvTreffer.setText(Integer.toString(gefangeneMuecken));
TextView tvZeit = (TextView)findViewById(R.id.time);
tvZeit.setText(Integer.toString(zeit/(1000/DELAY_MILLIS)));
FrameLayout flTreffer = (FrameLayout)findViewById(R.id.bar_hits);
FrameLayout flZeit = (FrameLayout)findViewById(R.id.bar_time);
ViewGroup.LayoutParams lpTreffer = flTreffer.getLayoutParams();
lpTreffer.width = Math.round( massstab * 300 * Math.min( gefangeneMuecken,muecken) / muecken);
ViewGroup.LayoutParams lpZeit = flZeit.getLayoutParams();
lpZeit.width = Math.round( massstab * zeit *300 / ZEITSCHEIBEN);
}
private void zeitHerunterzaehlen() {
zeit = zeit - 1;
if(zeit % (1000/DELAY_MILLIS) == 0) {
float zufallszahl = zufallsgenerator.nextFloat();
double wahrscheinlichkeit = muecken * 1.5;
if (wahrscheinlichkeit > 1) {
eineMueckeAnzeigen();
if (zufallszahl < wahrscheinlichkeit - 1) {
eineMueckeAnzeigen();
}
} else {
if (zufallszahl < wahrscheinlichkeit) {
eineMueckeAnzeigen();
}
}
}
mueckenVerschwinden();
bildschirmAktualisieren();
if(!pruefeSpielende()) {
if(!pruefeRundenende()) {
handler.postDelayed(this, DELAY_MILLIS);
}
}
}
private boolean pruefeRundenende() {
if (gefangeneMuecken >= muecken) {
starteRunde();
return true;
}
return false;
}
private void starteRunde() {
runde = runde +1;
muecken = runde *10;
gefangeneMuecken = 0;
zeit = ZEITSCHEIBEN;
bildschirmAktualisieren();
handler.postDelayed(this, DELAY_MILLIS);
}
private boolean pruefeSpielende() {
if(zeit == 0 && gefangeneMuecken < muecken) {
gameOver();
return true;
}
return false;
}
private void gameOver() {
Dialog dialog = new Dialog(this, android.R.style.Theme_Translucent_NoTitleBar_Fullscreen);
dialog.setContentView(R.layout.gameover);
dialog.show();
spielLaeuft = false;
}
private void mueckenVerschwinden() {
int nummer=0;
while (nummer < spielbereich.getChildCount()) {
ImageView muecke = (ImageView)spielbereich.getChildAt(nummer);
Date geburtsdatum = (Date) muecke.getTag(R.id.geburtsdatum);
long alter = (new Date()).getTime() - geburtsdatum.getTime();
if(alter > HOECHSTALTER_MS) {
spielbereich.removeView(muecke);
}else {
nummer++;
}
}
}
private void eineMueckeAnzeigen() {
int breite = spielbereich.getWidth();
int hoehe = spielbereich.getHeight();
int muecke_breite = (int) Math.round(massstab* 60);
int muecke_hoehe = (int) Math.round(massstab*49);
int links = zufallsgenerator.nextInt(breite - muecke_breite);
int oben = zufallsgenerator.nextInt(hoehe - muecke_hoehe);
ImageView muecke = new ImageView(this);
muecke.setImageResource(R.drawable.muecke);
muecke.setOnClickListener(this);
muecke.setTag(R.id.geburtsdatum, new Date());
FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(muecke_breite, muecke_hoehe);
params.leftMargin = links;
params.topMargin = oben;
params.gravity = Gravity.TOP + Gravity.LEFT;
spielbereich.addView(muecke,params);
}
#Override
public void onClick(View muecke) {
gefangeneMuecken++;
punkte += 100;
bildschirmAktualisieren();
spielbereich.removeView(muecke);
}
#Override
public void run() {
zeitHerunterzaehlen();
}
}
The FrameLayout, where I'm trying to display the 'muecke - mosquito' is called 'spielbereich' meaning as much as playground.
And this is the LogCat
12-28 16:19:26.449 5302-5302/ch.androidnewcomer.muckenfangfinal E/AndroidRuntime: FATAL EXCEPTION: main
Process: ch.androidnewcomer.muckenfangfinal, PID: 5302
java.lang.ClassCastException: android.widget.LinearLayout cannot be cast to android.widget.ImageView
at ch.androidnewcomer.muckenfangfinal.GameActivity.mueckenVerschwinden(GameActivity.java:168)
at ch.androidnewcomer.muckenfangfinal.GameActivity.zeitHerunterzaehlen(GameActivity.java:104)
at ch.androidnewcomer.muckenfangfinal.GameActivity.run(GameActivity.java:218)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6776)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1520)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1410)
And here is my xmlLayout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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="ch.androidnewcomer.muckenfangfinal.GameActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="61dp">
<TextView
android:id="#+id/round"
android:layout_width="136dp"
android:layout_height="wrap_content"
android:text="TextView"
android:textSize="21sp"
android:textStyle="bold" />
<TextView
android:id="#+id/points"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:text="TextView"
android:textSize="21sp"
android:textStyle="bold" />
</FrameLayout>
<FrameLayout
android:id="#+id/spielbereich"
android:layout_width="match_parent"
android:layout_height="332dp"
android:layout_weight="1">
<LinearLayout
android:id="#+id/hintergrundlinearlayout"
android:layout_width="match_parent"
android:layout_height="70dp"
android:layout_gravity="bottom"
android:orientation="vertical">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="35dp">
<FrameLayout
android:id="#+id/bar_hits"
android:layout_width="50dp"
android:layout_height="match_parent"
android:layout_gravity="center_vertical"
android:background="#android:color/holo_orange_dark">
</FrameLayout>
<TextView
android:id="#+id/hits"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:text="#string/hits"
android:textSize="15sp"
android:textStyle="bold" />
</FrameLayout>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout
android:id="#+id/bar_time"
android:layout_width="50dp"
android:layout_height="match_parent"
android:layout_gravity="center_vertical"
android:background="#android:color/holo_orange_light">
</FrameLayout>
<TextView
android:id="#+id/time"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:text="#string/time" />
</FrameLayout>
</LinearLayout>
</FrameLayout>
</LinearLayout>
if you need anymore informations, please tell me.
It would be great if you could tell me exactely how I have to change the code, because I'm really a beginner.
you are casting a linear layout to imageview.You are trying to get a child of frame layout which is a linear layout but you casted it to a image view.thats why this error was happened. casting it to the linearlayout will solve this error.
This is your layout with id spielbereich
<FrameLayout
android:id="#+id/spielbereich"
android:layout_width="match_parent"
android:layout_height="332dp"
android:layout_weight="1">
<LinearLayout
android:id="#+id/hintergrundlinearlayout"
android:layout_width="match_parent"
android:layout_height="70dp"
android:layout_gravity="bottom"
android:orientation="vertical">
And this is the code where you are trying to cast the childView into an ImageView
private void mueckenVerschwinden() {
int nummer=0;
while (nummer < spielbereich.getChildCount()) {
ImageView muecke = (ImageView)spielbereich.getChildAt(nummer);
Date geburtsdatum = (Date) muecke.getTag(R.id.geburtsdatum);
long alter = (new Date()).getTime() - geburtsdatum.getTime();
if(alter > HOECHSTALTER_MS) {
spielbereich.removeView(muecke);
}else {
nummer++;
}
}
}
ImageView muecke = (ImageView)spielbereich.getChildAt(nummer);
This line is giving you a cast error because nummer = 0 at this point and spielbereich.getChildAt(0) is a LinearLayout
Related
I am working on a tasks app, for which I created a list view that shows list items consitsting of task names, their priority etc. The data given to the list view is from an sqlite database. I, however, am unable to add more than one item to the list. I have no idea why. I have created a method to do so, but it doesn't seem to work. I don't know if the error is due to the database or my method itself. Even debugging didn't help. Please note that I am using a list adapter since I am using a custom listview.
Code for Activity where list is shown :
package com.example.taskmasterv3;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.database.Cursor;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.widget.ListView;
import android.widget.TextView;
import java.util.ArrayList;
public class TaskSummary extends AppCompatActivity {
ListView lvTaskList;
TextView tvBreak, tvBreakAfterEvery, txt1, txt2, text1, hmm;
TextView break_duration_mins;
ArrayList<SubtaskPartTwo> subtaskList = new ArrayList<>();
String subtname;
String pri;
String time;
DBHelper dbHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_task_summary);
lvTaskList = findViewById(R.id.lvTaskList);
tvBreak = findViewById(R.id.tvBreak);
tvBreakAfterEvery = findViewById(R.id.tvBreakAfterEvery);
txt1 = findViewById(R.id.txt1);
txt2 = findViewById(R.id.txt2);
break_duration_mins = findViewById(R.id.break_duration_mins);
text1 = findViewById(R.id.text1);
hmm = findViewById(R.id.hmm);
dbHelper = new DBHelper(this);
subtname = getIntent().getStringExtra("subtaskname");
pri = getIntent().getStringExtra("pri");
time = getIntent().getStringExtra("time");
// Using adapter for listview :
SubtaskDetailAdapter adapter = new SubtaskDetailAdapter(this, subtaskList);
lvTaskList.setAdapter(adapter);
SubtaskPartTwo subtaskPartTwo = new SubtaskPartTwo(subtname, pri, time);
subtaskList.add(subtaskPartTwo);
adapter.addANewSubTask(subtaskPartTwo);
double working_hours = getIntent().getIntExtra("working_hours", 1);
double working_minutes = getIntent().getIntExtra("working_minutes", 0);
double without_break_hours = getIntent().getIntExtra("without_break_hours", 1);
double without_break_minutes = getIntent().getIntExtra("without_break_minutes", 0);
double break_duration = getIntent().getIntExtra("break_duration", 20);
String a = working_hours + " h";
txt1.setText(a);
String b = working_minutes + " m";
break_duration_mins.setText(b);
String c = break_duration + " m";
txt2.setText(c);
//Mathematics
double g = working_hours * 100;
double h = g + working_minutes;
double i = h + break_duration;
double j = i / 60;
double p = (int) j;
double q = j - p;
double r = q * 60;
without_break_hours = p;
without_break_minutes = r;
String d = without_break_hours + " h";
String e = without_break_minutes + " m";
text1.setText(d);
hmm.setText(e);
}
}
Code for Adapter Class :
package com.example.taskmasterv3;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import java.util.ArrayList;
public class SubtaskDetailAdapter extends ArrayAdapter<SubtaskPartTwo> {
private final Context context;
private ArrayList<SubtaskPartTwo> values;
public boolean deleted;
public SubtaskDetailAdapter(Context context, ArrayList<SubtaskPartTwo> list) {
//since your are using custom view,pass zero and inflate the custom view by overriding getview
super(context, 0 , list);
this.context = context;
this.values = list;
}
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
//check if its null, if so inflate it, else simply reuse it
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.task_summary_item, parent, false);
}
//use convertView to refer the childviews to populate it with data
TextView tvSubtaskName = convertView.findViewById(R.id.tvlolitaskname);
ImageView ivPri = convertView.findViewById(R.id.ivloliPri);
ImageView ivTime = convertView.findViewById(R.id.ivloliTime);
tvSubtaskName.setText(values.get(position).getSubtaskName());
if (values.get(position).getPri() == "h")
{
ivPri.setImageResource(R.drawable.priority_high);
}
if (values.get(position).getPri() == "m")
{
ivPri.setImageResource(R.drawable.priority_med);
}
if (values.get(position).getPri() == "l")
{
ivPri.setImageResource(R.drawable.priority_low);
}
if (values.get(position).getTime() == "more")
{
ivPri.setImageResource(R.drawable.time_symbol_more);
}
if (values.get(position).getPri() == "med")
{
ivPri.setImageResource(R.drawable.time_symbol_med);
}
if (values.get(position).getPri() == "less")
{
ivPri.setImageResource(R.drawable.time_symbol_less);
}
//return the view you inflated
return convertView;
}
//to keep adding the new subtasks try the following
public void addANewSubTask(SubtaskPartTwo newSubTask){
ArrayList<SubtaskPartTwo> newvalues = new ArrayList<>(this.values);
newvalues.add(newSubTask);
this.values = newvalues;
notifyDataSetChanged();
}
}
XML code for listview activity :
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.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:id="#+id/parent"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/background"
tools:context=".TaskSummary">
<!-- hello -->
<ScrollView
android:id="#+id/scrollView2"
android:layout_width="wrap_content"
android:layout_height="0dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<LinearLayout
android:id="#+id/okay"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="16dp"
android:orientation="vertical">
<ListView
android:id="#+id/lvTaskList"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="16dp">
</ListView>
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:orientation="horizontal">
<TextView
android:id="#+id/tvBreak"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="8dp"
android:fontFamily="#font/roboto"
android:text="Total Working Time (Including Breaks)"
android:textColor="#B8AEAE"
android:textSize="20sp" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:orientation="horizontal">
<TextView
android:id="#+id/txt1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_margin="8dp"
android:layout_weight="1"
android:fontFamily="#font/roboto"
android:gravity="right"
android:text="00 h"
android:textColor="#B8AEAE"
android:textSize="20sp" />
<TextView
android:id="#+id/break_duration_mins"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="8dp"
android:layout_marginRight="8dp"
android:layout_marginBottom="8dp"
android:layout_weight="1"
android:gravity="left"
android:text="20 m"
android:textColor="#B8AEAE"
android:textSize="20sp" />
</LinearLayout>
</LinearLayout>
<!-- hello -->
<!-- hello -->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="16dp"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:orientation="horizontal">
<TextView
android:id="#+id/tvWorktimeWithoutBreak"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="8dp"
android:fontFamily="#font/roboto"
android:text="Work Time Before Each Break"
android:textColor="#B8AEAE"
android:textSize="20sp" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:orientation="horizontal">
<TextView
android:id="#+id/text1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_margin="8dp"
android:layout_weight="1"
android:fontFamily="#font/roboto"
android:gravity="right"
android:text="00 h"
android:textColor="#B8AEAE"
android:textSize="20sp" />
<TextView
android:id="#+id/hmm"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="8dp"
android:layout_marginRight="8dp"
android:layout_marginBottom="8dp"
android:layout_weight="1"
android:gravity="left"
android:text="20 m"
android:textColor="#B8AEAE"
android:textSize="20sp" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
<!-- hello -->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<TextView
android:id="#+id/tvBreakAfterEvery"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="8dp"
android:layout_marginTop="8dp"
android:layout_marginRight="8dp"
android:layout_marginBottom="8dp"
android:fontFamily="#font/roboto"
android:text="Break Duration"
android:textColor="#B8AEAE"
android:textSize="20sp"
app:layout_constraintBottom_toTopOf="#+id/lvTaskList"
app:layout_constraintEnd_toStartOf="#+id/lvTaskList"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/txt2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="8dp"
android:fontFamily="#font/roboto"
android:gravity="center_horizontal"
android:text="30 m"
android:textColor="#B8AEAE"
android:textSize="20sp" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<Button
android:id="#+id/btnStart"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|center_horizontal"
android:layout_margin="16dp"
android:text="Start" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
</ScrollView>
</androidx.constraintlayout.widget.ConstraintLayout>
EDIT : Database Code
package com.example.taskmasterv3;
public class TaskInfo extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_task_info);
tvTaskName = findViewById(R.id.tvTaskName);
btnProceed = findViewById(R.id.btnProceed);
dbHelper = new DBHelper(this);
tvTaskName.setVisibility(View.INVISIBLE);
if (tvTaskName.getText().equals(""))
{
tvTaskName.setClickable(false);
}
else
{
tvTaskName.setClickable(true);
}
btnSaveTaskName.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
tvTaskName.setVisibility(View.VISIBLE);
tvTaskName.setText(etTaskName.getText().toString().toUpperCase().trim());
etTaskName.setVisibility(View.GONE);
btnSaveTaskName.setVisibility(View.GONE);
btnNewSubtask.setEnabled(true);
}
});
tvTaskName.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String tasksname = tvTaskName.getText().toString().trim();
tvTaskName.setText("");
etTaskName.setVisibility(View.VISIBLE);
etTaskName.setText(tasksname);
btnSaveTaskName.setVisibility(View.VISIBLE);
}
});
btnNewSubtask.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i2 = new Intent(TaskInfo.this, SubtaskActivity.class);
startActivityForResult(i2, ENTER_SUBTASK);
overridePendingTransition(R.anim.slide_in_up, R.anim.slide_out_up);
}
});
// THE DATABASE PART
btnProceed.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Cursor res = dbHelper.getdata();
while(res != null && res.moveToNext()){
subtname = res.getString(0);
pri = res.getString(1);
time = res.getString(2);
}
if (etWorkingHours.getText().toString().isEmpty())
{
etWorkingHours.setText("0");
}
if (etWorkingMinutes.getText().toString().isEmpty())
{
etWorkingMinutes.setText("0");
}
if (etWorkinghrs.getText().toString().isEmpty())
{
etWorkinghrs.setText("0");
}
if (etWorkingMins.getText().toString().isEmpty())
{
etWorkingMins.setText("0");
}
int working_hours = Integer.parseInt(etWorkinghrs.getText().toString().trim());
int working_minutes = Integer.parseInt(etWorkingMins.getText().toString().trim());
int without_break_hours = Integer.parseInt(etWorkingHours.getText().toString().trim());
int without_break_minutes = Integer.parseInt(etWorkingMinutes.getText().toString().trim());
if (etWorkingHours.getText().toString().isEmpty() || etWorkingMinutes.getText().toString().isEmpty() || etWorkinghrs.getText().toString().isEmpty() || etWorkingMins.getText().toString().isEmpty())
{
Toast.makeText(TaskInfo.this, "Field cannot be empty, please try again.", Toast.LENGTH_SHORT).show();
}
else
{
if (working_hours != 0)
{
if (working_hours > without_break_hours)
{
int breaktime = Integer.parseInt(tvBreakTime.getText().toString());
Intent intent = new Intent(TaskInfo.this, TaskSummary.class);
intent.putExtra("working_hours", working_hours);
intent.putExtra("working_minutes", working_minutes);
intent.putExtra("without_break_hours", without_break_hours);
intent.putExtra("without_break_minutes", without_break_minutes);
intent.putExtra("break_duration", breaktime);
intent.putExtra("subtaskname", taskName);
intent.putExtra("priigh", NpriHigh);
intent.putExtra("primed", NpriMed);
intent.putExtra("prilow", NpriLow);
intent.putExtra("timemore", NtimeMore);
intent.putExtra("timemed", NtimeMed);
intent.putExtra("timeless", NtimeLess);
startActivity(intent);
}
if (working_hours == without_break_hours){
if (working_minutes >= without_break_minutes){
int breaktime = Integer.parseInt(tvBreakTime.getText().toString());
Intent intent = new Intent(TaskInfo.this, TaskSummary.class);
intent.putExtra("working_hours", working_hours);
intent.putExtra("working_minutes", working_minutes);
intent.putExtra("without_break_hours", without_break_hours);
intent.putExtra("without_break_minutes", without_break_minutes);
intent.putExtra("break_duration", breaktime);
intent.putExtra("subtaskname", taskName);
intent.putExtra("priigh", NpriHigh);
intent.putExtra("primed", NpriMed);
intent.putExtra("prilow", NpriLow);
intent.putExtra("timemore", NtimeMore);
intent.putExtra("timemed", NtimeMed);
intent.putExtra("timeless", NtimeLess);
intent.putExtra("subtaskname", subtname);
intent.putExtra("pri", pri);
intent.putExtra("time", time);
startActivity(intent);
}
if (working_minutes < without_break_minutes){
Toast.makeText(TaskInfo.this, "Invalid Time Entered", Toast.LENGTH_SHORT).show();
}
}
if (working_hours < without_break_hours){
Toast.makeText(TaskInfo.this, "Invalid Time Entered", Toast.LENGTH_SHORT).show();
}
}
if (working_hours == 0){
if (without_break_hours == 0)
{
if (working_minutes >= without_break_minutes){
int breaktime = Integer.parseInt(tvBreakTime.getText().toString());
Intent intent = new Intent(TaskInfo.this, TaskSummary.class);
intent.putExtra("working_hours", working_hours);
intent.putExtra("working_minutes", working_minutes);
intent.putExtra("without_break_hours", without_break_hours);
intent.putExtra("without_break_minutes", without_break_minutes);
intent.putExtra("break_duration", breaktime);
intent.putExtra("subtaskname", taskName);
intent.putExtra("prihigh", NpriHigh);
intent.putExtra("primed", NpriMed);
intent.putExtra("prilow", NpriLow);
intent.putExtra("timemore", NtimeMore);
intent.putExtra("timemed", NtimeMed);
intent.putExtra("timeless", NtimeLess);
startActivity(intent);
}
if (working_minutes < without_break_minutes){
Toast.makeText(TaskInfo.this, "Invalid Time Entered", Toast.LENGTH_SHORT).show();
}
}
if (without_break_hours != 0)
{
Toast.makeText(TaskInfo.this, "Invalid Time Entered", Toast.LENGTH_SHORT).show();
}
}
}
}
});
boolean delete = getIntent().getBooleanExtra("deleted", false);
if (delete){
}
}
}
}
}
The problem is that you're creating a new ArrayList while the adapter is left using the old one. That's why notifyDataSetChanged() doesn't work because the adapter's backing list has not changed.
To fix this, update the values list directly
public void addANewSubTask(SubtaskPartTwo newSubTask) {
this.values.add(newSubTask);
notifyDataSetChanged();
}
or, add() through the adapter itself.
public void addANewSubTask(SubtaskPartTwo newSubTask) {
add(newSubTask);
notifyDataSetChanged();
}
Even if I add one item, it shows 2 (both the same)
It seems you're adding the new element twice:
SubtaskPartTwo subtaskPartTwo = new SubtaskPartTwo(subtname, pri, time);
subtaskList.add(subtaskPartTwo);
adapter.addANewSubTask(subtaskPartTwo);
Just add via adapter only as it notifies as well. Check other places too for such duplicates.
Hi i am developing an app where i have to make a ui like playtstore for that i saw this tutorial but now my problem is that i'm unable to add different
text for different rows and second is that even after setting height and width it doesnt seem to be get affected.
Please if someone can help me out here i'm stuck at this point
my code is as follows
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
int[] images = {R.drawable.vancouver,R.drawable.party,R.drawable.hands_ip,R.drawable.dj};
// Inflate the layout for this fragment
allSampleData = new ArrayList<SectionDataModel>();
createDummyData();
HorizontalAdapter firstAdapter = new HorizontalAdapter(images);
View view = inflater.inflate(R.layout.fragment_home, container, false);
NestedScrollView nestedScrollView = view.findViewById(R.id.scrollView);
llm = new LadderLayoutManager(1.5f, 0.85f, LadderLayoutManager.HORIZONTAL).
setChildDecorateHelper(new LadderLayoutManager
.DefaultChildDecorateHelper(getResources().getDimension(R.dimen.item_max_elevation)));
llm.setChildPeekSize((int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
30, getResources().getDisplayMetrics()));
//llm.setReverse(true);
/*llm.setMaxItemLayoutCount(5);
rcv = (RecyclerView) view.findViewById(R.id.rcv);
rcv.setLayoutManager(llm);
new LadderSimpleSnapHelper().attachToRecyclerView(rcv);
adapter = new HSAdapter();
rcv.setAdapter(adapter);
multi_scroll_recyclerview = (RecyclerView)view.findViewById(R.id.multi_scroll_recyclerview);
multi_scroll_recyclerview.setNestedScrollingEnabled(false);
multi_scroll_layout_manager = new LinearLayoutManager(getActivity(),LinearLayoutManager.VERTICAL,false);
multi_scroll_recyclerview.setLayoutManager(multi_scroll_layout_manager);
multi_scroll_adapter = new RecyclerViewDataAdapter(getActivity(),allSampleData);
multi_scroll_recyclerview.setAdapter(multi_scroll_adapter);
multi_scroll_recyclerview.setHasFixedSize(true);*/
/* MultiSnapRecyclerView firstRecyclerView = (MultiSnapRecyclerView)view.findViewById(R.id.first_recycler_view);
LinearLayoutManager firstManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.HORIZONTAL, false);
firstRecyclerView.setLayoutManager(firstManager);
firstRecyclerView.setAdapter(firstAdapter);
HorizontalAdapter secondAdapter = new HorizontalAdapter(images);
MultiSnapRecyclerView secondRecyclerView =(MultiSnapRecyclerView) view.findViewById(R.id.second_recycler_view);
LinearLayoutManager secondManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.HORIZONTAL, false);
secondRecyclerView.setLayoutManager(secondManager);
secondRecyclerView.setAdapter(secondAdapter);
HorizontalAdapter thirdAdapter = new HorizontalAdapter(images);
MultiSnapRecyclerView thirdRecyclerView = (MultiSnapRecyclerView)view.findViewById(R.id.third_recycler_view);
LinearLayoutManager thirdManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.HORIZONTAL, false);
thirdRecyclerView.setLayoutManager(thirdManager);
thirdRecyclerView.setAdapter(thirdAdapter);*/
return view;
}
public void createDummyData() {
for (int i = 1; i <= 5; i++) {
SectionDataModel dm = new SectionDataModel();
dm.setHeaderTitle("Clubs");
dm.setHeadertitle2("Lounge");
dm.setHeadertitle3("Cafe");
dm.setHeadertitle4("Rooftop");
ArrayList<SingleItemModel> singleItem = new ArrayList<SingleItemModel>();
for (int j = 0; j <= 5; j++) {
singleItem.add(new SingleItemModel("Item " + j, "URL " + j));
}
dm.setAllItemsInSection(singleItem);
allSampleData.add(dm);//line which is causing issue
}
}
code for adapter
public class SectionListDataAdapter extends RecyclerView.Adapter<SectionListDataAdapter.SingleItemRowHolder> {
private ArrayList<SingleItemModel> itemsList;
private Context mContext;
public SectionListDataAdapter(Context context, ArrayList<SingleItemModel> itemsList) {
this.itemsList = itemsList;
this.mContext = context;
}
#Override
public SingleItemRowHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.list_single_card, null);
SingleItemRowHolder mh = new SingleItemRowHolder(v);
return mh;
}
#Override
public void onBindViewHolder(SingleItemRowHolder holder, int i) {
SingleItemModel singleItem = itemsList.get(i);
holder.tvTitle.setText(singleItem.getName());
/* Glide.with(mContext)
.load(feedItem.getImageURL())
.diskCacheStrategy(DiskCacheStrategy.ALL)
.centerCrop()
.error(R.drawable.bg)
.into(feedListRowHolder.thumbView);*/
}
#Override
public int getItemCount() {
return (null != itemsList ? itemsList.size() : 0);
}
public class SingleItemRowHolder extends RecyclerView.ViewHolder {
protected TextView tvTitle;
protected ImageView itemImage;
public SingleItemRowHolder(View view) {
super(view);
this.tvTitle = (TextView) view.findViewById(R.id.tvTitle);
this.itemImage = (ImageView) view.findViewById(R.id.itemImage);
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Toast.makeText(v.getContext(), tvTitle.getText(), Toast.LENGTH_SHORT).show();
}
});
}
}
}
My code for model class
public class SectionDataModel {
private String headerTitle,headertitle2,headertitle3,headertitle4;
private ArrayList<SingleItemModel> allItemsInSection;
public SectionDataModel() {
}
public SectionDataModel(String headerTitle, ArrayList<SingleItemModel> allItemsInSection) {
this.headerTitle = headerTitle;
this.allItemsInSection = allItemsInSection;
}
public String getHeaderTitle() {
return headerTitle;
}
public String getHeadertitle2() {
return headertitle2;
}
public String getHeadertitle3() {
return headertitle3;
}
public String getHeadertitle4() {
return headertitle4;
}
public void setHeaderTitle(String headerTitle) {
this.headerTitle = headerTitle;
}
public void setHeadertitle2(String headertitle2) {
this.headertitle2 = headertitle2;
}
public void setHeadertitle3(String headertitle3) {
this.headertitle3 = headertitle3;
}
public void setHeadertitle4(String headertitle4) {
this.headertitle4 = headertitle4;
}
public ArrayList<SingleItemModel> getAllItemsInSection() {
return allItemsInSection;
}
public void setAllItemsInSection(ArrayList<SingleItemModel> allItemsInSection) {
this.allItemsInSection = allItemsInSection;
}
}
listitem.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?android:selectableItemBackground"
android:orientation="vertical"
android:padding="5dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<com.ct.listrtrial.Custom.CustomTextViewMedium
android:id="#+id/itemTitle"
android:layout_width="0dp"
android:layout_weight="8"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_centerVertical="true"
android:layout_gravity="center_vertical"
android:layout_toLeftOf="#+id/btnMore"
android:text="Sample title"
android:textColor="#android:color/white"
android:textSize="27sp" />
<ImageView
android:id="#+id/btnMore"
android:layout_width="0dp"
android:layout_weight="0.8"
android:layout_marginTop="13dp"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:background="#drawable/ic_more_horiz_black_24dp"
android:textColor="#FFF" />
</LinearLayout>
<android.support.v7.widget.RecyclerView
android:id="#+id/recycler_view_list"
android:layout_width="match_parent"
android:layout_marginTop="10dp"
android:layout_height="160dp"
android:layout_gravity="center_vertical"
android:orientation="horizontal" />
</LinearLayout>
main fragment.xml
<android.support.v4.widget.NestedScrollView android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/scrollView"
android:fillViewport="true"
android:background="#color/colorPrimary"
xmlns:android="http://schemas.android.com/apk/res/android">
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.v7.widget.RecyclerView
android:id="#+id/rcv"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_gravity="center_horizontal"
android:layout_weight="1"
android:paddingBottom="10dp"
android:paddingTop="10dp" />
<android.support.v7.widget.RecyclerView
android:id="#+id/multi_scroll_recyclerview"
android:layout_width="wrap_content"
android:layout_height="0dp"
android:layout_weight="1">
</android.support.v7.widget.RecyclerView>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
</LinearLayout>
</LinearLayout>
</android.support.v4.widget.NestedScrollView>
listsinglecard.xml
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="220dp"
android:layout_marginLeft="18dp"
android:layout_height="200dp"
app:cardCornerRadius="65dp"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?android:selectableItemBackground"
android:orientation="vertical">
<ImageView
android:id="#+id/itemImage"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center_horizontal"
android:scaleType="centerCrop"
android:src="#drawable/vancouver" />
<TextView
android:id="#+id/tvTitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/itemImage"
android:gravity="center"
android:padding="5dp"
android:visibility="gone"
android:text="Sample title"
android:textColor="#android:color/black"
android:textSize="18sp" />
</LinearLayout>
</android.support.v7.widget.CardView>
I'm creating a simple little game to practice my coding but I've stumbled into a problem. It's not game breaking but it's certainly annoying. In my game, I have a class Tappable which is what my ListView is populated with. Every time you tap on a ListView element, my OnItemClickListener just adds 1 to the amount you have of a Tappable.
Long story short, I use a custom ArrayAdapter and I have AsyncTask running on a loop with handlers in order to calculate how much money you are making. This implementation of a timed AsyncTask was done so I could put calculations on another thread and then update the UI onPostExecute. However, when I tap on a ListView element, some taps are completely ignored. This happens more severely the lower the interval is between the timed AsyncTasks.
Here is my MainActivity.java
import android.os.AsyncTask;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.Locale;
public class MainActivity extends AppCompatActivity {
TextView moneyView;
ListView tappablesView;
ArrayList<Tappable> tappables = new ArrayList<>();
TappableAdapter tappableAdapter;
double money = 0; // Total amount of money you have
double time; // Var to do checks on the amount of time to finish AsyncTask
// Here is the stuff that I use as my Timer.
int millisecondsToDelay = 30;
Handler handler = new Handler();
public class WorldUpdater extends AsyncTask<Void, Integer, Double> {
#Override
protected void onPreExecute() {
super.onPreExecute();
//This is for checking how long it takes my Tasks to complete
time = System.currentTimeMillis();
}
#Override
protected Double doInBackground(Void... params) {
// Var to hold amount to add to money
double moneyAddable = 0;
// Go through the tappables arraylist
for (int i = 0; i < tappables.size(); i++) {
Tappable t = tappables.get(i);
// increase the progress to a payout for a tappable
if (t.getAmount() > 0) {
t.updateProgress();
}
// add any money that can be collected to moneyAddable
moneyAddable += t.collectMoney();
}
// To be processed in onPostExecute
return moneyAddable;
}
#Override
protected void onPostExecute(Double m) {
super.onPostExecute(m);
// add the moneyAddable from doInBackground to the amount of money you have
money += m;
// Set the moneyView text to show how much money you have
updateMoneyView();
// Tappable progress increased, so show that in the list view
tappableAdapter.notifyDataSetChanged();
// Now we see how long the task took
time = System.currentTimeMillis() - time;
// If the task took longer than the amount I want it to delay, then say how long it took
if (time > millisecondsToDelay) {
Log.i("Timer info", "Too long: " + time);
}
handler.postDelayed(new Runnable() {
#Override
public void run() {
new WorldUpdater().execute();
}
}, (((long) (millisecondsToDelay - time)) > 0)? (long) (millisecondsToDelay - time): (long) 0);
}
}
public void updateMoneyView() {
moneyView.setText(String.format(Locale.getDefault(), "$%,.2f", money));
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
moneyView = (TextView) findViewById(R.id.Money);
tappablesView = (ListView) findViewById(R.id.TappablesView);
// The two tappables in the listview
tappables.add(new Tappable("Buy me!", .25, 1, 1500));
tappables.add(new Tappable("Buy me as well!", 1, 2.25, 1000));
tappableAdapter = new TappableAdapter(this, tappables);
tappablesView.setAdapter(tappableAdapter);
tappablesView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// On item click, increase the amount of the tappable that was clicked by 1
tappables.get(position).buyAmount(1);
}
});
updateMoneyView();
// Start my timer
handler.postDelayed(new Runnable() {
#Override
public void run() {
new WorldUpdater().execute();
}
}, millisecondsToDelay);
}
#Override
protected void onDestroy() {
super.onDestroy();
handler.removeCallbacksAndMessages(null);
}
}
Here is my Tappable.java
public class Tappable {
private String title;
private double revenue, cost, revenuePerItem, costPerItem;
private int progress, progressNeeded, progressStep, amount;
private boolean canCollect = false;
private double amountToCollect = 0;
public Tappable(String title, double r, double c, int ps) {
this.title = title;
revenuePerItem = r;
amount = 0;
revenue = revenuePerItem * amount;
costPerItem = c;
cost = costPerItem * (amount + 1);
progressNeeded = 100000;
progress = 0;
progressStep = ps;
}
public void buyAmount(int n) {
amount += n;
updateCost();
updateRevenue();
}
public void updateProgress() {
progress += progressStep;
if (progress >= progressNeeded) {
progress = 0;
amountToCollect += getRevenue();
canCollect = true;
}
}
public double collectMoney() {
double amountCollectable = 0;
if (canCollect) {
amountCollectable = amountToCollect;
amountToCollect = 0;
canCollect = false;
}
return amountCollectable;
}
public void updateCost() {
cost = costPerItem * (amount + 1);
}
public void updateRevenue() {
revenue = revenuePerItem * amount;
}
public String getTitle() {
return title;
}
public int getAmount() {
return amount;
}
public double getCost() {
return cost;
}
public int getProgress() {
return progress;
}
public int getProgressNeeded() {
return progressNeeded;
}
public double getRevenue() {
return revenue;
}
}
Here is my TappableAdapter.java
import android.app.Activity;
import android.content.res.Resources;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ProgressBar;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.Locale;
public class TappableAdapter extends BaseAdapter {
private final Activity context;
private final ArrayList<Tappable> tappables;
private final Resources res;
private final LayoutInflater inflater;
public TappableAdapter(Activity context, ArrayList<Tappable> t) {
this.context = context;
tappables = t;
res = context.getResources();
inflater = context.getLayoutInflater();
}
#Override
public int getCount() {
return tappables.size();
}
#Override
public Object getItem(int position) {
return tappables.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Tappable t = tappables.get(position);
View rowView = inflater.inflate(R.layout.list_item, null, true);
TextView titleView, amountView, costView, revenueView;
titleView = (TextView) rowView.findViewById(R.id.Title);
amountView = (TextView) rowView.findViewById(R.id.Amount);
costView = (TextView) rowView.findViewById(R.id.Cost);
revenueView = (TextView) rowView.findViewById(R.id.Revenue);
ProgressBar p = (ProgressBar) rowView.findViewById(R.id.progressBar);
titleView.setText(t.getTitle());
amountView.setText("Amount: " + t.getAmount());
costView.setText(String.format(Locale.getDefault(), "$%,.2f", t.getCost()));
revenueView.setText(String.format(Locale.getDefault(), "$%,.2f", t.getRevenue()));
p.setMax(t.getProgressNeeded());
p.setProgress(t.getProgress());
return rowView;
}
}
Here is my activity_main.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="com.jake.mypointclicker.MainActivity">
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginTop="8dp"
android:text="Simple Point Clicker"
android:textColor="#android:color/background_light"
android:textSize="36sp"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:layout_marginStart="8dp"
android:layout_marginEnd="8dp"
app:layout_constraintVertical_weight="0" />
<TextView
android:id="#+id/Money"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="8dp"
android:layout_marginTop="8dp"
android:text="$123,456,789.00"
android:textColor="#android:color/holo_orange_dark"
android:textSize="30sp"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toBottomOf="#+id/textView"
android:layout_marginEnd="8dp"
app:layout_constraintVertical_weight="0" />
<Button
android:id="#+id/button"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginTop="8dp"
android:text="Button"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toBottomOf="#+id/Money"
android:layout_marginStart="8dp"
android:layout_marginEnd="8dp"
app:layout_constraintVertical_weight="0" />
<LinearLayout
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_marginBottom="8dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginTop="8dp"
android:orientation="vertical"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toBottomOf="#+id/button"
app:layout_constraintVertical_weight="0">
<ListView
android:id="#+id/TappablesView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
</android.support.constraint.ConstraintLayout>
Here is my list_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="wrap_content"
android:background="#android:color/black"
android:orientation="vertical"
android:padding="8dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:id="#+id/Title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="top|left"
android:text="Test Title"
android:textColor="#android:color/holo_blue_light"
android:textSize="20sp" />
<TextView
android:id="#+id/Revenue"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="top|right"
android:text="$123,456,789.00"
android:textColor="#android:color/holo_green_light"
android:textSize="20sp" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:id="#+id/Amount"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="top|left"
android:text="Amount: 123456789" />
<TextView
android:id="#+id/Cost"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="top|right"
android:text="$123,456,789.00"
android:textColor="#android:color/holo_red_light"
android:textSize="20sp" />
</LinearLayout>
<ProgressBar
android:id="#+id/progressBar"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
I have tried many ways of doing my timer. I tried just using Timer with a timertask which had the same effect. Line 25 or so is where my variable for how long to delay is. Lowering that increases the amount of clicks that are ignored. Raising it has the inverse effect but makes the progress bars look less smooth. Like I said, it's not a game braking problem, but I don't understand why the onItemClick is not called sometimes when I try updating the UI frequently. Is the Listener itself on the UI thread and it is being blocked when I update the UI in my AsyncTask?
I'm working on a calculator app for my class project in school, but there seem to be some errors behind the scenes that are not syntax-based. I try to run my app it crashes. I have been unable to find my error but it always crashes after I hit the submit button. I haven't had an app just completely refuse to run.
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.stins.calculator">
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name="com.example.stins.calculator.MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
</application>
MainActivity.java
package com.example.stins.calculator;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import com.example.stins.calculator.Calculator;
import com.example.stins.calculator.CalculatorImpl;
import com.example.stins.calculator.Config;
import com.example.stins.calculator.Constants;
import com.example.stins.calculator.Formatter;
import com.example.stins.calculator.R;
import com.example.stins.calculator.Utils;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.OnLongClick;
import me.grantland.widget.AutofitHelper;
public class MainActivity extends SimpleActivity implements Calculator {#BindView(R.id.result)
TextView mResult;#BindView(R.id.formula)
TextView mFormula;
private static CalculatorImpl mCalc;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
CalculatorImpl calc = new CalculatorImpl(this);
AutofitHelper.create(mResult);
AutofitHelper.create(mFormula);
}
#OnClick(R.id.btn_plus)
public void plusClicked() {
mCalc.handleOperation(Constants.PLUS);
}
#OnClick(R.id.btn_minus)
public void minusClicked() {
mCalc.handleOperation(Constants.MINUS);
}
#OnClick(R.id.btn_multiply)
public void multiplyClicked() {
mCalc.handleOperation(Constants.MULTIPLY);
}
#OnClick(R.id.btn_divide)
public void divideClicked() {
mCalc.handleOperation(Constants.DIVIDE);
}
#OnClick(R.id.btn_modulo)
public void moduloClicked() {
mCalc.handleOperation(Constants.MODULO);
}
#OnClick(R.id.btn_power)
public void powerClicked() {
mCalc.handleOperation(Constants.POWER);
}
#OnClick(R.id.btn_root)
public void rootClicked() {
mCalc.handleOperation(Constants.ROOT);
}
#OnClick(R.id.btn_clear)
public void clearClicked() {
mCalc.handleClear();
}
#OnLongClick(R.id.btn_clear)
public boolean clearLongClicked() {
mCalc.handleReset();
return true;
}
#OnClick(R.id.btn_equals)
public void equalsClicked() {
mCalc.handleEquals();
}
#OnClick({
R.id.btn_decimal,
R.id.btn_0,
R.id.btn_1,
R.id.btn_2,
R.id.btn_3,
R.id.btn_4,
R.id.btn_5,
R.id.btn_6,
R.id.btn_7,
R.id.btn_8,
R.id.btn_9
})
public void numpadClick(View view) {
numpadClicked(view.getId());
}
public void numpadClicked(int id) {
mCalc.numpadClicked(id);
}
#Override
public void setValue(String value) {
mResult.setText(value);
}
// used only by Robolectric
#Override
public void setValueDouble(double d) {
mCalc.setValue(Formatter.doubleToString(d));
mCalc.setLastKey(Constants.DIGIT);
}
public void setFormula(String value) {
mFormula.setText(value);
}
public CalculatorImpl getCalc() {
return mCalc;
}
}
CalcImpl.java
package com.example.stins.calculator;
public class CalculatorImpl {
private String mDisplayedValue;
private String mDisplayedFormula;
private String mLastKey;
private String mLastOperation;
private Calculator mCallback;
private boolean mIsFirstOperation;
private boolean mResetValue;
private double mBaseValue;
private double mSecondValue;
public CalculatorImpl(Calculator calculator) {
mCallback = calculator;
resetValues();
setValue("0");
setFormula("");
}
public CalculatorImpl(Calculator calculatorInterface, String value) {
mCallback = calculatorInterface;
resetValues();
mDisplayedValue = value;
setFormula("");
}
private void resetValueIfNeeded() {
if (mResetValue) mDisplayedValue = "0";
mResetValue = false;
}
private void resetValues() {
mBaseValue = 0;
mSecondValue = 0;
mResetValue = false;
mLastKey = "";
mLastOperation = "";
mDisplayedValue = "";
mDisplayedFormula = "";
mIsFirstOperation = true;
}
public void setValue(String value) {
mCallback.setValue(value);
mDisplayedValue = value;
}
private void setFormula(String value) {
mCallback.setFormula(value);
mDisplayedFormula = value;
}
private void updateFormula() {
final String first = Formatter.doubleToString(mBaseValue);
final String second = Formatter.doubleToString(mSecondValue);
final String sign = getSign(mLastOperation);
if (sign.equals("√")) {
setFormula(sign + first);
} else if (!sign.isEmpty()) {
setFormula(first + sign + second);
}
}
public void setLastKey(String mLastKey) {
this.mLastKey = mLastKey;
}
public void addDigit(int number) {
final String currentValue = getDisplayedNumber();
final String newValue = formatString(currentValue + number);
setValue(newValue);
}
private String formatString(String str) {
// if the number contains a decimal, do not try removing the leading zero anymore, nor add group separator
// it would prevent writing values like 1.02
if (str.contains(".")) return str;
final double doubleValue = Formatter.stringToDouble(str);
return Formatter.doubleToString(doubleValue);
}
private void updateResult(double value) {
setValue(Formatter.doubleToString(value));
mBaseValue = value;
}
public String getDisplayedNumber() {
return mDisplayedValue;
}
public double getDisplayedNumberAsDouble() {
return Formatter.stringToDouble(getDisplayedNumber());
}
public String getDisplayedFormula() {
return mDisplayedFormula;
}
public void handleResult() {
mSecondValue = getDisplayedNumberAsDouble();
calculateResult();
mBaseValue = getDisplayedNumberAsDouble();
}
public void calculateResult() {
if (!mIsFirstOperation) updateFormula();
switch (mLastOperation) {
case Constants.PLUS:
updateResult(mBaseValue + mSecondValue);
break;
case Constants.MINUS:
updateResult(mBaseValue - mSecondValue);
break;
case Constants.MULTIPLY:
updateResult(mBaseValue * mSecondValue);
break;
case Constants.DIVIDE:
divideNumbers();
break;
case Constants.MODULO:
moduloNumbers();
break;
case Constants.POWER:
powerNumbers();
break;
case Constants.ROOT:
updateResult(Math.sqrt(mBaseValue));
break;
default:
break;
}
mIsFirstOperation = false;
}
private void divideNumbers() {
double resultValue = 0;
if (mSecondValue != 0) resultValue = mBaseValue / mSecondValue;
updateResult(resultValue);
}
private void moduloNumbers() {
double resultValue = 0;
if (mSecondValue != 0) resultValue = mBaseValue % mSecondValue;
updateResult(resultValue);
}
private void powerNumbers() {
double resultValue = Math.pow(mBaseValue, mSecondValue);
if (Double.isInfinite(resultValue) || Double.isNaN(resultValue)) resultValue = 0;
updateResult(resultValue);
}
public void handleOperation(String operation) {
if (mLastKey.equals(Constants.DIGIT)) handleResult();
mResetValue = true;
mLastKey = operation;
mLastOperation = operation;
if (operation.equals(Constants.ROOT)) calculateResult();
}
public void handleClear() {
final String oldValue = getDisplayedNumber();
String newValue = "0";
final int len = oldValue.length();
int minLen = 1;
if (oldValue.contains("-")) minLen++;
if (len > minLen) newValue = oldValue.substring(0, len - 1);
newValue = newValue.replaceAll("\\.$", "");
newValue = formatString(newValue);
setValue(newValue);
mBaseValue = Formatter.stringToDouble(newValue);
}
public void handleReset() {
resetValues();
setValue("0");
setFormula("");
}
public void handleEquals() {
if (mLastKey.equals(Constants.EQUALS)) calculateResult();
if (!mLastKey.equals(Constants.DIGIT)) return;
mSecondValue = getDisplayedNumberAsDouble();
calculateResult();
mLastKey = Constants.EQUALS;
}
public void decimalClicked() {
String value = getDisplayedNumber();
if (!value.contains(".")) value += ".";
setValue(value);
}
public void zeroClicked() {
String value = getDisplayedNumber();
if (!value.equals("0")) addDigit(0);
}
private String getSign(String lastOperation) {
switch (lastOperation) {
case Constants.PLUS:
return "+";
case Constants.MINUS:
return "-";
case Constants.MULTIPLY:
return "*";
case Constants.DIVIDE:
return "/";
case Constants.MODULO:
return "%";
case Constants.POWER:
return "^";
case Constants.ROOT:
return "√";
}
return "";
}
public void numpadClicked(int id) {
if (mLastKey.equals(Constants.EQUALS)) mLastOperation = Constants.EQUALS;
mLastKey = Constants.DIGIT;
resetValueIfNeeded();
switch (id) {
case R.id.btn_decimal:
decimalClicked();
break;
case R.id.btn_0:
zeroClicked();
break;
case R.id.btn_1:
addDigit(1);
break;
case R.id.btn_2:
addDigit(2);
break;
case R.id.btn_3:
addDigit(3);
break;
case R.id.btn_4:
addDigit(4);
break;
case R.id.btn_5:
addDigit(5);
break;
case R.id.btn_6:
addDigit(6);
break;
case R.id.btn_7:
addDigit(7);
break;
case R.id.btn_8:
addDigit(8);
break;
case R.id.btn_9:
addDigit(9);
break;
default:
break;
}
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
android:id="#+id/calculator_holder"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.stins.calculator.MainActivity">
<TextView
android:id="#+id/formula"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="2.1"
android:fontFamily="sans-serif-light"
android:gravity="right|bottom"
android:maxLines="1"
android:paddingLeft="#dimen/activity_margin"
android:paddingRight="#dimen/activity_margin"
android:textSize="#dimen/formula_text_size"/>
<TextView
android:id="#+id/result"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1.8"
android:fontFamily="sans-serif-light"
android:gravity="center_vertical|right"
android:maxLines="1"
android:paddingLeft="#dimen/activity_margin"
android:paddingRight="#dimen/activity_margin"
android:text="0"
android:textSize="#dimen/display_text_size"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="2"
android:orientation="horizontal">
<Button
android:id="#+id/btn_modulo"
style="#style/MyButton"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="mod"
android:textAllCaps="false"
android:textSize="#dimen/mod_text_size"/>
<Button
android:id="#+id/btn_power"
style="#style/MyButton"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="^"/>
<Button
android:id="#+id/btn_root"
style="#style/MyButton"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="√"/>
<Button
android:id="#+id/btn_clear"
style="#style/MyButton"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="C"/>
<Button
android:id="#+id/btn_reset"
style="#style/MyButton"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="AC"
android:visibility="gone"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="2"
android:orientation="horizontal">
<Button
android:id="#+id/btn_7"
style="#style/MyButton"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="7"/>
<Button
android:id="#+id/btn_8"
style="#style/MyButton"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="8"/>
<Button
android:id="#+id/btn_9"
style="#style/MyButton"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="9"/>
<Button
android:id="#+id/btn_divide"
style="#style/MyButton"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="÷"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="2"
android:orientation="horizontal">
<Button
android:id="#+id/btn_4"
style="#style/MyButton"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="4"/>
<Button
android:id="#+id/btn_5"
style="#style/MyButton"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="5"/>
<Button
android:id="#+id/btn_6"
style="#style/MyButton"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="6"/>
<Button
android:id="#+id/btn_multiply"
style="#style/MyButton"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="*"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="2"
android:orientation="horizontal">
<Button
android:id="#+id/btn_1"
style="#style/MyButton"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="1"/>
<Button
android:id="#+id/btn_2"
style="#style/MyButton"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="2"/>
<Button
android:id="#+id/btn_3"
style="#style/MyButton"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="3"/>
<Button
android:id="#+id/btn_minus"
style="#style/MyButton"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="-"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="2"
android:orientation="horizontal">
<Button
android:id="#+id/btn_0"
style="#style/MyButton"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="0"/>
<Button
android:id="#+id/btn_decimal"
style="#style/MyButton"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="."/>
<Button
android:id="#+id/btn_equals"
style="#style/MyButton"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="="/>
<Button
android:id="#+id/btn_plus"
style="#style/MyButton"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="+"/>
</LinearLayout>
</LinearLayout>
logcat
02-11 14:27:36.485 5006-5006/com.example.stins.calculator E/AndroidRuntime:
FATAL EXCEPTION: main
Process: com.example.stins.calculator, PID: 5006
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.stins.calculator/com.example.stins.calculator.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.widget.TextView.getContext()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.widget.TextView.getContext()' on a null object reference
at me.grantland.widget.AutofitHelper.<init>(AutofitHelper.java:246)
at me.grantland.widget.AutofitHelper.create(AutofitHelper.java:62)
at me.grantland.widget.AutofitHelper.create(AutofitHelper.java:46)
at com.example.stins.calculator.MainActivity.onCreate(MainActivity.java:40)
at android.app.Activity.performCreate(Activity.java:6237)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
If at all possible, would anyone know how to help ?
I included my logcat as well
Check to make sure that you have the annotationProcessor for butterknife setup in your build.gradle. You should have a line under dependencies that looks like this:
annotationProcessor 'com.jakewharton:butterknife-compiler:8.5.1'.
After you add that run build->rebuild project.
This View is supposed to make a Button for each LinearLayout inside itself, and put that LinearLayout inside a ScrollView. I think the problem is that the LinearLayouts don't exist yet, since they are created AFTER initializing this view. Therefore getChildCound() returns zero. You could work around this by hard coding the number of Buttons or getting it from a XML attribute, but you can't put the LinearLayouts in the ScrollViews, when there are no LinearLayouts. Is there a way to work around this?
code:
package mika.actual;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import java.util.ArrayList;
public class AccordionWidget extends LinearLayout{
public AccordionWidget(Context c, AttributeSet attrs) {
super(c, attrs);
final Context context = c;
final int count = this.getChildCount();
TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.accordion);
String[] btns = getResources().getStringArray(R.array.buttons);
ArrayList<LinearLayout> lls = new ArrayList <> (count);
for(int i = 0; i < count; i++){
View child = this.getChildAt(i);
if (child instanceof LinearLayout) {
lls.add((LinearLayout)child);
}
}
for(int i = 0; i < lls.size(); i++){
if(btns[i] == null){
Log.e("error: ", "Please add more Button lables to the strings.xml file.");
}
final Button btn = new Button(context);
final LinearLayout ll = lls.get(i);
final ScrollView sv = new ScrollView(context);
final int col_pressed = a.getColor(R.styleable.accordion_backgroundColorPressed, Color.BLACK);
final int col_unpressed = a.getColor(R.styleable.accordion_backgroundColorUnpressed, Color.YELLOW); //Black and yellow, black and yellow...
LayoutParams btnparams = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
LayoutParams swparams = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
LayoutParams llparams = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
btn.setText(btns[i]);
btn.setBackgroundColor(col_pressed);
llparams.weight = 1f;
btn.setLayoutParams(btnparams);
ll.setLayoutParams(llparams);
sv.setLayoutParams(swparams);
ll.setOrientation(LinearLayout.VERTICAL);
sv.setVisibility(View.GONE);
this.addView(sv);
this.addView(btn);
sv.addView(ll);
btn.setOnClickListener(new OnClickListener() {
private boolean btnstate = false;
#Override
public void onClick(View v) {
if (btnstate) {
btn.setBackgroundColor(col_pressed);
sv.setVisibility(View.VISIBLE);
btnstate = true;
} else {
btn.setBackgroundColor(col_unpressed);
sv.setVisibility(View.GONE);
btnstate = false;
}
}
});
}
a.recycle();
}
}
XML:
<?xml version="1.0" encoding="utf-8"?>
<mika.actual.AccordionWidget
xmlns:accordion="http://schemas.android.com/apk/res-auto"
xmlns:android="http://schemas.android.com/apk/res/android"
accordion:text_color="#color/text_color"
accordion:backgroundColorPressed="#color/button_pressed"
accordion:backgroundColorUnpressed="#color/button_not_pressed"
android:id="#+id/swaggy"
android:layout_height="match_parent"
android:layout_width="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="yolooooo yooo"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="yolooooo yooo"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="yolooooo yooo"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="yolooooo yooo"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="yolooooo yooo"/>
</LinearLayout>
</mika.actual.AccordionWidget>
The idea is that you need to put your logic into onLayout
Something like this:
#Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
final Context context = c;
final int count = this.getChildCount();
TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.accordion);
String[] btns = getResources().getStringArray(R.array.buttons);
ArrayList<LinearLayout> lls = new ArrayList <> (count);
for(int i = 0; i < count; i++){
View child = this.getChildAt(i);
if (child instanceof LinearLayout) {
lls.add((LinearLayout)child);
}
}
.......
See this
Make sure that you call child.layout() for each child inside this method.
You can create custom LinearLayout inside ScrollView:
<ScrollView>
<LinearLayout android:id="#+id/parent"/>
</ScrollView>
Then Create java class for your layout and inflate it.
See this