How to clear and add new texts to a dynamically created TextView? - android

I have added a TextView dynamically in a loop. On a button click, I want to clear the existing text in the text view and set some other text to it. How can I do this?
This is my current code:
ArrayList<String> Cheif_ComplaintNew = new ArrayList<String>();
int cc_Arraylist_length = Cheif_ComplaintNew.size();
android.widget.TextView cc_new = new android.widget.TextView(getApplicationContext());
for(int i=0; i<cc_Arraylist_length; i++)
{
cc_new.setId(i);
cc_new.setText(Cheif_ComplaintNew.get(i));
cc_new.setTextColor(getResources().getColor(R.color.black));
cc_new.setTypeface(null,android.graphics.Typeface.ITALIC);
cc_new.setTextSize(14);
cc_linearNew.addView(cc_new);
System.out.println("id"+i);
}
On a button click, the list is cleared and new data is stored in it. I want to display the new data in the same text view by clearing the old one.

You can either add the text to the textbox when you are creating it or assign it a class variable when you create it and later on you can add text to it.
TextView dynamicTextView;
...
private void CreateNewTextView()
{
dynamicTextView = Your New Text View;
}
...
private void ChangeTheText()
{
dynamicTextView.SetText("new value");
}
if you have more than one TextView you can create a class level generic list of TextViews and add them to the list and call them later.
you can also create a map of all TextView so you can call them with their key as well.

I think you can set a tag to cc_new before add it to cc_linearNew, like this: cc_new.setTag(i). when button got click, you can find those TextView by cc_linearNew.findViewByTag(i) in loop, and set new data to them.

Depends on how many TextViews you need to add to the layout dynamically.
As per the code mentioned, no TextViews are added to the layout as: Cheif_ComplaintNew.size() would return "0" so your loop will not be executed.
If you have to add only one TextView, then I agree with Daniel's answer of having a class level TextView variable.
If its multiple TextViews and you know which ID to use then in your Activity you can always get that TextView by calling findViewById("ID_OF_THE_TEXTVIEW_NEEDED")

You can do this in many ways, some of them :
Store your just created ids in array. Then just get your views calling parentView.findViewById(arreyOfIds(0));
Bad for performance do not do this :) - remove all of just added views from your parentView and create them one more time.
To handle back click in Activity use :
#Override
public void onBackPressed()
{
clearTextView();
}
All of this will simple look like this :
private List<Integer> ids = new ArrayList<Integer>();
#Override
public void onBackPressed()
{
clearTextView();
}
private void clearTextView()
{
for(Integer id : ids)
{
TextView view = (TextView)findViewById(id);
view.setText("")
}
}
private void createTextViews()
{
ArrayList<String>Cheif_ComplaintNew = new ArrayList<String> ();
int cc_Arraylist_length=Cheif_ComplaintNew.size();
android.widget.TextView cc_new = new android.widget.TextView(getApplicationContext() );
for(int i=0; i<cc_Arraylist_length; i++)
{
ids.add(i)
cc_new.setId(i);
cc_new.setText(Cheif_ComplaintNew.get(i));
cc_new.setTextColor(getResources().getColor(R.color.black));
cc_new.setTypeface(null,android.graphics.Typeface.ITALIC);
cc_new.setTextSize(14);
cc_linearNew.addView(cc_new);
System.out.println("id"+i);
}
}

Related

Select multiple items from recycler view list delete not working Properly

if (RFidList.size() >0){
for (String s: RFidList){
RFidTagValueList.remove(s);
}
}
mTimeAdapter.notifyDataSetChanged();
dialog.dismiss();
when choose multiple items in recyclerview checkbox not working / and am use private ArrayList<String> data = new ArrayList<>();
You can't move and delete from the list. The best option to do this is to have an array that will remember the state of the checkbox. Scrolling through your recycler view will always change the state of the checkbox and maybe won't remember it. The way to do this is to add an array of boolean
private boolean[] checkStates;
then inside your constructor of the adapter do this.
checkStates = new boolean[data.size()];
This way you'll create an array of boolean filled with FALSE value the same size your data array is. Now, inside your adapter when you are binding your view do this for the checkbox.
holder.checkbox.setChecked(checkStates[position]);
Also, don't use onCheckedChangeListener on checkbox inside adapter. This will be called even when you scroll and it will change whatever you are doing inside the function. What you can do is override onClick for the checkbox, but there is something tricky here. When you click the checkbox to check it, inside the onClick method the view will have the state as it is already checked so to follow this do it like this:
holder.checkbox.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Checkbox c = (CheckBox) v;
checkStates[position] = c.isChecked();
}
});
I wrote this from my head and maybe there are some mistakes but you'll get the point. The animation of the check state will be handled you just need to handle changes inside the checkStates array.
Now your checkbox will always have the state it had before. After this, you can create a function to delete items from your data.
public void removeItems() {
ArrayList<YOUR-MODEL> items_to_delete = new ArrayList<>();
for (int i = 0; i < checkStates.length(); ++i) {
if (checkStates[i]) items_to_delete.add(data.get(i]);
}
data.removeAll(items_to_delete);
notifyDataSetChanged();
checkStates = new boolean[data.size()];
}
This works if your data is a type of ArrayList. I think this is the best way to go.

Android - RecyclerView - Scrolling to specific textview

In my application, I want to scroll to a specific TextView in a RecyclerView if an intent specifies to scroll there. The original implementation involved looking at a listView, and looking at each item in it until I found a string matching the expected TextView string. I'm not sure how to replicate this for a RecyclerView. The closest I got to it was to look at the PreferenceGroupAdapter, but it seems to be a restricted class.
Create a method that returns the position of that TextView within your adapter. For this example, I created a very simple RecyclerView.Adapter that just holds a List<String> items and is looking for the string "target".
private int getTargetPosition(RecyclerView recycler) {
MyAdapter adapter = (MyAdapter) recycler.getAdapter();
for (int i = 0; i < adapter.items.size(); i++) {
if (adapter.items.get(i).equals("target")) {
return i;
}
}
throw new AssertionError("target is guaranteed to be in the list");
}
After that, it's as easy as calling scrollToPosition():
int position = getTargetPosition(recycler);
recycler.scrollToPosition(position);

programatically add textview inside recyclerview onbindView adapter

On scrolling the RecyclerView the data inside the TextView changes even though the data in the array logtime.get(i).getTime() does not change.it changes only when we place the data inside textview which is generating dynamically.
public void onBindViewHolder(PunchCardViewHolder holder, int position) {
PunchCardReport punchCardReport = punchCardReports.get(position);
holder.sNumber.setText(punchCardReport.getmSNumber());
holder.logDate.setText(punchCardReport.getmLogDate());
StringTokenizer stringTokenizer = new StringTokenizer(punchCardReport.getmLogTime(), ",");
List<LogTime> logtime = punchCardReport.getmLogTimeList();
for (int i = 0; i < logtime.size(); i++) {
Log.d(TAG, "onBindViewHolder: "+logtime.get(i).getTime());
}
LinearLayout.LayoutParams dim = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
for (int i = 0; i < logtime.size(); i++) {
TextView textView=new TextView(mContext);
textView.setLayoutParams(dim);
textView.setText(logtime.get(i).getTime());//the problem is here when we put data inside textview
holder.logTime.addView(textView);
}
}
#Override
public int getItemCount () {
return punchCardReports.size();
}
Your design is completely wrong. You are creating new TextViews on every call to onBindViewHolder() which means when you scroll back to a view a fresh list of TextViews are created, so now you have two sets of TextViews one from last call and one from now (Keep scrolling and there will be more extra TextViews attached).
Creating new Views should be done in onCreateViewHolder(). The reason you are getting this behavior could be because RecyclerView uses Scrapped Views, which means that it reuses the Views created earlier. Thus enhancing performance (because no new memory allocations are required). If you are looking for a Nested RecyclerView then do that instead.
You can add following code in onBindViewHolder.
if(holder.logTime.getChildCount()>0){
holder.logTime.removeAllViews();
}
for (int i = 0; i < logtime.size(); i++) {
TextView textView=new TextView(mContext);
textView.setLayoutParams(dim);
textView.setText(logtime.get(i).getTime());
//the problem is here when we put data inside textview
holder.logTime.addView(textView);
}
Try to Put this line in starting of onbindViewHolder.
holder.setIsRecyclable(false);
Or, you can put your TextView inside XML file. There is no need to create dynamic textview inside Onbinder.
You just add holder.setIsRecyclable(false); inside method onBindViewHolder in your Adapter

android- Appending textView objects to a LinearLayout by clicking on a button from a different page (multiple times)

I have two Activities. Activity 1 is designed to take in user input (EditText), and has a button that (if clicked) will go to activity 2. In activity 2, there is a LinearLayout and a button that will take you back to activity 1. I can currently add one textView (containing the user input from activity 1) to the LinearLayout in activity 2, but I would like to add several textView objects to the LinearLayout. When I try to add user input any time after the first, it simply replaces the textView object that held the information from the user input that was entered the first time.
From Activity 1 (AddExercise):
public class AddExercise extends AppCompatActivity {
private EditText name;
private EditText weight;
private EditText sets;
private EditText reps;
private String deets;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_exercise);
Button button = (Button) findViewById(R.id.button5);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
goToAddWorkout();
}
});
}
private void goToAddWorkout() {
Intent intent = new Intent(this, AddWorkout.class);
name = (EditText) findViewById(R.id.name);
weight = (EditText) findViewById(R.id.weight);
sets = (EditText) findViewById(R.id.sets);
reps = (EditText) findViewById(R.id.reps);
deets = name.getText().toString() + "\n\t\tWeight: " + weight.getText().toString() + "\n\t\tSets: " + sets.getText().toString() + "\n\t\tReps: " + reps.getText().toString();
intent.putExtra("details", deets);
startActivity(intent);
}
}
From Activity 2 (AddWorkout):
public class AddWorkout extends AppCompactActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_workout);
LinearLayout vBox = (LinearLayout) findViewById(R.id.vBox);
Bundle extras = getIntent().getExtras();
if (extras != null) {
TextView tv = new TextView(this);
tv.setText(extras.getString("details").toString());
vBox.addView(tv);
}
Button button = (Button) findViewById(R.id.button3);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
goToAddExercise();
}
});
}
}
You can try a public static List of String each time you can add your text to list and then On your second activity create text-view as per your list count. And add to your linear-layout.
For more click here....
So you want to be able to add multiple entries in your second activity, for every time you add one in the first. I would recommend a different and easier approach.
In your second activity, use a listview/recyclerview, instead of adding new textview. This has the added advantage that once you have added enough entries, scrolling won't be an issue.
Maintain a global list of entries, which you add the entries to. And populate the listview using this list.
you should try something like that as said by roshan-
((ArrayAdapter)listView.getAdapter()).insert(data_object, index);
((ArrayAdapter)listView.getAdapter()).notifyDataSetChanged();
use a shared preference for index... every time you come to second activity increment the index... on exit of app just clear the shared pref index variable.
Also you can add textview in your each list view item
There can be several ways to do it according to me, pick the one that suits your relevant application.
have a single activity and host two fragments. So you can share the data between the fragments using single activity. (Recommended way, I guess Fragments will ease the job for you.). Also you can store a local variable in Activity so that each time you start your application you can start it afresh, if its intended!
If not, you can use SharedPreferences. For each button click, add a string to the preference. When you add one more click, append the new data with a separator like ("|", "||").. So in Activity one write to the preference, in activity 2 read from the preference and display it as list view of dynamically create the linear layout and append it to the root layout.
Declare a static ArrayList in your Activity 1 and access it in activity 2. (Really bad way)

Get the values from one layout to next layout?

I've listed some items in list that extends Activity and the list are listed using Custom Adapter. My question is, this is my xml File I've added some items to this spinner. How can i get the spinner values to next layout. Anyone knows then please tell me? Advance thanks.
I'm not clear on what you're actually asking here, but as a guess there are two possible things you're asking
How to get the currently selected value out of the Spinner
How to set the same value to a spinner in the next layout
1.
Is simple enough
((Spinner)findViewById(R.id.spinner1)).getSelectedItem()
Will return the object selected by your spinner.
Is slightly more complex, you'll need to determine what index in the data supplied corresponds to the result you get from getSelectedItem(), for example if you had an array of Strings then you could search through until you found the index and then set it on the new spinner.
For example:
String[] options = new String[] {"One","Two","Three","Four"};
String val = (String)((Spinner)findViewById(R.id.spinner1)).getSelectedItem();
//.......pass this to a layout/activity etc.........
for (int i=0; i<options.length; i++)
{
if (options[i].equals(test))
{
((Spinner)findViewById(R.id.spinner2).setSelection(i);
break;
}
}
But your best bet would be to try and explain more clearly what you're asking.
first you have to select data from spinner using
spinnerobject.setOnItemSelectedListener(
new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent,
View view, int position, long id)
{
Spinner spinnerobject = (Spinner) findViewById(R.id.Spinner02);
string value = (String)spinnerobj.getSelectedItem();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
}
});
then u hava to use intent for sending it to next activity..
Use
Intent.putExtra(..):
intent.putExtra("keyName", "somevalue");
This method is overloaded and takes various types as second argument: int, byte, String, various arrays..
To get the data out use appropriate getXYZExtra(). For String this is:
getStringExtra(String keyName)
First thing :: you can pass value from one activity to second activity not one layout to second
second :: if you need to pass value from one activity to second use
first activity::
activity.putExtra("lastpage", lastscore5);
*here lastpage is key which unique for aplication
second activity::
Intent i1 = getIntent();
var = i1.getIntExtra("lastpage", 1);

Categories

Resources