Android : Adding EditText one below the old one dynamically - java

I am working on an Android application in which I want to add EditText below an EditText which is at the first added in XML, and then added in code one below the other. Even though I am giving margin from top 200, the new EditText is appearing on top right. What am I doing wrong?
XML file:
<?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="wrap_content"
android:background="#drawable/border"
android:orientation="horizontal"
>
<RelativeLayout
android:id="#+id/menuLayout"
android:layout_width="wrap_content"
android:layout_height="1000dp">
<ImageView
android:layout_width="fill_parent"
android:layout_height="180dp"
android:background="#drawable/bottom_border"
android:padding="3dp"
android:scaleType="fitXY"
android:src="#drawable/mittag_top" />
<EditText
android:id="#+id/date"
android:layout_width="wrap_content"
android:layout_height="35dp"
android:layout_alignParentEnd="true"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="80dp"
android:layout_marginStart="80dp"
android:layout_marginTop="125dp"
android:hint="Menu karte datum..."
android:lineSpacingExtra="10dp"
android:lineSpacingMultiplier="1"
android:paddingTop="7dp"
android:textColor="#color/abc_primary_text_material_dark"
android:textColorHint="#color/abc_primary_text_material_dark"
android:textSize="12sp" />
<EditText
android:id="#+id/time"
android:layout_width="wrap_content"
android:layout_height="35dp"
android:layout_alignLeft="#+id/menuDate"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:layout_alignStart="#+id/menuDate"
android:layout_below="#+id/menuDate"
android:hint="Opening times..."
android:lineSpacingExtra="10dp"
android:lineSpacingMultiplier="1"
android:paddingTop="7dp"
android:textColor="#color/abc_primary_text_material_dark"
android:textColorHint="#color/abc_primary_text_material_dark"
android:textSize="12sp" />
<EditText
android:id="#+id/firstEntry"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentStart="true"
android:layout_below="#+id/openTime"
android:textColor="#color/abc_primary_text_material_dark"
android:textColorHint="#color/abc_primary_text_material_dark"
android:hint="Menu entry.." />
</RelativeLayout>
</ScrollView>
Java code :
public class AddStuff extends Activity{
EditText firstEntry, date, time;
RelativeLayout relativeLayout;
Typeface type;
int counter = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.ocr_menu);
type = Typeface.createFromAsset(getAssets(),"fonts/MyFont.ttf");
firstEntry = (EditText)findViewById(R.id.firstEntry);
firstEntry.setTypeface(type);
date = (EditText)findViewById(R.id.date);
date.setTypeface(type);
time = (EditText)findViewById(R.id.time);
time.setTypeface(type);
relativeLayout = (RelativeLayout)findViewById(R.id.menuLayout);
firstEntry.addTextChangedListener(new TextWatcher(){
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
if (s.length() > 0) {
addEditText();
}
}
});
}
public void addEditText(){
EditText editText = new EditText(getApplicationContext());
editText.setHint("Entry number "+counter);
// editText.setPadding(2, 200, 2, 2);
TableLayout.LayoutParams params = new TableLayout.LayoutParams();
params.setMargins(2, 300, 0, 0);
editText.setHintTextColor(Color.WHITE);
editText.setTypeface(type);
relativeLayout.addView(editText);
counter++;
}
}
What am I doing wrong? How can I add EditText below the last added EditText. Thank you.
Update
updated addEdittext()
public void addEditText(){
EditText editText = new EditText(getApplicationContext());
editText.setHint("Entry number "+counter);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.MATCH_PARENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
int idLastChild= relativeLayout.getChildAt(relativeLayout.getChildCount()-1).getId();
params.addRule(RelativeLayout.BELOW,idLastChild);
editText.setHintTextColor(Color.WHITE);
editText.setTypeface(type);
relativeLayout.addView(editText);
editText.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
if (s.length() > 5) {
addEditText();
}
}
});
counter++;
}

Because adding dynamic EditText in RelativeLayout so need to use LayoutParams .addRule instead of margin to align EditText:
EditText editText = new EditText(AddStuff.this);
...
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.MATCH_PARENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
// get last child id from RelativeLayout
int idLastChild=relativeLayout.getChildAt(relativeLayout.getChildCount()-1);
params.addRule(RelativeLayout.BELOW,idLastChild);
// set id for EditText
editText.setId(idLastChild+1);
// set layout params
editText.setLayoutParams(params);
relativeLayout.addView(editText, params);

It's a relative layout. Not LinearLayout. You should specify how position of your view depends on other views.
RelativeLayout.LayoutParams params
= (RelativeLayout.LayoutParams) yourView.getLayoutParams();
params.addRule(RelativeLayout.BELOW, R.id.firstEntry);

You're creating the params, but not assigning them to the layout. Do as follow:
EditText editText = new EditText(getApplicationContext());
final LayoutParams lparams = new LayoutParams(50,30); // Width , height
editText.setLayoutParams(lparams);

Try this
public void addEditText(){
EditText editText = new EditText(getApplicationContext());
editText.setHint("Entry number "+counter);
// editText.setPadding(2, 200, 2, 2);
TableLayout.LayoutParams params = new TableLayout.LayoutParams();
params.setMargins(2, 300, 0, 0);
editText.setHintTextColor(Color.WHITE);
editText.setTypeface(type);
RelativeLayout.LayoutParams newParams = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
newParams.addRule(RelativeLayout.BELOW, R.id.date);
editText.setLayoutParams(newParams);
relativeLayout.addView(editText);
counter++;
}

Related

Change the whole style of my Android app with Java

I'm trying to programatically change the whole style (background color, font and font size) of my app based on which radio button has been checked (cf code below). I have read that for it to work I must write it in the onCreate method, since setTypeFace or setTextSize can't be resolved in other functions.
I also tried to call those two methods in another function, which is called setStyles, but those two methods still can't be resolved and I have no idea why.
I did import android.graphics.Typeface for the font.
Below are my Java code et two of my XML codes.
full Java code :
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LinearLayout buttonMenu = findViewById(R.id.dynamic_btn);
Button showBtn = new Button(this);
showBtn.setText(R.string.menu);
showBtn.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
showBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View v) {
//setStyles(v);
final View myView = getLayoutInflater().inflate(R.layout.style, null);
final AlertDialog.Builder diag = new AlertDialog.Builder(getApplicationContext());
diag.setTitle("Configuration de l'application");
diag.setPositiveButton("Enregistrer", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
RadioGroup radioColGroup = (RadioGroup) ((Dialog)dialog).findViewById(R.id.radioColor);
int col = Color.parseColor("#000000"); // background color
int selectedId = radioColGroup.getCheckedRadioButtonId();
Typeface type = getResources().getFont(R.font.fff_tusj);
if (selectedId == R.id.style1) {
// change background, font and size
col = Color.parseColor("#000000");
type = getResources().getFont(R.font.fff_tusj);
v.setTextSize(40);
}
if (selectedId == R.id.style2) {
// change background, font and size
col = Color.parseColor("#00574A");
type = getResources().getFont(R.font.sansation_light);
v.setTextSize(50);
}
else if (selectedId == R.id.style3) {
// change background, font and size
col = Color.parseColor("#6B0504");
type = getResources().getFont(R.font.oswald_stencil);
v.setTextSize(30);
}
View background = findViewById(R.id.layoutBackground);
background.setBackgroundColor(col);
v.setTypeFace(type);
}
});
diag.setNegativeButton("Annuler", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// do nothing
}
});
diag.setView(R.layout.style);
diag.show();
}
});
if(buttonMenu != null) {
buttonMenu.addView(showBtn);
}
}
public void setStyles(View view) {
final View myView = getLayoutInflater().inflate(R.layout.style, null);
final AlertDialog.Builder diag = new AlertDialog.Builder(this);
diag.setTitle("Configuration de l'application");
diag.setPositiveButton("Enregistrer", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
RadioGroup radioColGroup = (RadioGroup) ((Dialog)dialog).findViewById(R.id.radioColor);
int col = Color.parseColor("#000000"); // background color
int selectedId = radioColGroup.getCheckedRadioButtonId();
Typeface type = Typeface.createFromAsset(getAssets(), "fff_tusj.ttf");
if (selectedId == R.id.style1) {
// change background, font and size
col = Color.parseColor("#000000");
type = Typeface.createFromAsset(getAssets(), "oswald_stencil.ttf");
//myView.setTextSize();
}
if (selectedId == R.id.style2) {
// change background, font and size
col = Color.parseColor("#00574A");
type = Typeface.createFromAsset(getAssets(), "sansation_light.ttf");
}
else if (selectedId == R.id.style3) {
// change background, font and size
col = Color.parseColor("#6B0504");
}
View background = findViewById(R.id.layoutBackground);
background.setBackgroundColor(col);
//myView.setTypeFace(type);
}
});
diag.setNegativeButton("Annuler", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// do nothing
}
});
diag.setView(R.layout.style);
diag.show();
}
}
activity_main.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:orientation="vertical"
android:id="#+id/layoutBackground">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<LinearLayout
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/dynamic_btn"
android:layout_weight="1"/>
<EditText
android:id="#+id/saisie_recherche"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="5"
android:inputType="text"/>
<Button
android:id="#+id/recherche"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/recherche"/>
</LinearLayout>
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/resultats"/>
<!-- dynamic menu -->
</LinearLayout>
style.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:id="#+id/style">
<RadioGroup
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/radioColor"
android:orientation="horizontal"
android:layout_margin="50px"
android:gravity="center">
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/style1"
android:text="style 1"/>
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/style2"
android:text="style 2"/>
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/style3"
android:text="style 3"/>
</RadioGroup>
</LinearLayout>
If someone is interested in the answer, I actually changed how I do things.
To change fonts, font sizes and background color I created new themes in the layout file style.xml and declared three new themes.
Then according to the Radio button that was clicked on (if condition), I used the setTheme(nameOfTheme).
It works.

Validate the field in recyler view android

I need to validate the each field inside recylerview. I didn't find the best approach to perform the validation. The each Edittext field need to validation if the value is empty.Show the toast message on each empty value
Custom XML File
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<android.support.v7.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="#dimen/carview_margin">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1">
<EditText
android:id="#+id/ET_CT_foodeaten"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Food Eaten"
android:imeActionLabel="Food Eaten"
android:imeOptions="actionUnspecified"
android:maxLines="1"
android:singleLine="true" />
</android.support.design.widget.TextInputLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<RelativeLayout
android:id="#+id/rel_serving"
android:layout_width="wrap_content"
android:layout_alignParentLeft="true"
android:layout_height="wrap_content">
<LinearLayout
android:id="#+id/linear_ser"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_margin="#dimen/carview_margin"
android:text="Servings Eaten"
android:textSize="18dp" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="-10dp"
android:background="#drawable/linear_layout_radius_custom"
android:orientation="horizontal">
<ImageView
android:layout_width="60sp"
android:id="#+id/minus_foodeaten"
android:layout_height="50sp"
android:padding="#dimen/carview_margin"
android:src="#drawable/minus" />
<View
android:layout_width="1dp"
android:layout_height="35sp"
android:layout_gravity="center"
android:background="#color/TabHeaderColor" />
<ImageView
android:layout_width="60sp"
android:layout_height="50sp"
android:id="#+id/add_foodeaten"
android:padding="#dimen/carview_margin"
android:src="#drawable/ic_add" />
</LinearLayout>
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:layout_centerVertical="true"
android:layout_toRightOf="#+id/linear_ser"
android:orientation="vertical">
<ImageView
android:id="#+id/IMG_info"
android:layout_width="wrap_content"
android:layout_marginRight="15dp"
android:layout_height="wrap_content"
android:src="#drawable/info" />
<TextView
android:id="#+id/value_serving"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginRight="15dp"
android:text="0"
android:textSize="18dp" />
</LinearLayout>
</RelativeLayout>
<View
android:layout_width="1dp"
android:id="#+id/space_view"
android:layout_height="80sp"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:background="#color/TabHeaderColor" />
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_toRightOf="#+id/rel_serving">
<TextView
android:id="#+id/label_food"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_gravity="center"
android:layout_margin="#dimen/carview_margin"
android:text="Food Group"
android:textSize="18dp" />
<Spinner
android:id="#+id/CS_food_group_spinner"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_below="#+id/label_food"
android:layout_margin="#dimen/carview_margin"
android:drawSelectorOnTop="true"
android:spinnerMode="dropdown" />
</RelativeLayout>
</RelativeLayout>
</LinearLayout>
</android.support.v7.widget.CardView>
</LinearLayout>
Adapter code
public class CustomDataAdapterRecylerview extends RecyclerView.Adapter {
private List values;
private Activity activity;
AlertDialog alertDialogStores;
String[] foodLists;
FoodList[] val_list;
private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
FoodList food_list_value;
public CustomDataAdapterRecylerview(List<String> values, Activity context) {
this.values = values;
this.activity = context;
}
#Override
public CustomDataAdapterRecylerview.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.edittext_twospinner, viewGroup, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(ViewHolder viewHolder, int position) {
final ViewHolder holder = viewHolder;
final int pos = position;
viewHolder.info.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showPopUp();
}
});
final ArrayAdapter<CharSequence> foodGroup_adapter = ArrayAdapter.createFromResource(activity, R.array.Food_Group, android.R.layout.simple_spinner_item);
foodGroup_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
viewHolder.FoodGroup_spinner.setAdapter(foodGroup_adapter);
foodLists = new String[100];
val_list = new FoodList[100];
food_list_value = new FoodList();
viewHolder.FoodGroup_spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
food_list_value.setServingsEaten(parent.getItemAtPosition(position).toString());
SingletonAddValueFoodTracker.getInstance().setList_values(val_list);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
viewHolder.setClickListener(new RecyclerViewItemClickListener() {
#Override
public void onClick(View view, int position, boolean isLongClick) {
if (view.getId() == holder.Add_Food_Item.getId()) {
int val = Integer.parseInt(holder.valueserving.getText().toString());
if (val < 15) {
val++;
food_list_value.setServingsEaten(String.valueOf(val));
SingletonAddValueFoodTracker.getInstance().setList_values(val_list);
}
holder.valueserving.setText(String.valueOf(val));
} else if (view.getId() == holder.Minus_Food_Item.getId()) {
int val = Integer.parseInt(holder.valueserving.getText().toString());
if (val != 0) {
val--;
food_list_value.setServingsEaten(String.valueOf(val));
SingletonAddValueFoodTracker.getInstance().setList_values(val_list);
}
holder.valueserving.setText(String.valueOf(val));
}
{
//Toast.makeText(view.getContext(), "ROW PRESSED = " + String.valueOf(position), Toast.LENGTH_SHORT).show();
}
}
});
viewHolder.Food_Eaten.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
foodLists[pos] = String.valueOf(s);
food_list_value.setFoodEaten(foodLists[pos]);
val_list[pos] = food_list_value;
SingletonAddValueFoodTracker.getInstance().setList_values(val_list);
}
});
}
#Override
public int getItemCount() {
return values.size();
}
public void addItem(String country) {
values.add(country);
notifyItemInserted(values.size());
}
public void removeItem(int position) {
values.remove(position);
notifyItemRemoved(position);
notifyItemRangeChanged(position, values.size());
}
private void showPopUp() {
// add your items, this can be done programatically
// your items can be from a database
List<FoodTrackerAlertDialogModel> ObjectItemData = new ArrayList<FoodTrackerAlertDialogModel>();
ObjectItemData.add(new FoodTrackerAlertDialogModel("Fruit", "1 medium-sized piece of fruit", "1/2 cup berries", "3/4 cup fruit/veggie juice"));
ObjectItemData.add(new FoodTrackerAlertDialogModel("Vege\ntables", "1/2 cup raw not-leafy veggies", "1 cup raw leafy veggies", "1 small baked potato"));
ObjectItemData.add(new FoodTrackerAlertDialogModel("Dairy", "8 ounces milk", "1 cup yogurt", "1/2 ounces of cheese"));
ObjectItemData.add(new FoodTrackerAlertDialogModel("Grains", "1 slice bread", "1 ounce dry cereal", "1/2 cup cooked rice or pasta"));
ObjectItemData.add(new FoodTrackerAlertDialogModel("Lean\nMeat\nPoultry", "3 ounces cooked lean meat", "skinless poultry (about the size of a deck of cards)", "1 egg"));
ObjectItemData.add(new FoodTrackerAlertDialogModel("Fish", "", "2 to 3 oz. (about the size of the palm of a woman&apos;s hand)", ""));
ObjectItemData.add(new FoodTrackerAlertDialogModel("Snacks", "15 potato chips", "2 small cookies", "1/2 cup ice cream"));
ObjectItemData.add(new FoodTrackerAlertDialogModel("Fats\nOils", "2 tablespoons light salad dressing", "1 tablespoon low-fat margarine or mayonnaise", "1 teaspoon vegetable oil"));
// our adapter instance
ListViewArrayAdapter adapter = new ListViewArrayAdapter(activity, R.layout.listview_fourtextview, ObjectItemData);
// create a new ListView, set the adapter and item click listener
ListView listViewItems = new ListView(activity);
listViewItems.setAdapter(adapter);
//listViewItems.setOnItemClickListener(new OnItemClickListenerListViewItem());
// put the ListView in the pop up
alertDialogStores = new AlertDialog.Builder(activity)
.setView(listViewItems)
.setTitle("Examples of what a serving\n").setPositiveButton("Back", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
alertDialogStores.dismiss();
}
})
.show();
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener, View.OnLongClickListener {
EditText Food_Eaten;
ImageView info, Add_Food_Item, Minus_Food_Item;
Spinner FoodGroup_spinner;
TextView valueserving;
private RecyclerViewItemClickListener clickListener;
public ViewHolder(View view) {
super(view);
info = (ImageView) view.findViewById(R.id.IMG_info);
Food_Eaten = (EditText) view.findViewById(R.id.ET_CT_foodeaten);
FoodGroup_spinner = (Spinner) view.findViewById(R.id.CS_food_group_spinner);
valueserving = (TextView) view.findViewById(R.id.value_serving);
Add_Food_Item = (ImageView) view.findViewById(R.id.add_foodeaten);
Minus_Food_Item = (ImageView) view.findViewById(R.id.minus_foodeaten);
view.setOnClickListener(this);
view.setOnLongClickListener(this);
Add_Food_Item.setOnClickListener(this);
Minus_Food_Item.setOnClickListener(this);
}
public void setClickListener(RecyclerViewItemClickListener recyclerViewItemClickListener) {
this.clickListener = recyclerViewItemClickListener;
}
#Override
public void onClick(View v) {
clickListener.onClick(v, getPosition(), false);
}
#Override
public boolean onLongClick(View view) {
clickListener.onClick(view, getPosition(), true);
return true;
}
}
}
On click of correct icon if the edit text is empty a validation needs perform and show a toast message.
You need to use this check and print your toast in else part and your implementation in if part -
if (edittext.getText().length() > 0) {
// perform action here
} else {
// show toast here if edittext is empty
}
Hope it may be of help to you.

Set text inside fragment not working after revisiting fragment

I am developing an bus time table android app. I have three fragments.
Inside first fragment I have two radio buttons i.e. From Malegaon & To Malegaon. (Malegaon is name of place).
If I select From Malegaon radio button then I am setting text to sourceEditText as Malegaon. and If I select To Malegaon radio button then I am setting text to destinationEditText as Malegaon.
This condition is working fine, when I visit fragment first time, but if I revisit fragment then From Malegaon radio Button is already selected, sourceEditText is blank and destinationEditText has text as Malegaon.
Here is my snapshot and code for first fragment.
after selecting to Malegaon radio button.
I am just changing visibility of layout. (source edittext,destination edittext,search button is one layout)
OldStandFragment.java
public class OldStandFragment extends Fragment {
public static OldStandFragment fragment ;
private static final String ARG_POSITIONS = "position";
private int positions;
private View myFragmentViewOld;
private LinearLayout fromOldMalegoanView, toOldMalegoanView;
Button selectRouteButton;
public static final String required_dest = "Please Enter Destination";
public static final String required_source = "Please Enter Source";
String language = "";
DbHelper helper;
private String sourceId = "", destinationId = "";
private ArrayList<Route> myArrayList;
private RouteAdapter routeAdapter;
private ListView routeListView;
private EditText sourceEditTextFromMalegoanOld;
private EditText destinationEditTextFromMalegoanOld;
private ImageButton searchFromMalegoanButtonOld;
private EditText sourceEditTextToMalegoanOld;
private EditText destinationEditTextToMalegoanOld;
private ImageButton searchToMalegoanButtonOld;
private RadioButton fromOldMalegoanRadioButton, toOldMalegoanRadioButton;
public OldStandFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
positions = getArguments().getInt(ARG_POSITIONS);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
myFragmentViewOld = inflater.inflate(R.layout.fragment_old_stand, container, false);
selectRouteButton = (Button) myFragmentViewOld.findViewById(R.id.selectRouteButton);
fromOldMalegoanRadioButton = (RadioButton) myFragmentViewOld.findViewById(R.id.fromOldMalegoanRadioButton);
toOldMalegoanRadioButton = (RadioButton) myFragmentViewOld.findViewById(R.id.toOldMalegoanRadioButton);
fromOldMalegoanView = (LinearLayout) myFragmentViewOld.findViewById(R.id.fromOldMalegoanView);
toOldMalegoanView = (LinearLayout) myFragmentViewOld.findViewById(R.id.toOldMalegoanView);
sourceEditTextFromMalegoanOld = (EditText) fromOldMalegoanView.findViewById(R.id.sourceEditText);
destinationEditTextFromMalegoanOld = (EditText) fromOldMalegoanView.findViewById(R.id.destinationEditText);
searchFromMalegoanButtonOld = (ImageButton) fromOldMalegoanView.findViewById(R.id.searchResultButton);
sourceEditTextToMalegoanOld = (EditText) toOldMalegoanView.findViewById(R.id.sourceEditText);
destinationEditTextToMalegoanOld = (EditText) toOldMalegoanView.findViewById(R.id.destinationEditText);
searchToMalegoanButtonOld = (ImageButton) toOldMalegoanView.findViewById(R.id.searchResultButton);
SharedPreferences prefs = getContext().getSharedPreferences("MyPrefsFile", Context.MODE_PRIVATE);
int a = prefs.getInt("LangValue", 0);
if (a == 0) {
language = "English";
} else {
language = "मराठी";
}
helper = new DbHelper(getContext());
fromOldMalegoanRadioButton.setChecked(true);
toOldMalegoanRadioButton.setChecked(false);
fromOldMalegoanView.setVisibility(View.VISIBLE);
toOldMalegoanView.setVisibility(View.GONE);
String stopValue = helper.getStopName("1", language);
sourceEditTextFromMalegoanOld.setText(stopValue);
fromOldMalegoanRadioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (fromOldMalegoanRadioButton.isChecked()) {
toOldMalegoanRadioButton.setChecked(false);
fromOldMalegoanView.setVisibility(View.VISIBLE);
toOldMalegoanView.setVisibility(View.GONE);
helper = new DbHelper(getContext());
String stopValue1 = helper.getStopName("1", language);
sourceEditTextFromMalegoanOld.setText(stopValue1);
destinationEditTextFromMalegoanOld.setText("");
}
}
});
toOldMalegoanRadioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (toOldMalegoanRadioButton.isChecked()) {
fromOldMalegoanRadioButton.setChecked(false);
fromOldMalegoanView.setVisibility(View.GONE);
toOldMalegoanView.setVisibility(View.VISIBLE);
helper = new DbHelper(getContext());
String stopValue2 = helper.getStopName("1", language);
destinationEditTextToMalegoanOld.setText(stopValue2);
sourceEditTextToMalegoanOld.setText("");
}
}
});
searchFromMalegoanButtonOld.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//search result code.
}
});
searchToMalegoanButtonOld.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//search result code.
}
});
return myFragmentViewOld;
}
public static OldStandFragment newInstance(int position) {
if(fragment == null) {
fragment = new OldStandFragment();
}
Bundle bundle = new Bundle();
bundle.putInt(ARG_POSITIONS, position);
fragment.setArguments(bundle);
return fragment;
}
}
fragment_old_stand.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:orientation="vertical"
android:background="#000000"
android:scrollbars="vertical"
tools:context="com.ashishkudale.malegoanagar.Fragments.OldStandFragment">
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Select Direction or Route"
android:gravity="center"
android:textColor="#FFFFFF"
android:id="#+id/Note"
android:textStyle="bold"
android:textAppearance="?android:attr/textAppearanceMedium"
android:layout_margin="15dp" />
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<RadioGroup
android:id="#+id/rg_ContainerOld"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:layout_marginTop="15dp">
<RadioButton
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="From Malegaon"
android:id="#+id/fromOldMalegoanRadioButton"
android:layout_marginLeft="5dp"
android:checked="false" />
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp">
<include
android:id="#+id/fromOldMalegoanView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
layout="#layout/source_destination"
android:layout_margin="5dp" />
</LinearLayout>
<RadioButton
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="To Malegaon"
android:id="#+id/toOldMalegoanRadioButton"
android:layout_marginLeft="5dp" />
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp">
<include
android:id="#+id/toOldMalegoanView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
layout="#layout/source_destination"
android:layout_margin="5dp" />
</LinearLayout>
</RadioGroup>
</LinearLayout>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=" Select Route "
android:id="#+id/selectRouteButton"
android:background="#drawable/button_effect"
android:layout_gravity="center_horizontal"
android:layout_margin="5dp" />
</LinearLayout>
</ScrollView>
this is Adapter to call fragment.
MyPagerAdapter
public class MyPagerAdapter extends FragmentPagerAdapter {
private final String[] TITLES = {"Old Stand","New Stand", "Fare"};
public MyPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public CharSequence getPageTitle(int position) {
return TITLES[position];
}
#Override
public int getCount() {
return TITLES.length;
}
#Override
public android.support.v4.app.Fragment getItem(int position) {
android.support.v4.app.Fragment fragment = null;
if(position ==0) {
fragment = OldStandFragment.newInstance(position);
}else if(position ==1 ){
fragment = NewStandFragment.newInstance(position);
} else if (position == 2) {
fragment = MapFragment.newInstance(position);
}
return fragment;
}
}
after revisiting OldStandFragment it look like this.
I checked with adding logs everywhere possible. And I found that after revisiting OldStandFragment, toOldMalegoanRadioButton.setOnClickListner() method is getting called.
Now I want to refresh fragment when I re-visit or any other way to solve this issue.
You have to use SharedPreferences to save state of checkbox, try this code
public class StackOne extends AppCompatActivity {
SharedPreferences prefs;
private RadioButton rButton1, rButton2;
private RadioGroup rg_ContainerOld;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.stack_one);
prefs = PreferenceManager.getDefaultSharedPreferences(StackOne.this);
rButton1 = (RadioButton) findViewById(R.id.fromOldMalegoanRadioButton);
rButton2 = (RadioButton) findViewById(R.id.toOldMalegoanRadioButton);
rg_ContainerOld = (RadioGroup) findViewById(R.id.rg_ContainerOld);
GetSelectedRadioButton();
int k = prefs.getInt("rb1", 0);
if (k == 1) {
rButton1.setChecked(true);
sourceEditTextFromMalegoanOld.setText("");
} else if (k == 2) {
rButton2.setChecked(true);
sourceEditTextToMalegoanOld.setText("");
}
}
private void GetSelectedRadioButton() {
rg_ContainerOld.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
switch (group.getCheckedRadioButtonId()) {
case R.id.fromOldMalegoanRadioButton:
prefs.edit().putInt("rb1", 1).commit();
break;
case R.id.toOldMalegoanRadioButton:
prefs.edit().putInt("rb1", 2).commit();
break;
}
}
});
}
}
In your code you are dynamically setting checked state of radiobutton
fromOldMalegoanRadioButton.setChecked(true);
toOldMalegoanRadioButton.setChecked(false);
thats why your radiobutton's oncheckedchanged method will get call. And thats why code in it.

SeekBar null pointer exception

I am using SeekBar to change the opacity level in drawing But I am getting Nullpointer exception in the lines
seekOpq.setMax(100);
and
seekTxt.setText(currLevel);
in the following code..
public void onClick(View view){
if(view.getId()==R.id.opacity_btn){
//launch opacity chooser
final Dialog seekDialog = new Dialog(this);
final TextView seekTxt = (TextView)seekDialog.findViewById(R.id.opq_txt);
final SeekBar seekOpq = (SeekBar)seekDialog.findViewById(R.id.seek);
Toast.makeText(getApplicationContext(),
"start.", Toast.LENGTH_SHORT).show();
seekDialog.setTitle("Opacity level:");
seekDialog.setContentView(R.layout.opacity_chooser);
seekOpq.setMax(100);
int currLevel = drawView.getPaintAlpha();
seekTxt.setText(currLevel);
seekOpq.setProgress(currLevel);
seekOpq.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
seekTxt.setText(Integer.toString(progress)+" % ");
}
#Override
public void onStartTrackingTouch(SeekBar seekBar){}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {}
});
Button opqBtn = (Button)seekDialog.findViewById(R.id.opq_ok);
opqBtn.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
drawView.setPaintAlpha(seekOpq.getProgress());
Toast.makeText(getApplicationContext(),
"end.", Toast.LENGTH_SHORT).show();
seekDialog.dismiss();
}
});
}
I have tried giving numeric arguments manualy to these lines like
seekTxt.setText(50);
But the error still remains the same
This is my opacity_chooser.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:gravity="center"
android:orientation="vertical" >
<TextView
android:id="#+id/opq_txt"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:gravity="center"
android:text="100%"
android:textStyle="bold" />
<SeekBar
android:id="#+id/seek"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp" />
<Button
android:id="#+id/opq_ok"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="OK" />
</LinearLayout>
First set Content View after initialize seekbar & textview.
eg.
final Dialog seekDialog = new Dialog(this);
seekDialog.setContentView(R.layout.opacity_chooser);
final TextView seekTxt = (TextView)seekDialog.findViewById(R.id.opq_txt);
final SeekBar seekOpq = (SeekBar)seekDialog.findViewById(R.id.seek);
Toast.makeText(getApplicationContext(),
"start.", Toast.LENGTH_SHORT).show();
seekDialog.setTitle("Opacity level:");
seekOpq.setMax(100);
-------------------

Android Pagination ListView

Hi i have trouble in achieving pagination for listview in android. My task is to add Values from editTextto ListView and i need to add pagination to the list. But I tried and i am to insert only one value . While i try to add next values i end up in errors. Please kindly tell me the error on my code. i have added my layout,Activity and Log
MainActivity.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/agnes2_back"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.vivek.projectone.MainActivity" >
<LinearLayout
android:id="#+id/linearLayout1"
android:layout_width="match_parent"
android:layout_height="50dp"
android:background="#drawable/border" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="65dp"
android:layout_marginTop="15dp"
android:gravity="right"
android:text="#string/welcome"
android:textColor="#58FA58" />
<TextView
android:id="#+id/userView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="25dp"
android:layout_marginTop="15dp"
android:text="#string/userLabel"
android:textColor="#FF0000" />
</LinearLayout>
<LinearLayout
android:id="#+id/linearlayout2"
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_alignLeft="#+id/linearLayout1"
android:layout_below="#+id/linearLayout1"
android:layout_marginTop="14dp"
android:background="#drawable/border"
android:orientation="horizontal" >
<EditText
android:id="#+id/itemName"
android:layout_width="199dp"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="textPersonName" >
<requestFocus />
</EditText>
<Button
android:id="#+id/addButton1"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/adds"
android:text="" />
</LinearLayout>
<LinearLayout
android:id="#+id/linearLayout3"
android:layout_width="match_parent"
android:layout_height="210dp"
android:layout_alignLeft="#+id/linearlayout2"
android:layout_below="#+id/linearlayout2"
android:layout_marginTop="16dp"
android:background="#drawable/border"
android:orientation="horizontal" >
<ListView
android:id="#+id/listView1"
android:layout_width="match_parent"
android:layout_height="184dp"
android:layout_weight="2.32"
android:background="#android:color/transparent"
android:cacheColorHint="#android:color/transparent"
tools:listitem="#android:layout/simple_list_item_checked" >
</ListView>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignLeft="#+id/linearLayout3"
android:layout_alignParentBottom="true"
android:layout_below="#+id/linearLayout3"
android:orientation="horizontal" >
<Button
android:id="#+id/btn_Prev"
style="?android:attr/buttonStyleSmall"
android:layout_width="80dp"
android:layout_height="wrap_content"
android:layout_marginLeft="35dp"
android:layout_marginTop="10dp"
android:background="#drawable/buttonbackground"
android:text="#string/btn_prev" />
<Button
android:id="#+id/btn_Next"
style="?android:attr/buttonStyleSmall"
android:layout_width="80dp"
android:layout_height="wrap_content"
android:layout_marginLeft="50dp"
android:layout_marginTop="10dp"
android:background="#drawable/buttonbackground"
android:text="#string/btn_next" />
</LinearLayout>
</RelativeLayout>
MainActivity.java
public class MultipleActivity extends Activity implements OnItemClickListener {
Button addToList;
EditText viewListItem1, viewListItem2;
ListView customItemList;
PackageManager packageManager;
ArrayList<String> checkedCustomItem;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_multiple);
addToList = (Button) findViewById(R.id.adToListBtn);
viewListItem1 = (EditText) findViewById(R.id.viewEditItem1);
viewListItem2 = (EditText) findViewById(R.id.viewEditItem2);
packageManager = getPackageManager();
final List<PackageInfo> packageList = packageManager
public class MainActivity extends Activity {
String userLabel;
EditText itemName;
Button addBut;
Button multipleBtn;
ListView itemList;
private ArrayList<String> itemAList;
ArrayAdapter<String> itemAdapter;
private int pageCount;
private Button buttonPrev;
private Button buttonNext;
private int increment = 0;
public int TOTAL_LIST_ITEMS = 1030;
public int NUM_ITEMS_PAGE = 5;
String item;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView textView = (TextView) findViewById(R.id.userView);
itemName = (EditText) findViewById(R.id.itemName);
addBut = (Button) findViewById(R.id.addButton1);
buttonNext = (Button) findViewById(R.id.btn_Next);
buttonPrev = (Button) findViewById(R.id.btn_Prev);
itemList = (ListView) findViewById(R.id.listView1);
buttonPrev.setEnabled(false);
multipleBtn = (Button) findViewById(R.id.multipleValsBtn);
int val = TOTAL_LIST_ITEMS % NUM_ITEMS_PAGE;
val = val == 0 ? 0 : 1;
pageCount = TOTAL_LIST_ITEMS / NUM_ITEMS_PAGE + val;
Intent intent = getIntent();
userLabel = intent.getExtras().getString("emailID");
textView.setText(userLabel);
itemAList = new ArrayList<>();
itemAdapter = new ArrayAdapter<>(this,
android.R.layout.simple_list_item_1, itemAList);
itemList.setAdapter(itemAdapter);
itemList.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView parent, View v, int arg2,
long arg3) {
// TODO Auto-generated method stub
item = itemAList.get(arg2);
Toast.makeText(getApplicationContext(), item, 0).show();
}
});
buttonNext.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
increment++;
loadList(increment);
CheckEnable();
}
});
buttonPrev.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
increment--;
loadList(increment);
CheckEnable();
}
});
addBut.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
item = itemName.getText().toString();
itemAList.add(0, item);
loadList(0);
itemName.setText("");
}
});
multipleBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent = new Intent(MainActivity.this,
MultipleActivity.class);
startActivity(intent);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, 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);
}
private void CheckEnable() {
if (increment + 1 == pageCount) {
buttonNext.setEnabled(false);
} else if (increment == 0) {
buttonPrev.setEnabled(false);
} else {
buttonPrev.setEnabled(true);
buttonNext.setEnabled(true);
}
}
private void loadList(int number) {
ArrayList<String> sort = new ArrayList<String>();
int start = number * NUM_ITEMS_PAGE;
for (int i = start; i < (start) + NUM_ITEMS_PAGE; i++) {
if (i < itemAList.size()) {
sort.add(itemAList.get(i));
} else {
break;
}
}
itemAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, sort);
itemList.setAdapter(itemAdapter);
}
}
You need to use setAdapter only once. For changing the list item next time (for loading next 5 items), you just need to use next notifyDataSetChanged
private void loadList(int number) {
ArrayList<String> sort = new ArrayList<String>();
int start = number * NUM_ITEMS_PAGE;
for (int i = start; i < (start) + NUM_ITEMS_PAGE; i++) {
if (i < itemAList.size()) {
sort.add(itemAList.get(i));
} else {
break;
}
}
if(itemAdapter ==null){
itemAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, sort);
itemList.setAdapter(itemAdapter);
}
else{
itemAdapter.notifyDataSetChanged();
}
}
Though I didn't get what you are doing, but try to do this change:
Remove this line
itemAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, sort);
or Add add one more line below this line
itemList.setAdapter(itemAdapter);
Because you have already called :itemAdapter.notifyDataSetChanged(); it should update the list.

Categories