I am adding programatically and dynamically some elements (buttons and text views) with android. I also need to set the setOnClickListener event for each of these buttons and from that event execute some action on the click of button:
do
{
EditText txt1 = new EditText(this);
EditText txt2 = new EditText(this);
Button showtxt = new Button(this);
linearLayout.addView(showtxt );
linearLayout.addView(txt1);
linearLayout.addView(txt2);
showtxt.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
String aaa= txt1 .getText().toString();//HOW TO ACCESS txt1 and txt2 from here
String bbb= txt2 .getText().toString();
}
}
}
while(somecondition)
I am almost new to android. How can I access to txt1 and txt2 in the click callback function?
You need to make the define the variables where they will have class wide scope:
public class Example extends Activity {
EditText txt1;
EditText txt2;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
txt1 = new EditText(this);
txt2 = new EditText(this);
...
Now your onClick function will be able to see txt1 and txt2.
Alternatively
Since you appear to be creating a lot of txt1 and txt2 in one LinearLayout, you can pass your Button a reference to its EditTexts:
do {
...
// EditText[] array = { txt1, txt2 };
// is the short version of
EditText[] array = new EditText[2];
array[0] = txt1;
array[1] = txt2;
showtxt.setTag(array);
showtxt.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
EditText[] array = (EditText[]) v.getTag();
String aaa = array[0].getText().toString();
String bbb = array[1].getText().toString();
Log.v("Example", aaa + " " + bbb);
}
});
} while(some condition)
This may not be not ideal, however without any further context I cannot guess your ultimate goal. Hope that helps!
Last Suggestion
If we call the Button and two EditTexts a row, you could store each row in a ViewGroup or View of its own. Say you wanted to have background colors for each row:
View row = new View(this); // or this could be another LinearLayout
row.setBackgroundColor(0x0000ff);
// Create and add the Button and EditTexts to row, as in row.addView(showtxt), etc
...
linearLayout.addView(row);
showtxt.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
View row = v.getParent()
String aaa = ((EditText) row.getChildAt(1)).getText().toString();
String bbb = ((EditText) row.getChildAt(2)).getText().toString();
Log.v("Example", aaa + " " + bbb);
}
});
Related
Hi everyone.
I'd like to add a clickable url in the errormsg shown by using TextView.setError(msg) method.
please take a look on my code.
final EditText testview = findViewById(R.id.testview);
final TextView textView = findViewById(R.id.testtextview);
Button btntest = findViewById(R.id.testbutton);
btntest.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
testview.setMovementMethod(new LinkMovementMethod());
testview.setError(Html.fromHtml("testurl click me "));
LayoutInflater inflater = LayoutInflater.from(testview.getContext());
TextView err = (TextView) inflater.inflate(
Resources.getSystem().getIdentifier("textview_hint","layout", "android"), null);
err.setMovementMethod(LinkMovementMethod.getInstance());
textView.setMovementMethod(LinkMovementMethod.getInstance());
textView.setText(Html.fromHtml("testurl click me "));
textView.setError(Html.fromHtml("testurl click me "));
inflater = LayoutInflater.from(textView.getContext());
err = (TextView) inflater.inflate(
Resources.getSystem().getIdentifier("textview_hint","layout", "android"), null);
err.setMovementMethod(LinkMovementMethod.getInstance());
}
});
I have tried to setMovementMethod() on the specific TextView, which shows the errormsg, but the "click me" seems remain unclickable.
Thanks again.
If you can call setMovementMethod on error textview then this solution is perfect
final EditText testview = findViewById(R.id.editText);
final TextView textView = findViewById(R.id.testtextview);
Button btntest = findViewById(R.id.testbutton);
SpannableStringBuilder ssb = new SpannableStringBuilder(Html.fromHtml("testurl click me "));
URLSpan[] urlSpans = ssb.getSpans(0,ssb.length(),URLSpan.class);
int start = ssb.getSpanStart(urlSpans[0]);
int end = ssb.getSpanEnd(urlSpans[0]);
testview.setMovementMethod(LinkMovementMethod.getInstance());
ClickableSpan span = new ClickableSpan() {
#Override
public void onClick(#NonNull View view) {
Log.d("Cust","C");
}
};
ssb.setSpan(span,start,end,Spannable.SPAN_INCLUSIVE_INCLUSIVE);
//testview.setError(span.toString());
testview.setError(ssb);
I have about 50 different textviews in a linear layout in a scrollview
its like this
1.This is the first textview
2.This is the second textview
3.This is the third textview
4.This is the fourth textview
5.This is the fifth textview
6.This is the sixth textview
7.This is the seventh textview
8.This is the eighth textview
9.This is the ninth textview
10.This is the tenth textview
I have an edittext and button for search ,what i want is when i enter a number say 6 in the edittext and click the button then it should show or go to 6.This is the sixth textview,also i dont want other textviews to disappear,i just want the camera to move to textview number 6.
Please Help!!
public static void scrollToView(final ScrollView scrollView, final View view) {
view.requestFocus();
final Rect scrollBounds = new Rect();
scrollView.getHitRect(scrollBounds);
if (!view.getLocalVisibleRect(scrollBounds)) {
new Handler().post(new Runnable() {
#Override
public void run() {
scrollView.smoothScrollTo(0, view.getBottom());
}
});
}
}
Button clickButton = (Button) findViewById(R.id.yout_button_id);
clickButton.setOnClickListener( new OnClickListener() {
#Override
public void onClick(View v) {
String n = ((EditText) findViewById(R.id.your_edittext_id)).getText();
int tn = Integer.parseInt(n); //TODO: check the view exists
TextView tv = (TextView)((LinearLayout)findViewById(R.id.your_linearlayout_id)).getChildAt(tn);
scrollToView((ScrollView)findViewById(R.id.yout_scrollview_id, tv);
}
});
After clicking a button my code creates a row in table with a TextView , an EditView and a delete button. The delete button is programmed to delete the row from the table (which successfully does) and the date from a list in Notes.class (which is the problem). To confirm this action i have a text view to count the list size with the dates and when i press the delete button nothing is changed.
Sorry if this is a silly question but i am really new to Android :)
The button handler
public void addButtonHandler(View view) {
TableLayout tl = (TableLayout) findViewById(R.id.subs_table);
TableRow tr = new TableRow(this);
tr.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.WRAP_CONTENT));
//get the date in string
String date = new SimpleDateFormat("dd-MM-yyyy").format(new Date());
//the TextView with the date
TextView tv = new TextView(this);
tv.setText(date);
tv.setTextSize(TypedValue.COMPLEX_UNIT_SP , 18);
//editText with the type
final EditText et = new EditText(this);
TableRow.LayoutParams params = new TableRow.LayoutParams(getPx(50), ViewGroup.LayoutParams.WRAP_CONTENT);
params.setMargins(getPx(130),0,getPx(40),0);
et.setLayoutParams(params);
SharedPreferences prefs = getSharedPreferences(SubsPREFERENCES , MODE_PRIVATE); // get notes object
Gson gsonN = new Gson();
String jsonN = prefs.getString("DATES" , "");
final Notes notes = gsonN.fromJson(jsonN , Notes.class);
//button for deleting row
ImageButton imageButton = new ImageButton(this);
TableRow.LayoutParams imageParams = new TableRow.LayoutParams(50,70);
imageParams.setMargins(5 ,0 ,0 ,0);
imageButton.setLayoutParams(imageParams);
imageButton.setImageResource(R.drawable.ok);
imageButton.setClickable(true);
imageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ViewGroup parent = (ViewGroup) view.getParent();
ViewGroup gradnparent = (ViewGroup) parent.getParent();
gradnparent.removeView(parent);
notes.delete(tv.getText().toString()); // this does not seem to work
}
}
);
// Adding views in row
tr.addView(tv);
tr.addView(et);
tr.addView(imageButton);
// Adding row in table
tl.addView(tr, new TableLayout.LayoutParams(TableLayout.LayoutParams.MATCH_PARENT
, TableLayout.LayoutParams.WRAP_CONTENT));
//add info in note
notes.addNote(date , et.getText().toString());
// saving the changes in notes
SharedPreferences sharedPreferences =getSharedPreferences(SubsPREFERENCES ,MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
String json1 = gsonN.toJson(notes);
editor.putString("DATES" , json1);
editor.apply();
//display the number of objects in list
TextView textView = (TextView) findViewById(R.id.textView);
textView.setText(String.valueOf(notes.getNum_dates()));
}
The notes class
package com.uni.notes;
public class Notes {
private ArrayList<String> list =new ArrayList<String>();
private ArrayList<String> type =new ArrayList<String>();
public Notes() {}
public int getNum_dates() {return list.size();}
public void addNote(String date ,String typeN) {
list.add(date);
type.add(typeN);
}
public String getDate (int pos){
return list.get(pos);
}
public String getType (int pos) {return type.get(pos);}
public void delete (String thing) {
for (String element : list){
if (element.equals(thing) ){
list.remove(element);
}
}
}
}
Just after
notes.delete(et.getText().toString()); // this does not seem to work
move your textview counting element update :
notes.delete(et.getText().toString()); // this does not seem to work
//display the number of objects in list
TextView textView = (TextView) findViewById(R.id.textView);
textView.setText(String.valueOf(notes.getNum_dates()));
This will update the counting Textview rigth after you clicked the delete button.
I am beginner to learn android,I have assigned table row value by dynamically.
But I am not able to get the row value using on click listener method .
Can any one please help to solve the issues .
I have tried following methods
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.passbook);
TableLayout tl = (TableLayout) findViewById(R.id.mytable);
tl.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//obj.myShow(Passbook.this, v.getTag() + ": Row is clicked" );
}
});
}
You have to set the onClickListener on the row not the layout.
I think this is what u need...try this and modify as u wish...
//...
tr.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
TableRow t = (TableRow) view;
TextView firstTextView = (TextView) t.getChildAt(0);
TextView secondTextView = (TextView) t.getChildAt(1);
String firstText = firstTextView.getText().toString();
String secondText = secondTextView.getText().toString();
}
});
//...
I successfully created a dynamic TextView and a Button now when ever the button was clicked the value of a TextView changes.
But the problem is I have a final "submit button" outside a loop which should get the INDIVIDUAL values of each TextView and I cant think of a way how to do it can someone pls give me an approach for this thanks!. pls be nice..
code
Cursor citem= sdb.rawQuery("SELECT * FROM ITEM INNER JOIN CATEGORY ON item.categoryid = category.id where category.categoryname='"+fcat+"'", null);
ScrollView scrollView= new ScrollView(this);
LinearLayout mainLayout= new LinearLayout(this);
mainLayout.setOrientation(LinearLayout.VERTICAL);
Button border = new Button(this);
border.setId(Integer.parseInt(cuser.getString(cuser.getColumnIndex("id"))));;
border.setText("ORDER");
while (citem.moveToNext())
{
byte[] blob =citem.getBlob(citem.getColumnIndex("itemimage"));
int id = Integer.parseInt(citem.getString(citem.getColumnIndex("id")));
LinearLayout linearLayout = new LinearLayout(this);
linearLayout.setOrientation(LinearLayout.HORIZONTAL);
linearLayout.setTag(id);
int i;
ImageView iv = new ImageView(this);
iv.setId(id);
iv.setImageBitmap(dh.getPhoto(blob));
final TextView txtquantity = new TextView(this);
txtquantity.setId(id);
txtquantity.setText("0");
txtquantity.setTextSize(20);
final TextView txtprice = new TextView(this);
txtprice.setId(id);
txtprice.setText(citem.getString(citem.getColumnIndex("itemprice")));
txtprice.setTextSize(30);
ImageButton btn1 = new ImageButton(this);
btn1.setId(id);
final int id_ = btn1.getId();
btn1.setImageResource(R.drawable.ic_launcher);
btn1.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
int i = 0;
i=Integer.parseInt((String) txtquantity.getText())+1;
txtquantity.setText(String.valueOf(i));
totalprice.setText(String.valueOf(Integer.parseInt(totalprice.getText().toString())+(Integer.parseInt(txtprice.getText().toString())*1)));
}
});
ImageButton btn2 = new ImageButton(this);
btn2.setId(id);
final int id2_ = btn2.getId();
btn2.setImageResource(R.drawable.ic_launcher);
btn2.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
if(Integer.parseInt((String)txtquantity.getText())<=0)
{
}
else
{
int i=0;
i= Integer.parseInt((String) txtquantity.getText())-1;
txtquantity.setText(String.valueOf(i));
totalprice.setText(String.valueOf(Integer.parseInt(totalprice.getText().toString())-(Integer.parseInt(txtprice.getText().toString())*1)));
}
}
});
linearLayout.addView(iv);
linearLayout.addView(txtprice);
linearLayout.addView(btn1);
linearLayout.addView(txtquantity);
linearLayout.addView(btn2);
mainLayout.addView(linearLayout);
}
mainLayout.addView(totalprice);
mainLayout.addView(border);
scrollView.addView(mainLayout);
setContentView(scrollView);
Not quite sure what problem you're having? If it's just reading all the TextViews you created in the loop, then you should just keep a list, and send it off for processing when you submit...
List<TextView> tv_list = new ArrayList<TextView>();
while(...){
//In loop..add your tv's
TextView some_tv = new TextView()
tv_list.add(some_tv);
...
}
//In the submit, send them off for processing...
private void process_tvs(List<TextView> tv_list){
for(TextView tv:tv_list){
//Assuming your tv's have numbers...
int val = Integer.valueOf(tv.getText().toString());
//do something....
}
}