Previously I had crash issues due to the wrong reference to the resource files. Fixed that issue and updated this thread with the logical error that I am getting.
I am new to android and currently learning custom classes and adapter. While working I am facing a problem which is the listview shows the first arraylist item only.
I have attached the codes of the required files as well.
Working Activity
package np.com.shresthakiran.tourswoniga;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ListView;
import java.util.ArrayList;
public class KhowpaActivity extends AppCompatActivity {
ListView lvHeritageList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listview_heritage);
lvHeritageList = findViewById(R.id.lvHeritage);
ArrayList<Heritages> heritageAryList = new ArrayList<>();
heritageAryList.add(new Heritages(R.drawable.ic_launcher_background,"Ngatapol", "Taumadi"));
heritageAryList.add(new Heritages(R.drawable.ic_launcher_foreground, "Dattatreya", "Taumadi"));
heritageAryList.add(new Heritages(R.drawable.ic_launcher_foreground, "Lu dhwakha", "Lyaaku"));
heritageAryList.add(new Heritages(R.drawable.ic_launcher_foreground, "55 jhyale Durbar", "Lyaaku"));
heritageAryList.add(new Heritages(R.drawable.ic_launcher_foreground, "Taleju Bhawani", "Lyaaku"));
HeritageAdapter heritageAdapter = new HeritageAdapter(KhowpaActivity.this, R.layout.heritages_row, heritageAryList);
lvHeritageList.setAdapter(heritageAdapter);
}
}
Custom Adapter
package np.com.shresthakiran.tourswoniga;
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 HeritageAdapter extends ArrayAdapter<Heritages> {
private Context mContext;
private int mResource;
public HeritageAdapter(#NonNull Context context, int resource, #NonNull ArrayList<Heritages> objects) {
super(context, resource, objects);
this.mContext = context;
this.mResource = resource;
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
LayoutInflater layoutInflater =LayoutInflater.from(mContext);
convertView = layoutInflater.inflate(mResource, parent, false);
ImageView ivHeritageImage = convertView.findViewById(R.id.ivHeritage);
TextView tvHeritageName = convertView.findViewById(R.id.tvHeritageName);
TextView tvHeritageAddress = convertView.findViewById(R.id.tvHeritageAddress);
ivHeritageImage.setImageResource(getItem(position).getmImageResourceId());
tvHeritageName.setText(getItem(position).getmHeritageName());
tvHeritageAddress.setText(getItem(position).getmHeritageAddress());
return convertView;
}
}
Object Class
package np.com.shresthakiran.tourswoniga;
public class Heritages {
private int mImageResourceId;
private String mHeritageName;
private String mHeritageAddress;
public Heritages(int heritageImageResourceId, String heritageName, String heritageAddress) {
this.mImageResourceId = heritageImageResourceId;
this.mHeritageName = heritageName;
this.mHeritageAddress = heritageAddress;
}
public int getmImageResourceId() {
return mImageResourceId;
}
public String getmHeritageName() {
return mHeritageName;
}
public String getmHeritageAddress() {
return mHeritageAddress;
}
}
ListView XML
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="100dp"
android:minHeight="100dp">
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/lvHeritage">
</ListView>
</RelativeLayout>
List Row XML
<?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"
android:orientation="horizontal"
android:weightSum="100"
android:layout_margin="10dp">
<ImageView
android:id="#+id/ivHeritage"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="33.33"
android:padding="2dp"
android:text="Ngatapol"
android:layout_marginTop="7dp"
android:src="#mipmap/ic_launcher"/>
<LinearLayout
android:id="#+id/llHeritageInfo"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_weight="66.66"
android:padding="8dp" >
<TextView
android:id="#+id/tvHeritageName"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:textSize="18sp"
android:textStyle="bold"
android:text="Ngatapol"
android:textAppearance="?android:textAppearanceMedium"
android:padding="2dp"/>
<TextView
android:id="#+id/tvHeritageAddress"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:textSize="18sp"
android:text="Taumadi"
android:padding="2dp"/>
</LinearLayout>
</LinearLayout>
listview shows the first item only is because you have set height in heritages_row layout to match_parent which will cover the whole screen height and for the next item, you've to scroll down even if the content of the first item is not covering the whole height.
To make each row to only cover the content its displaying, use wrap_content instead of match_parent.
Related
so I want to add an option to delete a particular entry in a list, so I added an Image view into my list's adapter. But for some reason, when I try to create the list in my app now, it crashes. This is the error line :
java.lang.ClassCastException: android.widget.LinearLayout cannot be cast to android.widget.ImageView
Here is the code for my list adapter :
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 SubtaskAdapter extends ArrayAdapter<subtask> {
private final Context context;
private ArrayList<subtask> values;
public SubtaskAdapter(Context context, ArrayList<subtask> 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.subtask_item, parent, false);
}
//use convertView to refer the childviews to populate it with data
TextView tvSubtaskName = convertView.findViewById(R.id.tvSubtaskName);
ImageView ivPri = convertView.findViewById(R.id.ivPri);
ImageView ivTime = convertView.findViewById(R.id.ivTime);
ImageView ivDelete = convertView.findViewById(R.id.ivDelete);
tvSubtaskName.setText(values.get(position).getSubtaskName());
if (values.get(position).isPriHigh()) {
ivPri.setImageResource(R.drawable.priority_high);
} else if (values.get(position).isPriMed()) {
ivPri.setImageResource(R.drawable.priority_med);
} else if (values.get(position).isPriLow()) {
ivPri.setImageResource(R.drawable.priority_low);
}
if (values.get(position).isTimeMore()) {
ivTime.setImageResource(R.drawable.time_symbol_more);
} else if (values.get(position).isTimeMed()) {
ivTime.setImageResource(R.drawable.time_symbol_med);
} else if (values.get(position).isTimeLess()) {
ivTime.setImageResource(R.drawable.time_symbol_less);
}
// Delete button for subtasks
ivDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
values.remove(position);
notifyDataSetChanged();
}
});
//return the view you inflated
return convertView;
}
//to keep adding the new subtasks try the following
public void addANewSubTask(subtask newSubTask){
ArrayList<subtask> newvalues = new ArrayList<>(this.values);
newvalues.add(newSubTask);
this.values = newvalues;
notifyDataSetChanged();
}
}
This is the xml code for the list item :
<?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"
android:id="#+id/ivDelete"
android:layout_width="match_parent"
android:layout_height="40dp"
android:layout_margin="16dp"
android:background="#color/white"
android:clickable="true"
android:orientation="horizontal"
>
<ImageView
android:id="#+id/imageView"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_weight="1"
android:clickable="true"
app:srcCompat="#drawable/delete" />
<TextView
android:id="#+id/tvSubtaskName"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_weight="3"
android:fontFamily="#font/roboto"
android:gravity="center_horizontal"
android:text="subtask_name"
android:textColor="#color/black"
android:textSize="15sp" />
<ImageView
android:id="#+id/ivPri"
android:layout_width="0dp"
android:layout_height="32dp"
android:layout_gravity="center"
android:layout_weight="1"
app:srcCompat="#drawable/priority_high" />
<ImageView
android:id="#+id/ivTime"
android:layout_width="0dp"
android:layout_height="32dp"
android:layout_gravity="center"
android:layout_weight="1"
app:srcCompat="#drawable/time_symbol_more" />
</LinearLayout>
You are trying to reference a LinearLayout as an ImageView.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/ivDelete"
...
ImageView ivDelete = convertView.findViewById(R.id.ivDelete);
Do you see the ids here?
Just replace this last line with the following:
LinearLayout ivDelete = convertView.findViewById(R.id.ivDelete);
Your issue is here:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/ivDelete"
and in your getView()
ImageView ivDelete = convertView.findViewById(R.id.ivDelete);
Use:
ImageView ivDelete = convertView.findViewById(R.id.imageView);
since in your layout:
<ImageView
android:id="#+id/imageView"
app:srcCompat="#drawable/delete"
yet another answer with fastest fix: replace id of your deleting ImageView, from:
ImageView ivDelete = convertView.findViewById(R.id.ivDelete);
to
ImageView ivDelete = convertView.findViewById(R.id.imageView);
btw. clean up your resources naming, currently your whole row have ivDelete id
So, I have followed this tutorial (https://www.youtube.com/watch?v=cS5l_hPwC10) on how to do a card stack and it works fine even with 2 cardstacks at the same time. now I want to add a button so i can reset both stacks and/or a button to get to the previous card
Here is all the code I have related to the card stack. Tell me if you need more since this is the first time I am trying to programm something
hauptanwendung_fragment.xml
<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:orientation="vertical"
android:gravity="center"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".FragmentHauptanwendung">
<com.wenchao.cardstack.CardStack
android:id="#+id/card_stack"
android:layout_width="280dp"
android:layout_height="170dp"
android:clipChildren="false"
android:clipToPadding="false" />
<com.wenchao.cardstack.CardStack
android:id="#+id/card_stack2"
android:layout_width="280dp"
android:layout_height="170dp"
android:clipChildren="false"
android:clipToPadding="false" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<ImageButton
android:id="#+id/stern"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#null"
app:srcCompat="#drawable/ic_stern02" />
<Space
android:layout_width="50sp"
android:layout_height="match_parent"
android:layout_marginRight="15sp"
android:layout_weight="1" />
<ImageButton
android:id="#+id/stift"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#null"
app:srcCompat="#drawable/ic_bearbeiten01" />
</LinearLayout>
</LinearLayout>
card_layout.xml
<?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"
android:orientation="vertical">
<ImageView
android:id="#+id/image_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="center" />
</LinearLayout>
card_layout2.xml
<?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"
android:orientation="vertical">
<ImageView
android:id="#+id/image_content2"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="center" />
</LinearLayout>
FragmentHauptanwendung.java
package com.example.ideenfinder3;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.wenchao.cardstack.CardStack;
import java.util.Objects;
public class FragmentHauptanwendung extends Fragment implements CardStack.CardEventListener {
View view;
private CardsDataAdapter card_adapter;
private CardsDataAdapter2 card_adapter2;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
view = inflater.inflate(R.layout.hauptanwendung_fragment, container, false);
initImages();
initImages2();
CardStack card_stack = (CardStack) view.findViewById(R.id.card_stack);
card_stack.setContentResource(R.layout.card_layout);
card_stack.setStackMargin(20);
card_stack.setAdapter(card_adapter);
card_stack.setListener(this);
CardStack card_stack2 = (CardStack) view.findViewById(R.id.card_stack2);
card_stack2.setContentResource(R.layout.card_layout2);
card_stack2.setStackMargin(20);
card_stack2.setAdapter(card_adapter2);
card_stack2.setListener(this);
return view;
}
private void initImages2() {
card_adapter2 = new CardsDataAdapter2(Objects.requireNonNull(getActivity()).getApplicationContext(),0);
card_adapter2.add(R.drawable.logo);
card_adapter2.add(R.drawable.schriftzug);
}
private void initImages() {
card_adapter = new CardsDataAdapter(Objects.requireNonNull(getActivity()).getApplicationContext(),0);
card_adapter.add(R.drawable.bild01);
card_adapter.add(R.drawable.bild02);
card_adapter.add(R.drawable.bild03);
card_adapter.add(R.drawable.bild04);
card_adapter.add(R.drawable.bild05);
}
#Override
public boolean swipeEnd(int i, float v) {
return v > 300;
}
#Override
public boolean swipeStart(int i, float v) {
return false;
}
#Override
public boolean swipeContinue(int i, float v, float v1) {
return false;
}
#Override
public void discarded(int i, int i1) {
}
#Override
public void topCardTapped() {
}
}
CardsDataAdapter
package com.example.ideenfinder3;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
public class CardsDataAdapter extends ArrayAdapter<Integer> {
public CardsDataAdapter(Context context, int resource) {
super(context, resource);
}
#Override
public View getView(int position, final View ImgcontentView, ViewGroup parent){
ImageView ImgV = (ImageView) (ImgcontentView.findViewById(R.id.image_content));
ImgV.setImageResource(getItem(position));
return ImgcontentView;
}
}
CardsDataAdapter2
package com.example.ideenfinder3;
import android.content.Context;
import android.support.annotation.NonNull;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
public class CardsDataAdapter2 extends ArrayAdapter<Integer> {
public CardsDataAdapter2(#NonNull Context context, int resource) {
super(context, resource);
}
#Override
public View getView(int position, final View ImgcontentView2, ViewGroup parent){
ImageView ImgV2 = (ImageView) (ImgcontentView2.findViewById(R.id.image_content2));
ImgV2.setImageResource(getItem(position));
return ImgcontentView2;
}
}
Just keep handles to CardStack instead:
private CardStack cardStack01;
private CardStack cardStack02;
And let the Fragment implement getters and setters for these.
So I have this custom list adapter and listview thingy and I can't seem to get it to work. I've spent a couple of days now trying to figure how to fix it. Change this change that, nothing seems to work. Any idea? thanks
MainActivity.class
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListView;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActvty";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_inventory_actvity);
Log.d(TAG, "onCreate, Started");
ListView resList = (ListView)findViewById(R.id.inListView);
resClass wood = new resClass("Wood", 10);
resClass iron = new resClass("Iron", 50);
resClass meat = new resClass("Meat", 5);
ArrayList<resClass> resArrayList = new ArrayList<>();
resArrayList.add(wood);
resArrayList.add(iron);
resArrayList.add(meat);
ResListAdapter rsAdapter = new ResListAdapter(this, R.layout.activity_inventory_actvity, resArrayList);
resList.setAdapter(rsAdapter);
}
}
resClass.class
public class resClass {
private String resType;
private int resCount;
public resClass(String resType, int resCount) {
this.resType = resType;
this.resCount = resCount;
}
public String getResType() {
return resType;
}
public void setResType(String resType) {
this.resType = resType;
}
public int getResCount() {
return resCount;
}
public void setResCount(int resCount) {
this.resCount = resCount;
}
}
ResListAdapter.class
I'm guessing there is something wrong with the adapter. But I'm not really sure.
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import java.util.ArrayList;
class ResListAdapter extends ArrayAdapter<resClass>{
private static final String TAG = "ResListAdapter";
private Context mContext;
int mResource;
public ResListAdapter( Context context, int resource, ArrayList<resClass> objects) {
super(context, resource, objects);
mContext = context;
mResource = resource;
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
String resType = getItem(position).getResType();
int resCount = getItem(position).getResCount();
resClass res = new resClass(resType, resCount);
LayoutInflater rsInflater = LayoutInflater.from(mContext);
convertView = rsInflater.inflate(mResource, parent, false);
TextView resTypeView = (TextView)convertView.findViewById(R.id.res_name);
TextView resCountView = (TextView)convertView.findViewById(R.id.res_count);
resTypeView.setText(resType);
resCountView.setText(Integer.toString(resCount));
return convertView;
}
}
The xml files
MainActivity
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="p_darkness.lonemandevelopmentstudio.com.p_darkness.MainActivity">
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:layout_editor_absoluteX="8dp"
tools:layout_editor_absoluteY="8dp"
android:id="#+id/inListView"/>
</RelativeLayout>
Custom layout for the listview
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:orientation="horizontal"
android:weightSum="100"
android:layout_height="match_parent">
<TextView
android:id="#+id/res_name"
android:textColor="#000"
android:textSize="17sp"
android:layout_width="wrap_content"
android:layout_height="60dp"
android:gravity="center"
android:layout_weight="50"
android:text="res_name"
android:textAlignment="center"/>
<TextView
android:id="#+id/res_count"
android:textColor="#000"
android:textSize="15sp"
android:textAlignment="center"
android:layout_width="wrap_content"
android:layout_height="60dp"
android:gravity="center"
android:layout_weight="50"
android:text="res_count"
/>
</LinearLayout>
It's been really frustrating guys hope I can find the solution by asking this time.
I am using a custom adapter for my ListView which I already don't understand as much as I would like to. I can find information online on how to add a row to ListView but it doesn't integrate nicely into my code, I'm guessing because I'm using a custom adapter. I have my setOnClickListener() method for my button in my Main Activity and have been experimenting there but just cant figure it out I'm also not sure if my method is in the right place?
this is the mainActivity
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Toast;
import static java.util.logging.Logger.global;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final String[] Chores = {""};
ListAdapter MyAdapter = new CustomAdapter(this, Chores);
ListView listViewObject = (ListView)findViewById(R.id.customListView_ID);
listViewObject.setAdapter(MyAdapter);
listViewObject.setOnItemClickListener(
new AdapterView.OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id){
String ChoreString = String.valueOf(parent.getItemAtPosition(position));
}
}
);
// this is where I am trying to have button click add another row to my listView
final Button button = (Button) findViewById(R.id.button_ID);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//this is where I am stuck
}
});
}
}
here is my CustomAdapter class
import android.content.Context;
import android.support.annotation.NonNull;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
class CustomAdapter extends ArrayAdapter{
public CustomAdapter(Context context, String[] choreText) {
super(context, R.layout.custon_listview_row, choreText);
}
#NonNull
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater myInflater = LayoutInflater.from(getContext());
View customView = myInflater.inflate(R.layout.custon_listview_row, parent, false);
String singleListItem = (String) getItem(position);
EditText choreText = (EditText) customView.findViewById(R.id.editText_ID);
ImageButton imageButton = (ImageButton) customView.findViewById(R.id.imageButton_ID);
choreText.setText(singleListItem, TextView.BufferType.EDITABLE);
imageButton.setImageResource(R.drawable.clock);
return customView;
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_main"
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="com.example.emilythacker.chorelist.MainActivity">
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/customListView_ID"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:layout_marginTop="50dp" />
<Button
android:text="Add Chore"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:id="#+id/button_ID" />
</RelativeLayout>
and custom_listview_row.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="horizontal" android:layout_width="match_parent"
android:layout_height="60dp">
<ImageButton
android:layout_width="60dp"
android:scaleType="fitCenter"
app:srcCompat="#drawable/clock"
android:id="#+id/imageButton_ID"
android:layout_height="60dp"
android:background="#null"
android:layout_alignParentRight="true"
android:padding="5dp"
android:layout_weight="1" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:id="#+id/editText_ID"
android:layout_alignParentLeft="true"
android:alpha = ".5"
android:hint="Enter chore"
android:maxLines="1"
android:inputType="text"
/>
</RelativeLayout>
First make your list into an ArrayList instead of String array.
private ArrayList<String> arrayList;
In the buttons onClick
arrayList.add("New Item");
((ArrayAdapter)MyAdapter).notifyDataSetChanged();
public void onClick(View v) {
String stringToAdd = ... //
MyAdapter.add(stringToAdd);
}
You will need to add final to the adapter declaration for this to work:
final ListAdapter MyAdapter = new CustomAdapter(this, Chores);
EDIT
To add more than one row at a time:
public void onClick(View v) {
String[] rowsToAdd = ... //
MyAdapter.addAll(rowsToAdd);
}
I want to have my items in listview looking like a conversation in messenger.
There is simple code of recieving messages:
if (arrayList2.get(y).toString().equals(myEmail)) {
arrayList.add(arrayList2.get(k).toString());
} else if (arrayList2.get(y).toString().equals(recipientEmail)) {
arrayList.add(arrayList2.get(k).toString());
}
arrayAdapter.notifyDataSetChanged();
When array.get.....equals(myEmail), the messages are from me so, they should stay like they are. When ...equals(recipientEmail), I want text to be on the right of the screen/or listview and have an background of image, like classically in messenger
I will recommend you to add all Your messages in one Arraylist and create two layouts one of sender with left gravity and one of receiver with right gravity then make a logic like-
if(arraylist.get(position).getUserID==currentUser){
senderLayout.setvisibility(View.VISIBLE);
senderTextview.setText(arraylist.get(position).getText)
}
else{
senderLayout.setvisibility(View.GONE);
receiverLayout.setvisibility(View.VISIBLE);
recieverTextview.setText(arraylist.get(position).getText)
}
Do this in getView method of your adapter.
You may create a row with 2 views. One on left and other on right. Based on your if condition you can make one of the views gone and the other visible. At any time only one view in that will be visible.
Another way of doing is to use single view in it and setting (left/right) gravity based on your condition.
You may refer http://www.uandblog.com/How-to-Create-Chat-Application-using-Firebase-in-Android-. See MainActivity.java and item.xml
Use two TextView in raw file
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.github.library.bubbleview.BubbleTextVew
android:id="#+id/tv_chatRecive"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="7dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="35dp"
android:layout_marginTop="8dp"
android:padding="10dp"
android:textColor="#android:color/white"
android:visibility="gone"
app:angle="5dp"
app:arrowHeight="12dp"
app:arrowLocation="left"
app:arrowPosition="5dp"
app:arrowWidth="12dp"
app:bubbleColor="#color/colorPrimary" />
<com.github.library.bubbleview.BubbleTextVew
android:id="#+id/tv_chatSend"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_marginBottom="7dp"
android:layout_marginLeft="35dp"
android:layout_marginRight="10dp"
android:layout_marginTop="8dp"
android:padding="10dp"
android:textColor="#color/text_labelColoe"
android:visibility="gone"
app:angle="5dp"
app:arrowHeight="12dp"
app:arrowLocation="right"
app:arrowPosition="5dp"
app:arrowWidth="12dp"
app:bubbleColor="#android:color/white" />
</RelativeLayout>
and in Adapter class use this kind of logic to manage textview
#Override
public void onBindViewHolder(final CustomViewHolder customViewHolder, final int position) {
if (listChat.get(position).CHAT_SEND_RECIVE.equalsIgnoreCase("right")) {
customViewHolder.tvSend.setVisibility(View.VISIBLE);
customViewHolder.tvRecive.setVisibility(View.GONE);
customViewHolder.tvSend.setText(listChat.get(position).CHAT_MESSAGE);
} else if (listChat.get(position).CHAT_SEND_RECIVE.equalsIgnoreCase("left")) {
customViewHolder.tvRecive.setVisibility(View.VISIBLE);
customViewHolder.tvSend.setVisibility(View.GONE);
customViewHolder.tvRecive.setText(listChat.get(position).CHAT_MESSAGE);
}
}
Add key in chat responce like just i add right and left
Here is complete example.
Resources under drawable:
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<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="com.example.andrii.myapplication.MainActivity">
<android.support.v7.widget.RecyclerView
android:id="#+id/chat"
android:background="#color/colorAccent"
android:layout_width="match_parent"
android:layout_height="match_parent">
</android.support.v7.widget.RecyclerView>
</RelativeLayout>
Message layout will looks like so (message.xml):
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<FrameLayout
android:id="#+id/container"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="15dp"
android:paddingTop="10dp"
android:paddingBottom="10dp"
android:paddingRight="10dp"
android:background="#drawable/in_9">
<TextView
android:id="#+id/message"
android:textSize="18sp"
android:layout_gravity="center"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:breakStrategy="balanced"
android:maxWidth="200dp"
android:text="test"
/>
</FrameLayout>
</LinearLayout>
And finally in MainActivity.java :
package com.example.andrii.myapplication;
import android.content.Context;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import java.util.LinkedList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
List<Message> list= new LinkedList<>();
list.add(new Message(true, "hi"));
list.add(new Message(false, "hello"));
list.add(new Message(true, "how are you"));
list.add(new Message(false, "I'm fine"));
list.add(new Message(false, "Test test test test test"));
RecyclerView view = (RecyclerView) findViewById(R.id.chat);
view.setLayoutManager(new LinearLayoutManager(this));
view.setAdapter(new ChatAdapter(this, list));
}
private class Message {
private boolean misMine;
private String mMessage;
public Message (boolean mine, String message) {
misMine = mine;
mMessage = message;
}
public boolean isMine() { return misMine; }
public String getMessage() { return mMessage; }
}
private class MessageViewHolder extends RecyclerView.ViewHolder {
private View mContainer;
private TextView mMessage;
public MessageViewHolder(View itemView) {
super(itemView);
mMessage = (TextView) itemView.findViewById(R.id.message);
mContainer = itemView.findViewById(R.id.container);
}
public void setMessage(String message) {
mMessage.setText(message);
}
public void setMine(boolean isMine) {
LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) mContainer.getLayoutParams();
params.gravity = isMine ? Gravity.RIGHT : Gravity.LEFT;
mContainer.setBackgroundResource(isMine ? R.drawable.out_9 : R.drawable.in_9 );
mContainer.setLayoutParams(params);
}
}
private class ChatAdapter extends RecyclerView.Adapter<MessageViewHolder> {
private List<Message> mMessages;
public ChatAdapter(Context context, List<Message> list) {
mMessages = list;
}
#Override
public MessageViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.message, parent, false);
MessageViewHolder holder = new MessageViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(MessageViewHolder holder, int position) {
Message message = mMessages.get(position);
holder.setMessage(message.getMessage());
holder.setMine(message.isMine());
}
#Override
public int getItemCount() {
return mMessages.size();
}
}
}
The result of code above: