So I'm creating a small application, and thanks to this site, I've progressed on it a lot more. The idea of it is that I will just have a button, and when it is clicked, it will add a new row with two "EditText" and one "CheckBox". I've somewhat accomplished this through dynamically adding these with a custom ListView and a custom adapter. I'm still iffy on custom ListView's and adapters.
Anyways, I've gotten it to add the two EditText and one CheckBox when the button is clicked, but it will not add any more after this (this is a separate problem though). The problem I'm having, is that it will add them on the same row as the button. This is where I get lost. I'm not sure how to get this custom ListView to display on a new row, rather than the same row as the button.
Now, here is my MainActivity code:
import android.content.Context;
import android.graphics.Color;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.InputType;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.view.ViewGroup.LayoutParams;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
ArrayList<CheckBox> checkBoxes = new ArrayList<>();
ArrayList<EditText> courses = new ArrayList<>();
ArrayList<EditText> credits = new ArrayList<>();
int numOfCheckBoxes = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final LinearLayout ll = (LinearLayout) findViewById(R.id.ll);
ll.setOrientation(LinearLayout.HORIZONTAL);
Button addCourse = new Button(this);
addCourse.setLayoutParams(new ActionBar.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
addCourse.setText("Add Course");
addCourse.setTextColor(Color.parseColor("#FFFFFF"));
addCourse.setBackgroundColor(Color.parseColor("#FF0000"));
addCourse.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ListView myListView = new ListView(MainActivity.this);
List<CustomRow> rows = new ArrayList<CustomRow>();
rows.add(new CustomRow(MainActivity.this));
MyListArrayAdapter myAdapter = new MyListArrayAdapter(MainActivity.this, rows);
myListView.setAdapter(myAdapter);
ll.addView(myListView);
}
});
ll.addView(addCourse);
} // End of onCreate
public void onCheckBoxChecked(View v) {
for (int i = 0; i < numOfCheckBoxes; i++) {
if (checkBoxes.get(i).isChecked()) {
courses.get(i).setEnabled(false);
courses.get(i).setFocusable(false);
courses.get(i).setInputType(InputType.TYPE_NULL);
credits.get(i).setEnabled(false);
credits.get(i).setFocusable(false);
credits.get(i).setInputType(InputType.TYPE_NULL);
} else {
courses.get(i).setEnabled(true);
courses.get(i).setFocusable(true);
courses.get(i).setFocusableInTouchMode(true);
courses.get(i).setInputType(InputType.TYPE_CLASS_TEXT);
credits.get(i).setEnabled(true);
credits.get(i).setFocusableInTouchMode(true);
credits.get(i).setFocusable(true);
credits.get(i).setInputType(InputType.TYPE_CLASS_NUMBER);
} // End of if else
} // End of for loop
} // End of onCheckBoxChecked
} // End of MainActivity
Here is my "MyListArrayAdapter" class (my custom adapter):
import android.app.Activity;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.view.LayoutInflater;
import android.widget.CheckBox;
import android.widget.EditText;
import java.util.List;
/**
* Created by Thomas on 5/21/2016.
*/
public class MyListArrayAdapter extends BaseAdapter {
LayoutInflater inflater;
List<CustomRow> rows;
public MyListArrayAdapter(Activity context, List rows){
super();
this.rows = rows;
this.inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return rows.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
CustomRow row = rows.get(position);
View v = convertView;
if (convertView==null) {
v = inflater.inflate(R.layout.new_course_row, null);
}
EditText course = (EditText) v.findViewById(R.id.course);
EditText credits = (EditText) v.findViewById(R.id.credits);
CheckBox checkBox = (CheckBox) v.findViewById(R.id.checkBox);
course.setHint("Enter Course");
credits.setHint("Enter Credits");
checkBox.setText("Check if complete");
course.setMaxHeight(150);
credits.setMaxHeight(150);
checkBox.setMaxHeight(150);
return v;
}
}
My "CustomRow" class (the custom class with the two EditText and one CheckBox):
import android.content.Context;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
/**
* Created by Thomas on 5/21/2016.
*/
public class CustomRow extends LinearLayout{
public CustomRow(Context context) {
super(context);
setOrientation(LinearLayout.HORIZONTAL);
EditText course = new EditText(context);
EditText credits = new EditText(context);
CheckBox checkBox = new CheckBox(context);
addView(course);
addView(credits);
addView(checkBox);
}
}
My "new_course_row.xml" file:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/course"
android:layout_weight="1"/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/credits"
android:layout_weight="1"/>
<CheckBox
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/checkBox"
android:onClick="onCheckBoxChecked"/>
</LinearLayout>
Lastly, my "activity_main.xml":
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android: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="exporian.collegetracker.MainActivity"
android:id="#+id/ll">
</LinearLayout>
</ScrollView>
Thank you in advance everyone! I've been stuck here for a few days. Not looking for anyone to write the app for me, just looking for some direction.
make sure that after adding a button you have called these two methods in your adapter to update the list
BuddyFeedsAdapter.this.notifyDataSetChanged();
notifyDataSetInvalidated();
If your code is working properly and adding row on same row, then please check below solution.
As you have write below line ,
List<CustomRow> rows = new ArrayList<CustomRow>();
in OnButton CLick event, so whenever button will be clicked, it will initialise rows again and remove all previous records from it, so just write above line at top or in onCreate() method after setContentView, then you will get all rows on click.
Hope this will help you.
Related
I have searched various sites and tutorials and I've done exactly the same, but I can't even make a Toast from my list.
Here's my xml of my activity view list_view.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"
android:padding="50px"
android:background="#drawable/minimalist_wallpapers_droidviews_25"
tools:context=".ViewList"
>
<com.google.android.material.card.MaterialCardView
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/card"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="8dp"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<ListView
android:id="#+id/lista"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</ListView>
</LinearLayout>
</com.google.android.material.card.MaterialCardView>
</LinearLayout>
Here's my ViewList.java:
package com.example.trialandroid;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
import com.arcu.dao.DaoPersona;
import com.arcu.util.Adaptador;
import java.util.List;
public class ViewList extends AppCompatActivity {
DaoPersona dao;
Adaptador adaptador;
List lista;
ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list_view);
dao = new DaoPersona(ViewList.this);
lista = dao.listarPersonas();
adaptador = new Adaptador(lista, dao, this);
listView = (ListView) findViewById(R.id.listView);
listView.setAdapter(adaptador);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
System.out.println("onclicklistener");
Toast.makeText(getApplicationContext(), "Posicion: ", Toast.LENGTH_LONG);
}
});
}
}
And I also have an adapter class called Adaptador.java
package com.arcu.util;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Base64;
import android.view.ContextThemeWrapper;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import com.arcu.bean.BeanPersona;
import com.arcu.dao.DaoPersona;
import com.example.trialandroid.R;
import java.util.ArrayList;
import java.util.List;
public class Adaptador extends BaseAdapter {
List<BeanPersona> lista;
DaoPersona dao;
BeanPersona bean;
ConversorImagenes conversor = new ConversorImagenes();
Activity actividad;
public Adaptador(List<BeanPersona> lista, DaoPersona dao, Activity actividad) {
this.lista = lista;
this.dao = dao;
this.actividad = actividad;
}
#Override
public int getCount() {
return lista.size();
}
#Override
public BeanPersona getItem(int i) {
bean = lista.get(i);
return null;
}
#Override
public long getItemId(int i) {
bean = lista.get(i);
return bean.getIdPersona();
}
#Override
public View getView(int position, View view, ViewGroup parent) {
View vista = view;
if(vista == null){
LayoutInflater li = (LayoutInflater) actividad.getSystemService(ContextThemeWrapper.LAYOUT_INFLATER_SERVICE);
vista = li.inflate(R.layout.list_element,null);
}
bean = lista.get(position);
ImageView fotoLista = (ImageView) vista.findViewById(R.id.listFoto);
TextView nombreLista = (TextView) vista.findViewById(R.id.listNombre);
TextView fechaNacLista = (TextView) vista.findViewById(R.id.listFechaNac);
TextView areaTrabajoLista = (TextView) vista.findViewById(R.id.listAreaTrabajo);
Button modificarBtn = (Button) vista.findViewById(R.id.listBtnModificar);
Button eliminarBtn = (Button) vista.findViewById(R.id.listBtnEliminar);
fotoLista.setImageBitmap(conversor.stringABitmap(bean.getFoto()));
nombreLista.setText(bean.getNombre());
fechaNacLista.setText(bean.getFechaNac());
areaTrabajoLista.setText(bean.getAreaTrabajo());
modificarBtn.setTag(position);
eliminarBtn.setTag(position);
modificarBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
eliminarBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
return vista;
}
}
I have no idea what's going on since I'm just starting in Android development.
Help please!
Thanks in advance.
you forgot to add .show() to your Toast. try this:
Toast.makeText(getApplicationContext(), "Posicion: ", Toast.LENGTH_LONG).show();
i have tried the all the suggestions for this. All that answers are changing the fragment from a activity but here is the difference in my question. i am trying to change one fragment to another fragment from the first fragment.Please help me .
i have a fragment which contains dynamic buttons.please find the image [![enter image description here][1]][1]
If the user clicks any of the button i want to show some stack cars for the same.see the image [![enter image description here][2]][2]
Ok this is my requirement. My problem is i have one activity which contains the bottom navigation bar names as ShowDashBoardActivity
ShowDashBoardActivity.java
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.Toast;
import com.yourname.R;
import com.yourname.fragments.DashBoardJobList;
import com.yourname.fragments.DashBoardOne;
import com.yourname.fragments.DashBoardTaskBubble;
import com.roughike.bottombar.BottomBar;
import com.roughike.bottombar.BottomBarBadge;
import com.roughike.bottombar.BottomBarFragment;
import butterknife.Bind;
public class ShowDashBoardActivity extends AppCompatActivity {
private BottomBar bottomBar;
LinearLayout CardAspirationLayout,TextCardAspirationLayout;
DashBoardOne _DashBoardOne;
Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.show_dash_board_activity);
context=getApplicationContext();
getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
getSupportActionBar().setDisplayShowCustomEnabled(true);
getSupportActionBar().setCustomView(R.layout.custom_action_bar_layout);
View view =getSupportActionBar().getCustomView();
/*ImageButton imageButton= (ImageButton)view.findViewById(R.id.action_bar_back);
imageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});*/
bottomBar = BottomBar.attach(this, savedInstanceState);
bottomBar.setFragmentItems(getSupportFragmentManager(), R.id.fragmentContainer,
new BottomBarFragment(DashBoardOne.newInstance("Content for Dashboard."), R.drawable.dashboard, "Dashboard"),
new BottomBarFragment(DashBoardTaskBubble.newInstance("Content for Task."), R.drawable.task, "Task"),
new BottomBarFragment(DashBoardJobList.newInstance("Content for Job."), R.drawable.job, "Job")
);
TextCardAspirationLayout=(LinearLayout) findViewById(R.id.TextCardAspirationLayout);
bottomBar.setActiveTabColor("#C2185B");
BottomBarBadge unreadMessages = bottomBar.makeBadgeForTabAt(2, "#E91E63", 4);
unreadMessages.show();
unreadMessages.setAnimationDuration(200);
unreadMessages.setAutoShowAfterUnSelection(true);
// bottomBar.useDarkTheme(true);
}
}
show_dash_board_activity.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/fragmentContainer"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/slidetwo"
xmlns:tools="http://schemas.android.com/tools" >
</FrameLayout>
The navigation drawer is working perfect. the in the DashBoardTaskBubble.java it is fragment i am drawing dynamic bubble to show like picture 1.
DashBoardTaskBubble.java
import android.content.res.ColorStateList;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewCompat;
import android.support.v7.widget.AppCompatButton;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.panenviron.R;
import java.util.ArrayList;
import java.util.List;
import static android.R.attr.tint;
public class DashBoardTaskBubble extends Fragment {
private static final String STARTING_TEXT = "Four Buttons Bottom Navigation";
public DashBoardTaskBubble() {
}
public static DashBoardTaskBubble newInstance(String text) {
Bundle args = new Bundle();
args.putString(STARTING_TEXT, text);
DashBoardTaskBubble dashBoardTaskBubble = new DashBoardTaskBubble();
dashBoardTaskBubble.setArguments(args);
return dashBoardTaskBubble;
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_task_bubble, container, false);
final RelativeLayout workViewLayout = (RelativeLayout)view.findViewById(R.id.workView);
int iNumberOfButtons = 6; // no of bubble create function to fetch no of bubble from db
// create a function to get color from db now give static
String[] colourList = new String[] { "#ffaa00","#32CD32","#0000FF"};
Button[] dynamicButtons = new Button[iNumberOfButtons];
List<String> tempColouersList= new ArrayList<String>();
for (int i = 0; i < iNumberOfButtons; i++) {
dynamicButtons[i] = new Button(getActivity());
dynamicButtons[i].setText("+"+i+5);
dynamicButtons[i].setId(i);
dynamicButtons[i].setTextSize(15.0f);
dynamicButtons[i].setBackgroundResource(R.drawable.round_button);
if(i==0){
RelativeLayout.LayoutParams paramsButton =
new RelativeLayout.LayoutParams(350,350);
paramsButton.setMargins(50,0,0,0);
dynamicButtons[0].setLayoutParams(paramsButton);
tempColouersList.add(colourList[0]);
} else if(i==1){
RelativeLayout.LayoutParams paramsButton2 =
new RelativeLayout.LayoutParams(350,350);
paramsButton2.setMargins(700,10,0,0);
dynamicButtons[1].setLayoutParams(paramsButton2);
tempColouersList.add(colourList[1]);
} else if(i==2){
RelativeLayout.LayoutParams paramsButton3 =
new RelativeLayout.LayoutParams(350,350);
paramsButton3.setMargins(400,250,0,0);
dynamicButtons[2].setLayoutParams(paramsButton3);
tempColouersList.add(colourList[2]);
} else if(i==3){
RelativeLayout.LayoutParams paramsButton4 =
new RelativeLayout.LayoutParams(350,350);
paramsButton4.setMargins(50,450,0,0);
dynamicButtons[3].setLayoutParams(paramsButton4);
tempColouersList.add(colourList[1]);
} else if(i==4){
RelativeLayout.LayoutParams paramsButton5 =
new RelativeLayout.LayoutParams(350,350);
paramsButton5.setMargins(700,500,0,0);
dynamicButtons[4].setLayoutParams(paramsButton5);
tempColouersList.add(colourList[2]);
}else if(i==5){
RelativeLayout.LayoutParams paramsButton6 =
new RelativeLayout.LayoutParams(350,350);
paramsButton6.setMargins(350,700,0,0);
dynamicButtons[5].setLayoutParams(paramsButton6);
tempColouersList.add(colourList[0]);
}
ColorStateList tint = new ColorStateList(new int[][]{new int[0]}, new int[]{Color.parseColor(tempColouersList.get(i)) });
if (Build.VERSION.SDK_INT == Build.VERSION_CODES.LOLLIPOP && dynamicButtons[i] instanceof AppCompatButton) {
((AppCompatButton) dynamicButtons[i]).setSupportBackgroundTintList(tint);
} else {
ViewCompat.setBackgroundTintList(dynamicButtons[i], tint);
}
dynamicButtons[i].setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
Log.e("im on","button clik");
} catch (Exception e) {
e.printStackTrace();
}
}
});
workViewLayout.addView(dynamicButtons[i]); // dynamicButtonsLinearLayout is the container of the buttons
}
return view;
}
public void replaceFragments( ) {
Log.e("im on","replaceFragments");
//Fragment fragment = null;
try {
//fragment = (Fragment) TaskCardListShow.newInstance();
/*TaskCardListShow nextFrag= new TaskCardListShow();
this.getFragmentManager().beginTransaction()
.replace(R.id.fragmentContainer, nextFrag)
.addToBackStack(null)
.commit();*/
FragmentManager mFragmentManager = getFragmentManager();
FragmentTransaction mFragmentTransaction = https://i.stack.imgur.com/J75iJ.pngmFragmentManager.beginTransaction();
TaskCardListShow mFragment = new TaskCardListShow();
//mFragmentTransaction.replace(R.id.fragmentContainer, mFragment);
mFragmentTransaction.add(R.id.fragmentContainer, mFragment);
mFragmentTransaction.addToBackStack(null);
mFragmentTransaction.commit();
} catch (Exception e)
{ e.printStackTrace(); }
// Insert the fragment by replacing any existing fragment FragmentManager
// fragmentManager = getSupportFragmentManager();
// fragmentManager.beginTransaction().replace(R.id.flContent, fragment).commit();
}
}
fragment_task_bubble.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_horizontal"
android:orientation="vertical"
android:background="#drawable/slidetwo">
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="12"
android:background="#color/white">
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="88"
android:orientation="vertical"
android:background="#color/white">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:layout_marginTop="3dp"
/>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="5dp"
android:layout_gravity="center_horizontal"
android:layout_marginBottom="20dp">
<View
android:layout_width="98dp"
android:gravity="center_horizontal"
android:layout_height="4dp"
android:background="#android:color/holo_red_dark"
android:id="#+id/normalViewSeparator"
/>
</LinearLayout>
<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="wrap_content"
android:layout_weight="30"
android:orientation="vertical"
android:id="#+id/workView"
android:background="#color/white">
</RelativeLayout>
</LinearLayout>
</LinearLayout>
The bubble drawing is also working perfect. Here i trying to add some features like if a user clicks a button i want to show the stack cards like picture 2
I am thinking to display the task cards in fragment . I dont know how to navigate one fragment to another fragment.
TaskCardListShow.java FRAGMENT
package com.panenviron.fragments;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.panenviron.R;
public class TaskCardListShow extends Fragment {
public TaskCardListShow() {
}
public static TaskCardListShow newInstance() {
TaskCardListShow _TaskCardListShow = new TaskCardListShow();
return _TaskCardListShow;
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.task_card_list_show, container, false);
Log.e("im on","TaskCardListShow");
return view;
}
}
task_card_list_show.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/fragment_task_card_list_show"
style="#style/Animation.AppCompat.Dialog">
<TextView
android:text="Im on task fragment"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/textView"
android:layout_weight="1" />
</LinearLayout>
i tried the above replaceFragments( ) custom function. But it is replaces the fragment but it is not removing the first fragment. How can do this.
Your are using support fragments (android.support.v4.app.Fragment) with native fragmentmanager - Activity.getFragmentManager(). Instead you have to use support fragmentmanager - AppCompatActivity.getSupportFragmentManager().
I really wish android tools would handle this annoying situation better.
inside the fragment you have to call getActivity().getSupportFragmentManager() instead of getFragmentManager. so you have to give like this "getActivity().getSupportFragmentManager().beginTransaction()" in the fragment transaction. after that you can replace simply like already done
I am getting java.lang.IllegalStateException while using relative layout using code. I know how to use relative layout using xml, but I have to use it using code only.
Here is my code:
package com.example.pr;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import android.app.DatePickerDialog;
import android.content.Context;
import android.content.DialogInterface.OnClickListener;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.InputType;
import android.util.Log;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnFocusChangeListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
public class ProfessionalProfileTab extends Fragment
{
EditText regNumber,medCouncil,languages,degree,course,year,speciality,
experience_start_month,experience_end_month,designation,experience_company;
TextView regNumberText,medCouncilText,languagesText,degreeText,specialityText,experienceText;
ImageButton addDegree;
Button updateProfession;
Display display;
double width,height;
private int mYear, mMonth, mDay;
Context con;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
display = getActivity().getWindowManager().getDefaultDisplay();
width = MainActivity.Parentwidth;
height = MainActivity.Parentheight;
Log.d("Inside Professional Profile Fragment","ppsg");
Log.d("width",String.valueOf(width));
Log.d("height",String.valueOf(height));
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
final View view = inflater.inflate(R.layout.professional_profile_tab, container, false);
con = container.getContext();
final LinearLayout layout=(LinearLayout)view.findViewById(R.id.professionalProfileDetails);
final LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
android.widget.LinearLayout.LayoutParams.MATCH_PARENT,
final RelativeLayout rlayout=(RelativeLayout)view.findViewById(R.id.reldegree) ;
final RelativeLayout.LayoutParams rparam=new RelativeLayout.LayoutParams(
android.widget.RelativeLayout.LayoutParams.MATCH_PARENT,
android.widget.RelativeLayout.LayoutParams.MATCH_PARENT) ;
final TextView degreeText=new TextView(con);
degreeText.setTag("degreeText");
degreeText.setText("degree:");
layout.addView(degreeText);
rlayout.addView(degreeText);
rparam.addRule(RelativeLayout.BELOW,degreeText.getId());
degreeText.setLayoutParams(params);
degreeText.setLayoutParams(rparam);
final ImageButton addDegree=new ImageButton(con);
addDegree.setTag("addDegree");
addDegree.setImageResource(R.drawable.ic_launcher);
layout.addView(addDegree);
rlayout.addView(addDegree);
rparam.addRule(RelativeLayout.BELOW,addDegree.getId());
degreeText.setLayoutParams(params);
addDegree.setLayoutParams(rparam);
return view;
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
int id = item.getItemId();
if (id == R.id.action_settings)
return true;
return super.onOptionsItemSelected(item);
}
}
Here is the xml version of what I want from my code:
<LinearLayout
android:id="#+id/professionalProfileDetails"
android:layout_width="320dp"
android:layout_height="200dp"
android:orientation="vertical">
<RelativeLayout
android:id="#+id/reldegree"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/degreeText"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:text="Degree Details"/>
<ImageButton
android:id="#+id/addDegree"
android:layout_toRightOf="#id/degreeText"
android:layout_width="50dp"
android:layout_height="50dp"
android:src="#drawable/ic_launcher"/>
</RelativeLayout>
</LinearLayout>
Here I want to set the image to the right of degreetext textField.
I have tried to search for a solution to this problem, but could not find any.
Can we use relative layout in the same way as we do in xml and set layout:toRightOf or toLeftOf or below etc using code for texts or images.
You are trying to add the same View to 2 different ViewGroups which is not possible.
layout.addView(degreeText);
rlayout.addView(degreeText);
Also, you are trying to position a View below itself.
rparam.addRule(RelativeLayout.BELOW,degreeText.getId());
degreeText.setLayoutParams(rparam);
**Try this**
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.demo.MainActivity" >
<RelativeLayout
android:id="#+id/layoutContainer"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:padding="10dp" >
</RelativeLayout>
</RelativeLayout>
MainActivity.java
public class MainActivity extends Activity {
RelativeLayout layoutContainer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
layoutContainer = (RelativeLayout)
findViewById(R.id.layoutContainer);
final TextView degreeText=new TextView(this);
degreeText.setId(1);
degreeText.setText("degree:");
layoutContainer.addView(degreeText);
RelativeLayout.LayoutParams params = new
RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.RIGHT_OF, degreeText.getId());
final ImageButton addDegree=new ImageButton(this);
addDegree.setImageResource(R.drawable.ic_launcher);
addDegree.setLayoutParams(params);
layoutContainer.addView(addDegree);
}
}
I want to create a list where the listview will display a textview and an icon for each row. The diagram should be as follows:
Other than that, The data is retrieved from the database. The attribute of "favorite" will be checked first and if true, then the image in listview will be assigned with favorite_icon.png. Else, no icon need to be assigned.
I have been search for the related answer and tutorial, but all of them is too different from what I want and I cannot understand it very much. Hope somebody here can help me. Thank you in advance.
Here is what I got after I have done my Homework
First we set up a custom layout for listview and also for the row of the listview we will use later.
Here is the custom_listview_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/customListView" />
</LinearLayout>
Here is the custom_listview_row.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_vertical"
android:minHeight="64dp">
<ImageView
android:id="#+id/clv_imageView"
android:layout_width="32dp"
android:layout_height="32dp"
android:contentDescription="#string/empty"
android:layout_alignParentRight="true"
android:layout_marginLeft="9dp"
android:layout_alignParentTop="true"/>
<TextView
android:id="#+id/clv_textView"
android:layout_width="97dp"
android:layout_height="32dp"
android:layout_alignParentLeft="true"
android:gravity="center_vertical"
android:text="#string/tv_definition"
android:textIsSelectable="true" />
</RelativeLayout>
Then we need to customized how our Custom ArrayAdaptor will look and do.
But before that, make sure you have put your icon in the drawable folder.
Here is my MyPerformanceArrayAdapter.java
import java.util.List;
import android.app.Activity;
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;
public class MyPerformanceArrayAdapter extends ArrayAdapter<DefinitionObject>{
private List<DefinitionObject> entries;
private Activity activity;
public MyPerformanceArrayAdapter(Activity a, int textViewResourceId, List<DefinitionObject> entries) {
super(a, textViewResourceId, entries);
this.entries = entries;
this.activity = a;
}
public static class ViewHolder{
public TextView item1;
public ImageView item2;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
ViewHolder holder;
if (v == null) {
LayoutInflater vi =
(LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.custom_listview_row, null);
holder = new ViewHolder();
holder.item1 = (TextView) v.findViewById(R.id.clv_textView);
holder.item2 = (ImageView) v.findViewById(R.id.clv_imageView);
v.setTag(holder);
}
else
holder=(ViewHolder)v.getTag();
final DefinitionObject custom = entries.get(position);
if (custom != null) {
holder.item1.setText(custom.getWord());
if(custom.getFav().equalsIgnoreCase("0"))
{
holder.item2.setImageResource(R.drawable.fav);
holder.item2.setVisibility(holder.item2.INVISIBLE);
}
else
{
holder.item2.setImageResource(R.drawable.fav2);
}
}
return v;
}
}
And lastly, here is my Activity to View the ListView using the CustomArrayAdaptor.
import java.util.List;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.ListView;
public class TempCLV extends Activity {
private MySQLiteDefinitionHelper db;
String tblName = "";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.custom_listview_main);
Intent msjIntent = getIntent();
tblName = msjIntent.getStringExtra(WordDefinitionHomeActivity.TABLENAME2);
refresh();
}
public void refresh()
{
db = new MySQLiteDefinitionHelper(this);
final List<DefinitionObject> values = db.getAllWords(tblName);
ListView mylist = (ListView)findViewById(R.id.customListView);
MyPerformanceArrayAdapter adapter = new MyPerformanceArrayAdapter(this, R.id.customListView, values);
mylist.setAdapter(adapter);
}
}
Ok, my problem is similar to this Background image in ListView entries spontaneously disappearing
but this issue is resolved with using setImageResource on a normal ImageView but I want an animation to exist on all elements of a list, and this can not be done without a custom ImageView class that allows the animation to run. Does anyone know why these images are disappearing after scrolling in the list view and maybe how this can be fixed? Thanks a lot!
Here is my ListAdapter:
package com.mmgworldwide.layout.listadapters;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import com.mmgworldwide.R;
import com.mmgworldwide.customviews.SpinLoadingAnim;
import com.mmgworldwide.data.FWREvent;
import com.mmgworldwide.data.ImageThreadLoader;
import com.mmgworldwide.data.ImageThreadLoader.ImageLoadedListener;
import com.mmgworldwide.layout.ListDivider;
import com.mmgworldwide.data.Personality;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.Drawable;
import android.text.SpannableString;
import android.text.style.UnderlineSpan;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class PersonalityListAdapter extends ArrayAdapter<Object>{
private Context parentContext;
public ArrayList<Object> items_list_ref;
private ImageThreadLoader imageLoader = new ImageThreadLoader();
public PersonalityListAdapter(Context context, int resource, int textViewResourceId, ArrayList<Object> items_list) {
super(context, resource, textViewResourceId, items_list);
items_list_ref = items_list;
parentContext = context;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Object node = (Object) items_list_ref.get(position);
LayoutInflater inflater = (LayoutInflater) parentContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if(node instanceof ListDivider){
//make new div bar
View div = inflater.inflate(R.layout.list_bar, parent, false);
TextView div_label = (TextView) div.findViewById(R.id.div_label);
div_label.setText(((ListDivider) node).label.toUpperCase());
return div;
}
View row = inflater.inflate(R.layout.picture_list, parent, false);
TextView name_txt = (TextView) row.findViewById(R.id.name_txt);
TextView title_txt = (TextView) row.findViewById(R.id.title_txt);
final ImageView portrait_img = (ImageView) row.findViewById(R.id.portrait);
final ImageView load_cnt = (ImageView) row.findViewById(R.id.portrait_loadDisplay);
name_txt.setText(((Personality) node).getName());
SpannableString title_underlined = new SpannableString(((Personality) node).getTitle());
title_underlined .setSpan(new UnderlineSpan(), 0, title_underlined.length(), 0);
title_txt.setText(title_underlined);
load_cnt.setVisibility(View.VISIBLE);
return row;
}
Here is my custom ImageView class
package com.mmgworldwide.customviews;
import android.R;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.drawable.AnimationDrawable;
import android.util.AttributeSet;
import android.util.Log;
import android.widget.ImageView;
public class SpinLoadingAnim extends ImageView{
AnimationDrawable animation;
private final Integer FRAME_SPEED = 20;
public SpinLoadingAnim(Context context, AttributeSet attrs){
super(context, attrs);
//setBackgroundColor(Color.GREEN);
animation = new AnimationDrawable();
animation.addFrame(context.getResources().getDrawable(com.mmgworldwide.R.drawable.spinner_00000), FRAME_SPEED);
animation.addFrame(context.getResources().getDrawable(com.mmgworldwide.R.drawable.spinner_00001), FRAME_SPEED);
animation.addFrame(context.getResources().getDrawable(com.mmgworldwide.R.drawable.spinner_00002), FRAME_SPEED);
animation.addFrame(context.getResources().getDrawable(com.mmgworldwide.R.drawable.spinner_00003), FRAME_SPEED);
animation.setOneShot(false);
this.setBackgroundDrawable(animation);
this.post(new Starter());
}
class Starter implements Runnable {
public void run() {
animation.start();
}
}
And here is my layout XML
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#FFFFFF"
android:gravity="center_vertical"
android:paddingTop="10dp"
android:paddingBottom="10dp"
android:paddingLeft="10dp"
android:paddingRight="10dp">
<ImageView android:layout_width="60dp" android:layout_height="60dp" android:id="#+id/portrait" android:layout_centerVertical="true"></ImageView>
<com.mmgworldwide.customviews.SpinLoadingAnim
android:id="#+id/portrait_loadDisplay"
android:layout_width="20dp" android:layout_height="20dp"
android:background="#939598"
android:layout_centerVertical="true" android:layout_marginLeft="20dp"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true" />
<ImageView android:layout_height="wrap_content" android:layout_width="wrap_content" android:layout_centerVertical="true" android:id="#+id/arrow" android:src="#drawable/list_arrow" android:layout_alignParentRight="true"></ImageView>
<LinearLayout android:layout_toRightOf="#id/portrait" android:layout_toLeftOf="#id/arrow" android:layout_centerVertical="true" android:orientation="vertical" android:layout_height="wrap_content" android:layout_width="wrap_content" android:baselineAligned="true" android:paddingLeft="15dp" android:paddingRight="15dp">
<TextView android:text="CHEF NAME" android:id="#+id/name_txt" android:layout_width="wrap_content" android:textColor="#000000" android:textStyle="bold"
android:layout_height="wrap_content" android:paddingBottom="2dp" android:textSize="15sp"></TextView>
<TextView android:text="Chef Title" android:id="#+id/title_txt" android:layout_width="wrap_content" android:textColor="#000000"
android:layout_height="wrap_content" android:textSize="13sp"></TextView>
</LinearLayout>
</RelativeLayout>
Every 5th 'preloader' graphic is still disappearing, but thanks Michele this has helped a lot, and made things cleaner.
package com.mmgworldwide.layout;
import java.util.ArrayList;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import com.mmgworldwide.R;
import com.mmgworldwide.data.DataConnection;
import com.mmgworldwide.data.ImageThreadLoader;
import com.mmgworldwide.data.Personality;
//http://code.google.com/p/and-conference/source/browse/trunk/src/com/totsp/conference/PresentationList.java
public class Personalities extends Activity{
private ListView listView;
private ArrayAdapter<Object> adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.personalities);
listView = (ListView) findViewById(R.id.personalitylistview);
listView.setDrawingCacheEnabled(false);
addListAdapter();
setFooterView("more");
}
private void addListAdapter(){
ArrayList<Object> adaptList = makeAdaptList();
adapter = new PersonalityListAdapter(this, 0, adaptList);
listView.setAdapter(adapter);
}
private ArrayList<Object> makeAdaptList(){
ArrayList<Object> adaptList = new ArrayList<Object>();
String currentDivDate = " ";
for(Personality aEvent : DataConnection.fwrInfo.getPersonalityList()){
adaptList.add(aEvent);
}
return adaptList;
}
private void setFooterView(String highlight){
Footer footer = (Footer) findViewById(R.id.footer);
footer.setHighlight(highlight);
}
//***********************************************************************************************************************************************
//ViewHolder
//***********************************************************************************************************************************************
static class ViewHolder {
private TextView tView1;
private TextView tView2;
private ImageView iView1;
}
//***********************************************************************************************************************************************
//PersonalityListAdapter
//***********************************************************************************************************************************************
private class PersonalityListAdapter extends ArrayAdapter<Object>{
LayoutInflater vi = (LayoutInflater) Personalities.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
private Context parentContext;
public ArrayList<Object> items_list_ref;
private ImageThreadLoader imageLoader = new ImageThreadLoader();
public PersonalityListAdapter(final Context context, final int resId, final ArrayList<Object> presentations) {
super(context, resId, presentations);
this.items_list_ref = presentations;
parentContext = context;
}
#Override
public int getCount() {
return items_list_ref.size();
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
//Log.d("TROY", "adding view");
View v = convertView;
if (v == null) {
//Log.d("TROY", "inflation");
v = vi.inflate(R.layout.picture_list, parent, false);
ViewHolder viewHolder = new ViewHolder();
viewHolder.tView1 = (TextView) v.findViewById(R.id.name_txt);
viewHolder.tView2 = (TextView) v.findViewById(R.id.title_txt);
viewHolder.iView1 = (ImageView) v.findViewById(R.id.portrait);
v.setTag(viewHolder);
}
Object p = items_list_ref.get(position);
if (p != null) {
//Log.d("TROY", "setting stuff");
ViewHolder viewHolder = (ViewHolder) v.getTag();
viewHolder.tView1.setText("hi");
}
return v;
}
}
}
Here is a screen shot of what's going on (why is the 5th preload graphic not showing?):
edit ------
Ok, I added the getCount and getItemId overrides but still have the same issues, I figured I would start a project from scratch and try again with just a listView, same issue, I have put up a test project to demonstrate this frustrating issue. In this test I did not even add any data to the adapters, and the animation only works for some of them, just like with my master project.
Thank you so much for your patience and help this far Michele, you have been very awesome.
http://faceonfire.com/temp/ListTester.zip
ListViews are highly optimized Datastructures. You should use ViewHolders to obey the rules of Lists and make the life of the system a bit easier.
When you Scroll a ListView the System caches the Items in Holders for performance.
Read How to load the Listview "smoothly" in android
you can also try to set
yourListView.setDrawingCacheEnabled(false);
edit: ok than try to set your animation with xml
http://developer.android.com/reference/android/graphics/drawable/AnimationDrawable.html
like:
<!-- Animation frames are wheel0.png -- wheel5.png files inside the
res/drawable/ folder -->
<animation-list android:id="selected" android:oneshot="false">
<item android:drawable="#drawable/wheel0" android:duration="50" />
<item android:drawable="#drawable/wheel1" android:duration="50" />
<item android:drawable="#drawable/wheel2" android:duration="50" />
<item android:drawable="#drawable/wheel3" android:duration="50" />
<item android:drawable="#drawable/wheel4" android:duration="50" />
<item android:drawable="#drawable/wheel5" android:duration="50" />
</animation-list>
edit2: please try to implement getCount and getItemId, theres something wrong with the boundarys of your List, maybe android cant find out on with position the list is after scrolling. Oh and can you please test it with random data, not the same item all the way (perhaps some weird hash (default getItemId Implementation?) that is always the same with the same item content).
for example like this:
#Override
public int getCount() {
return <yourdatastructure>.getSize();
}
#Override
public long getItemId(int position) {
return position;
}