Error using relative layout using code - java

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);
}
}

Related

Getting all launchable apps on home like android home menu with bottom dots

Hi i am working on a custom launcher app.I want to get all launchable apps on home like this.
My Current Code:
MainActivity.class
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;
import java.util.Collections;
import java.util.List;
public class MainActivity extends AppCompatActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recycalview);
LinearLayoutManager mLinearLayoutManager = new LinearLayoutManager(this);
StaggeredGridLayoutManager mGridLayoutManager = new StaggeredGridLayoutManager(4, StaggeredGridLayoutManager.VERTICAL); // 2 is number of items per row
recyclerView.setLayoutManager(mGridLayoutManager); // deafult
PackageManager pm = this.getPackageManager();
Intent main = new Intent(Intent.ACTION_MAIN, null);
main.addCategory(Intent.CATEGORY_LAUNCHER);
List<ResolveInfo> launchables = pm.queryIntentActivities(main, 0);
Collections.sort(launchables,
new ResolveInfo.DisplayNameComparator(pm));
Adapter adapter = new Adapter(this, launchables, pm);
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(mGridLayoutManager);
}
}
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"
tools:context=".MainActivity2">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recycalview"
android:layout_below="#+id/battery"
android:layout_width="match_parent"
android:layout_above="#id/hi"
android:layout_height="match_parent" />
</RelativeLayout>
Adapter.java
import android.annotation.SuppressLint;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.Bitmap;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
import java.util.List;
public class Adapter extends RecyclerView.Adapter<Adapter.ViewHolder> {
List<ResolveInfo> lapps;
Context context;
PackageManager pm=null;
public Adapter(Context context, List<ResolveInfo> apps, PackageManager pn) {
this.context = context;
lapps=apps;
pm=pn;
}
#NonNull
#Override
public Adapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.griditem, parent, false);
Adapter.ViewHolder viewHolder = new Adapter.ViewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(#NonNull Adapter.ViewHolder holder, #SuppressLint("RecyclerView") int position) {
holder.images.setImageDrawable(lapps.get(position).loadIcon(pm));
holder.text.setText(lapps.get(position).loadLabel(pm));
holder.itemlayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ResolveInfo launchable = lapps.get(position);
ActivityInfo activity = launchable.activityInfo;
ComponentName name = new ComponentName(activity.applicationInfo.packageName,
activity.name);
Intent i = new Intent(Intent.ACTION_MAIN);
i.addCategory(Intent.CATEGORY_LAUNCHER);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
i.setComponent(name);
context.startActivity(i);
}
});
}
#Override
public int getItemCount() {
return lapps.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
ImageView images;
TextView text;
RelativeLayout itemlayout;
public ViewHolder(View view) {
super(view);
images = (ImageView) view.findViewById(R.id.icon);
text = (TextView) view.findViewById(R.id.label);
itemlayout=view.findViewById(R.id.item);
}
}
}
griditem.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:id="#+id/item"
android:layout_marginTop="5dp"
android:gravity="center"
android:layout_height="wrap_content">
<com.google.android.material.imageview.ShapeableImageView
android:layout_width="60dp"
android:layout_height="60dp"
android:id="#+id/icon"
android:theme="#style/Theme.RoundedImage"/>
<TextView
android:layout_width="60dp"
android:layout_height="20dp"
android:layout_marginTop="5dp"
android:layout_below="#id/icon"
android:gravity="center_horizontal"
android:textSize="15dp"
android:textColor="#color/white"
android:textStyle="bold"
android:id="#+id/label"/>
</RelativeLayout>
I just want to show all apps on home screen with horizontal scroll with bottom dots.
I have also try this method but my issue can't solved

ANDROID fragment is not able to add or replace with new fragment

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

Adding views to another line (another LinearLayout)?

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.

Application stopped working when loading layout with setContentView

Here's the XML layout:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/search_lyt"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
android:name="search_act"
tools:context="com.example.app.Hisp$PlaceholderFragment">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/imageView2"
android:src="#drawable/hispania_lgs"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Back"
android:id="#+id/back2"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Info"
android:id="#+id/info2"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true" />
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/model_list"
android:layout_below="#+id/textViewML"
android:layout_alignParentRight="true"
android:layout_above="#+id/back2"
android:choiceMode="singleChoice" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="Select any of the models below and press Info for the model's specifications"
android:id="#+id/textViewML"
android:layout_below="#+id/imageView2"
android:layout_alignLeft="#+id/model_list" />
And using the setContentView method results in an 'Application stopped working'.
setContentView(R.layout.search_hisp);
Any idea on how to fix this? I'm quite new to Android Development and still trying to find how to switch layouts the correct way.
Well, even I change the onCreate()' setContentView to R.layout.search_hisp and gave me the error on startup. So my guess is it's probably from the XML file or something.
Thanks in advance!
Edit, there's the error:
>
03-25 12:10:23.415 20858-20858/com.example.app E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.ClassCastException: android.widget.TextView cannot be cast to android.widget.EditText
at com.example.app.Hisp.beginSearch(Hisp.java:121)
at com.example.app.Hisp$3.onClick(Hisp.java:107)
at android.view.View.performClick(View.java:4231)
at android.view.View$PerformClick.run(View.java:17537)
at android.os.Handler.handleCallback(Handler.java:725)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:158)
at android.app.ActivityThread.main(ActivityThread.java:5751)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1083)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:850)
at dalvik.system.NativeStart.main(Native Method)
03-25 12:10:23.420 515-550/? E/EmbeddedLogger﹕ App crashed! Process: com.example.app
03-25 12:10:23.420 515-550/? E/EmbeddedLogger﹕ App crashed! Package: com.example.app v1 (1.0)
03-25 12:10:23.420 515-550/? E/EmbeddedLogger﹕ Application Label: Hisp_Selector
And here's the code:
package com.example.app;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.IntentSender;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.res.AssetManager;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.database.DataSetObserver;
import android.database.DatabaseErrorHandler;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Handler;
import android.os.Looper;
import android.os.UserHandle;
import android.preference.DialogPreference;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View.OnClickListener;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.view.ViewGroup;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.view.Window;
import android.view.WindowManager;
import android.os.Build;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.ListAdapter;
import android.widget.ListView;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import android.widget.LinearLayout;
public class Hisp extends ActionBarActivity {
public static ActionBarActivity activity;
Context ctx;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
activity = this;
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_hisp);
TextView txt = (TextView) findViewById(R.id.textViewML);
Button btn = (Button) g(R.id.search);
Button rst = (Button) g(R.id.reset);
rst.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
finish();
startActivity(getIntent());
}
});
OnClickListener _rdb = new OnClickListener() {
#Override
public void onClick(View view) {
((CheckBox) g(R.id.R134a)).setChecked(false);
((CheckBox) g(R.id.R22)).setChecked(false);
((CheckBox) g(R.id.R404A)).setChecked(false);
((CheckBox) g(R.id.R507A)).setChecked(false);
((CheckBox) view).setChecked(true);
}
};
((CheckBox) g(R.id.R134a)).setOnClickListener(_rdb);
((CheckBox) g(R.id.R22)).setOnClickListener(_rdb);
((CheckBox) g(R.id.R404A)).setOnClickListener(_rdb);
((CheckBox) g(R.id.R507A)).setOnClickListener(_rdb);
btn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
beginSearch();
}
});
/*
if (stanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
*/
}
public void beginSearch() {
((EditText) g(R.id.rh)).setText("Test##".toCharArray(), 0, "Test##".length());
Boolean err = false;
try {
if (!(Double.parseDouble((((EditText) g(R.id.capacity)).getText().toString().trim())) >= 0 &&
isBetween(-35, 5, Integer.parseInt(((EditText) g(R.id.evaptemp)).getText().toString().trim())) &&
isBetween(28, 58, Integer.parseInt(((EditText) g(R.id.condtemp)).getText().toString().trim())) &&
isBetween(5, 13, Integer.parseInt(((EditText) g(R.id.dt1)).getText().toString().trim()))
)) err = true;
} catch(Exception e) {
err = true;
}
if (err) {
showMessageBox("ERROR", "Make sure you have filled all the fields correctly.", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
} else {
setContentView(R.layout.search_hisp);
}
}
public View g(int id) {
return activity.findViewById(id);
}
public Boolean isBetween(Integer i1, Integer i2, Integer ix) {
if (ix >= i1 && ix <= i2) return true;
return false;
}
public void showMessageBox(Object ttl, Object msg, DialogInterface.OnClickListener rt) {
new AlertDialog.Builder(activity)
.setMessage(msg.toString())
.setTitle(ttl.toString())
.setCancelable(false)
.setNeutralButton(android.R.string.ok, rt)
.show();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.hisp, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_hisp, container, false);
return rootView;
}
}
}
Because in onCreate() you have used
EditText textViewML = (EditText) findViewById(R.id.textViewML);
instead of
TextView txt = (TextView) findViewById(R.id.textViewML);
so you got problem. So you need to use after your setContentView() method.
TextView txt = (TextView) findViewById(R.id.textViewML);
Put in the onCreate :
TextView textViewML = (TextView) findViewById(R.id.textViewML);
The error was from
((EditText) g(R.id.rh)).setText("Test##".toCharArray(), 0, "Test##".length());
Thanks a lot guys for pointing this out!
you are casting Textview to EditText dont do that
EditText textViewML = (EditText) findViewById(R.id.textViewML);
change it as
TextView textViewML = (TextView) findViewById(R.id.textViewML);
Exception is not your layout file it is in your java file you are casting TextView into EditText.
You can not Cast Super class in to sub class.
you can cast Sub class into Super Class.
You can Cast EditText into TextView but not TextView in to EditText.
Change this line
TextView txt = (TextView) findViewById(R.id.textViewML);
Thanx

custom ImageViews disapearing from ListAdapter

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;
}

Categories

Resources