Rendering EditText of SortableTableView - android

I'am using SortableTableView to show sqlite table in android application. I want to add edit-button that are outside tables. How to enable editing mode for SortableTableView when edit-button is pressed?
I tried the code like this but it does not work.
/* EditDataAdapter.java */
// THIS IS NOT WORKED ???
public void setRenderEditable() {
int row = 0;
LinearLayout rowView = new LinearLayout(_tableView.getContext());
for (int col = 0; col < _tableView.getColumnModel().getColumnCount(); col++) {
View cellView = getLongPressCellView(row, col, rowView);
int cellWidth = _tableView.getColumnModel().getColumnWidth(col, _tableView.getWidth());
LinearLayout.LayoutParams cellLayoutParams = new LinearLayout.LayoutParams(cellWidth, LinearLayout.LayoutParams.WRAP_CONTENT);
cellView.setLayoutParams(cellLayoutParams);
_tableView.addView(cellView);
_tableView.invalidate();
}
}
/* EditFragment.java */
// Calling EditDataAdapter
ServerSortableTableView tableView = (ServerSortableTableView) rootView.findViewById(R.id.server_table);
if (tableView != null) {
EditDataAdapter editDataAdapter = new EditDataAdapter(getContext(), ServerDataFactory.readServerList(), tableView);
tableView.setDataAdapter(editDataAdapter);
}
Button editButton = (Button) rootView.findViewById(R.id.edit_button);
if (editButton != null) {
editButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (editButton.getText().toString().equals("edit")) {
editDataAdapter.setRenderEditable(); // This is not worked
editButton.setText("save");
} else {
editButton.setText("edit");
}
}
});
}

I found a solution to my problem. I will share here, it may be useful to others.
public void setRenderEditable() {
_tableView.setMinimumWidth(900);
_tableView.removeViewAt(1);
int row = 0;
LinearLayout rowView = new LinearLayout(_tableView.getContext());
for (int col = 0; col < _tableView.getColumnModel().getColumnCount(); col++) {
View cellView = getLongPressCellView(row, col, rowView);
int cellWidth = _tableView.getColumnModel().getColumnWidth(col, _tableView.getWidth());
LinearLayout.LayoutParams cellLayoutParams = new LinearLayout.LayoutParams(cellWidth, LinearLayout.LayoutParams.WRAP_CONTENT);
cellView.setLayoutParams(cellLayoutParams);
rowView.addView(cellView);
}
_tableView.addView(rowView, 1);
}

Related

Recycler view with multiple layout items duplicate radio buttons on scroll

RecyclerView containing multiple layouts such as one row containing Edittext, radioButtons another row containing checkbox etc
Now when I input in first edit text and scroll the list then same inputed value gets copied in the last edit text visible on the screen.
Also if there are two radio buttons visible say radio1 and radio 2 then on scroll this becomes
radio1
radio2
radio1
radio2
i.e. radio1 and radio 2 are duplicated on scroll.
Can any one suggest some solution for the same?
Code for dynamic Edit Text
private void configureViewHolderText(final ViewHolderText holderText, final int position) {
if (questionsArrayList != null && questionsArrayList.size() > 0) {
String hint = questionsArrayList.get(position).getHelperText();
int characterLength = questionsArrayList.get(position).getCharLimit();
boolean isQuestionRequired = questionsArrayList.get(position).isRequired();
if (isQuestionRequired) {
holderText.getTv_dynamic_star().setVisibility(View.VISIBLE);
}
holderText.getTv_dynamic_text_view().setText(questionsArrayList.get(position).getQuestionText());
if (characterLength > 0) {
holderText.getEt_dynamic_edit_text().setFilters(new InputFilter[]{new InputFilter.LengthFilter(characterLength)});
}
if (hint != null && hint.equals("null") == false && hint.equals("") == false) {
holderText.getEt_dynamic_edit_text().setHint(hint);
} else {
holderText.getEt_dynamic_edit_text().setHint("Enter Answer");
}
holderText.getEt_dynamic_edit_text().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) {
editTextInput = holderText.getEt_dynamic_edit_text().getText().toString();
// SubmitAnswerRequest submitAnswerRequest = new SubmitAnswerRequest();
// SubmitAnswerRequest.answers answers = submitAnswerRequest.new answers();
// hashAnswerInput.put(questionsArrayList.get(position).get_id(), editTextInput);
/*hashQuestionText.put(questionsArrayList.get(position).get_id(), questionsArrayList.get(position).getQuestionText()) ;
hashQuestionId.put(questionsArrayList.get(position).get_id(), questionsArrayList.get(position).get_id()) ;
hashAnswerType.put(questionsArrayList.get(position).get_id(), questionsArrayList.get(position).getAnswerType());*/
/* for(Map.Entry map : hashAnswerInput.entrySet() )
{
dynamicEditTextAnswer = String.valueOf(map.getValue());
//answers.setAnswerText(inputAnswer);
}*/
/*if(dynamicEditTextAnswer!= null)
{*/
SubmitAnswerRequest submitAnswerRequest = new SubmitAnswerRequest();
SubmitAnswerRequest.answers answers = submitAnswerRequest.new answers();
answers.setQuestionText(questionsArrayList.get(position).getQuestionText());
answers.setQuestionId(questionsArrayList.get(position).get_id());
answers.setAnswerText(editTextInput);
answers.setAnswerType(questionsArrayList.get(position).getAnswerType());
answersArrayList.put(questionsArrayList.get(position).get_id(),answers);
/* }*/
/*for(Map.Entry map : hashQuestionText.entrySet() )
{
String inputAnswer = String.valueOf(map.getValue());
answers.setQuestionText(inputAnswer);
}
for(Map.Entry map : hashQuestionId.entrySet() )
{
String inputAnswer = String.valueOf(map.getValue());
answers.setQuestionId(inputAnswer);
}
for(Map.Entry map : hashAnswerType.entrySet() )
{
String inputAnswer = String.valueOf(map.getValue());
answers.setAnswerType(inputAnswer);
}*/
// SubmitAnswerRequest submitAnswerRequest = new SubmitAnswerRequest();
// SubmitAnswerRequest.answers answers = submitAnswerRequest.new answers();
// answers.setQuestionText(questionsArrayList.get(position).getQuestionText());
// answers.setQuestionId(questionsArrayList.get(position).get_id());
// answers.setAnswerText(editTextInput);
// answers.setAnswerType(questionsArrayList.get(position).getAnswerType());
// answersArrayList.add(answers);
}
#Override
public void afterTextChanged(Editable s) {
}
});
}
}
Code for dynamic radio button
private void configureViewHolderRadioGroup(final ViewHolderRadioGroup holderRadioGroup, final int position) {
if (questionsArrayList != null && questionsArrayList.size() > 0) {
ArrayList<String> radioOptionsList = new ArrayList<String>();
for (int j = 0; j < questionsArrayList.get(position).getOptions().size(); j++) {
String radioItemName = questionsArrayList.get(position).getOptions().get(j).getOptionText();
radioOptionsList.add(radioItemName);
}
holderRadioGroup.getTv_dynamic_text_view().setText(questionsArrayList.get(position).getQuestionText());
boolean isQuestionRequired = questionsArrayList.get(position).isRequired();
if (isQuestionRequired) {
holderRadioGroup.getTv_dynamic_star().setVisibility(View.VISIBLE);
}
int totalCount = questionsArrayList.get(position).getOptions().size();
final RadioButton[] rb = new RadioButton[totalCount];
for (int i = 0; i < totalCount; i++) {
rb[i] = new RadioButton(context);
rb[i].setText(radioOptionsList.get(i));
rb[i].setId(i);
holderRadioGroup.getRg_dynamic_radio_group().addView(rb[i]); //the RadioButtons are added to the radioGroup instead of the layout
holderRadioGroup.getRg_dynamic_radio_group().setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
for (int i = 0; i < group.getChildCount(); i++) {
RadioButton rg = (RadioButton) group.getChildAt(i);
if (rg.getId() == checkedId) {
radioInput = rg.getText().toString();
Toast.makeText(context, radioInput, Toast.LENGTH_SHORT).show();
SubmitAnswerRequest submitAnswerRequest = new SubmitAnswerRequest();
SubmitAnswerRequest.answers answers = submitAnswerRequest.new answers();
answers.setQuestionText(questionsArrayList.get(position).getQuestionText());
answers.setQuestionId(questionsArrayList.get(position).get_id());
answers.setAnswerText(radioInput);
answers.setAnswerType(questionsArrayList.get(position).getAnswerType());
// answersArrayList.add(answers);
answersArrayList.put(questionsArrayList.get(position).get_id(),answers);
ArrayList<String> relatedQuestionsId = new ArrayList<String>();
relatedQuestionsId = questionsArrayList.get(position).getOptions().get(i).getRelatedQuestionIds();
if (relatedQuestionsId != null && relatedQuestionsId.size() > 0) {
for (int k = 0; k < relatedQuestionsId.size(); k++) {
((LinearLayout) holderRadioGroup.getLl_parent_radio_child()).removeAllViews();
getRadioChildQuestions(relatedQuestionsId, holderRadioGroup, k);
}
}
return;
}
else if(rg.getId() != checkedId) {
ArrayList<String> relatedQuestionsId = new ArrayList<String>();
/*for (int j = 0; j < questionsArrayList.get(position).getOptions().size(); j++) {*/
relatedQuestionsId = questionsArrayList.get(position).getOptions().get(i).getRelatedQuestionIds();
if (relatedQuestionsId != null && relatedQuestionsId.size() > 0) {
for (int k = 0; k < relatedQuestionsId.size(); k++) {
((LinearLayout) holderRadioGroup.getLl_parent_radio_child()).removeAllViews();
}
}
}
}
}
});
}
}
}
The recycler view reuses your view holders instances.
So if you are scrolling and a layout is leaving the screen at the top, it gets reused, when the same layout should be used for a new item at the bottom.
You need to reset all dynamic attribues in the onBindViewHolder-method.
For a better understanding set two debug points inside your recycler view adapter:
One inside the onCreateViewHolder-method and one inside the onBindViewHolder-method.
EDIT:
A sample for a working Recycler View Adapter can be found here: https://github.com/olLenz/Movies-with-Kotlin/blob/master/base/src/main/java/com/lenz/oliver/movieswithkotlin/ui/home/HomeAdapter.kt
The onCreateViewHolder-method creates a new instance of the ViewHolder.
The onBindViewHolder-method just calls the bind-method on a created ViewHolder instance. This bind-method sets all dynamic information to the given layout on every call.

How can get dynamic button text from another dynamic button OnClickListener event

I want get second dynamic button text from another dynamic button OnClickListener event:
Here is define some dynamic buutons:
LinearLayout lv=(LinearLayout)findViewById(R.id.lv);
for (int k = 1; k <= str[0].length(); k++) {
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(100, 100);
btnTopEn = new Button(this);
btnTopEn.setId(k);
final int id_ = btnTopEn.getId();
btnTopEn.setText(" ");
lv.addView(btnTopEn, params);
btnTopEn = ((Button) findViewById(id_));
final Button finalBtnT = btnTopEn;
btnTopEn.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
finalBtnT.setText("");
}
});
}
Now I want text of second button from OnClickListener Event:
TableLayout layout = (TableLayout)findViewById(R.id.TableL);
String stt="RZCEADHPTAUJTSFR";
int l=0;
for (int f=0; f<=1; f++) {
TableRow tr = new TableRow(this);
for (int c=0; c<=7; c++) {
btnCEn = new Button (this);
String ss=(String.valueOf(stt.charAt(l)));
btnCEn.setText(ss);;
final Button finalBtnB = btnCEn;
btnCEn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
int m=2;
btnTopEn = ((Button) findViewById(m));
final Button finalBtnT = btnTopEn;
if (finalBtnT.getText().equals("")) {
String stGetText=finalBtnB.getText().toString();
finalBtnT.setText(stGetText);
break;
}
}
}
});
TableRow.LayoutParams lp = new TableRow.LayoutParams(100,100);
tr.addView(btnCEn, lp);
}
layout.addView(tr);
}
I wrote some code in OnClickListener event but none happen!
What is the value of str in the first loop ?
Also you are setting the text to a space .
btnTopEn.setText(" ");
And while checking you check for empty :
if (finalBtnT.getText().equals("")){
}
Try changing to
if (finalBtnT.getText().toString().trim().equals("")){
}

Add ImageButton dynamically from Database not displayed

I'm here today for my soundboard app ! son to make it simple i have a G_Son object which is the controller of the "Son" model. i get the list of sound from my database (everything is fine until here) but then when I dynamically try to create ImageButtons and add them on my activity (manageLayout() ), I have absolutely nothing appearing on my activity ! not even a single button. So if you have any Idea, or want to give me a hand, I'm aware of any suggestion
private G_Son gson;
private OurNiceSoundPlayer soundPlayer;
private List<Son> sons;
RelativeLayout gameBoard;
private Son selectedSound;
private View.OnClickListener mSoundOnClickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
soundPlayer.setSound(sons.get(Integer.parseInt(v.getTag().toString())));
Log.i("Board", "Clicked on ImgButton ->" + v.getTag());
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_board);
gson = G_Son.getInstance();
sons = gson.getSons(getApplicationContext());
soundPlayer = new OurNiceSoundPlayer(getApplicationContext());
gameBoard = (RelativeLayout) findViewById(R.id.soundboard);
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
lp.addRule(RelativeLayout.CENTER_IN_PARENT,1);
manageLayout();
gameBoard.invalidate();
}
private void manageLayout() {
if (sons.size()>0)
{
int rawNbr = (int) Math.ceil((double) sons.size() / 3);
int currentSon = 0;
Son displayed = sons.get(currentSon);
for (int i = 0; i < rawNbr; i++)
{
LinearLayout row = new LinearLayout(this);
row.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
for (int j = 0; j < 3; j++)
{
ImageButton btnTag = new ImageButton(this);
if (displayed.getIsPerso()) {
File imgFile = new File(displayed.getPathImage());
if (imgFile.exists()) {
Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
btnTag.setImageBitmap(myBitmap);
} else {
btnTag.setImageResource(R.drawable.defaultimage);
}
}
else
{
int id = getResources().getIdentifier("com.example.m.sbst:drawable/" + displayed.getPathImage(), null, null);
btnTag.setImageResource(id);
}
btnTag.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
btnTag.setOnClickListener(mSoundOnClickListener);
btnTag.setBackgroundColor(Color.TRANSPARENT);
btnTag.setTag(currentSon);
btnTag.setId(i);
row.addView(btnTag);
currentSon++;
if (currentSon>=sons.size())
{
break;
}
else
{
displayed = sons.get(currentSon);
}
}
gameBoard.addView(row);
}
}
}
Forgot to mention a size, moreover, after months of learning android, I should advice people to use a grid view to do so, it allows with custom layout to do event better than creating your own layout with dynamic image buttons

Remove dynamically generated textviews on dynamic button click event

I need to remove each Table Rows on an individual button click event.
The Buttons are dynamically generated.
How will i achieve this?
Below is my code:
public class S2 extends Modify implements OnClickListener {
Button b;
String arry1[], category_main,str = null, catarray[];
int i,key = 0;
private static String url = "http://ashapurasoftech.com/train/test.json";
private static final String TAG_a = "menu",TAG_Name = "Name",TAG_Cat = "Category";
JSONArray items = null;
ArrayList<HashMap<String, String>> itemList;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.modify);
category_main = "";
new Getitems().execute(category_main);
b =(Button) findViewById(R.id.Order);
b.setOnClickListener(this);
itemList = new ArrayList<HashMap<String, String>>();
}
#Override
public void onClick(View arg0) {
switch(arg0.getId()){
case R.id.Order:try{ onbuttonclick();} catch(JSONException e){}
break;
}
}
private void onbuttonclick() throws JSONException {
TableRow[] tr = new TableRow[arry1.length];
final TextView[] tx = new TextView[arry1.length];
GridLayout gl = new GridLayout(S2.this);
gl.setRowCount(arry1.length);
gl.setColumnCount(1);
final TableLayout tl = (TableLayout) findViewById(R.id.tb1);
TableRow row = null;
for (i = 0; i < arry1.length; i++) {
final String cat = arry1[i].toString();
tx[i] = new TextView(S2.this);
tx[i].setLayoutParams(new TableRow.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
tx[i].setAllCaps(true);
tx[i].setTextSize(15);
tx[i].setText(cat);
tr[i] = new TableRow(S2.this);
tr[i].setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
tr[i].addView(tx[i],new TableRow.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
tl.addView(tr[i],new TableLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
int buttonsInRow = 0;
int numRows = tl.getChildCount();
if( numRows > 0 ){
row = (TableRow) tl.getChildAt( numRows - 1 );
buttonsInRow = row.getChildCount();
}
if( numRows == 0 || buttonsInRow == 3 ){
row = new TableRow( this );
tl.addView( row );
buttonsInRow = 0;
}
if( buttonsInRow < 3 ){
Button b = new Button( this );
b.setText("Cancel");
b.setId(i);
row.addView( b, 100, 50 );
}
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
b = (Button) findViewById(i);
tl.removeView(tx[i]);
}
});
}
}
this is my screen where i want to clear each items when i click on the button aside it.
you can probably achieve what you need in
onClick(View arg0)
by getting the arg0 parent. check it is
instanceof
Table row or has a tag you set up and then set its visibility to GONE
You can use removeView method in the similar fashion you are using addView:
tr[i].removeView(<YourTextView>;

Android Twitter Application Development and Usage of TextView and Linkify

I'm on developing a twitter kind of Application where in I want that the user would be displayed the timelines and the Textview in the Lists require to perform clicks on (http://)URLs, (#)usernames, and (#)hasTags and I want to invoke custom methods over these actions, I have used the Linkify class and the actions but where of no use because the customization that i require cannot be incorporated.
I have a solution to the problem to check it out go to the below mentioned link http://www.orangeapple.org/?p=354
Here is my solution.
The main idea is to split the text words and creating a TextView for each one, wrapping each line with horizontal LinearLayout and the lines into vertical LinearLayout:
private LinearLayout mDescription; // vertical LinearLayout
private void setDescriptionText(String twitterText){
String[] splitted;
String regexp = "(#[-a-zA-Z0-9_]*)|(#[-a-zA-Z0-9_]*)|(http://[-a-zA-Z0-9/._]*)|(https://[-a-zA-Z0-9/._]*)|( )";
TextSplitter splitter = new TextSplitter(regexp);
splitted = splitter.split(twitterText);
TextView[] textViews = new TextView[splitted.length];
for (int i = 0; i < splitted.length; i++) {
final String str = splitted[i];
TextView textView = new TextView(mDescription.getContext());
textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 16);
textViews[i] = textView;
textView.setText(str);
textView.setTypeface(roboReg);
textView.setTextColor(Color.WHITE);
if (str.startsWith("#")){
textView.setTextColor(mLinkColor);
textView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
startWebViewActivity("https://twitter.com/"+str.substring(1));
}
});
}else if (str.startsWith("#")){
textView.setTextColor(mLinkColor);
textView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
startWebViewActivity("https://twitter.com/#!/search/?q="+str.substring(1) + "&src=hash");
}
});
}else if (str.startsWith("http://") || str.startsWith("https://")){
textView.setTextColor(mLinkColor);
textView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
startWebViewActivity(str);
}
});
}
}
int maxWidth = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 210, getResources().getDisplayMetrics());
populateText(mDescription, maxWidth , textViews, mDescription.getContext());
}
private void populateText(LinearLayout ll,int maxWidth, View[] views, Context mContext) {
ll.removeAllViews();
LinearLayout.LayoutParams params;
LinearLayout newLL = new LinearLayout(mContext);
newLL.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT));
newLL.setGravity(Gravity.LEFT);
newLL.setOrientation(LinearLayout.HORIZONTAL);
int widthSoFar = 0;
for (int i = 0; i < views.length; i++) {
LinearLayout LL = new LinearLayout(mContext);
LL.setOrientation(LinearLayout.HORIZONTAL);
LL.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.BOTTOM);
LL.setLayoutParams(new ListView.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
views[i].measure(0, 0);
params = new LinearLayout.LayoutParams(views[i].getMeasuredWidth(),
LayoutParams.WRAP_CONTENT);
LL.addView(views[i], params);
LL.measure(0, 0);
widthSoFar += views[i].getMeasuredWidth();// YOU MAY NEED TO ADD THE MARGINS
if (widthSoFar >= maxWidth) {
ll.addView(newLL);
newLL = new LinearLayout(mContext);
newLL.setLayoutParams(new LayoutParams(
LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT));
newLL.setOrientation(LinearLayout.HORIZONTAL);
newLL.setGravity(Gravity.LEFT);
params = new LinearLayout.LayoutParams(LL
.getMeasuredWidth(), LL.getMeasuredHeight());
newLL.addView(LL, params);
widthSoFar = LL.getMeasuredWidth();
} else {
newLL.addView(LL);
}
}
ll.addView(newLL);
}
private class TextSplitter {
private Pattern pattern;
private boolean keep_delimiters;
public TextSplitter(Pattern pattern, boolean keep_delimiters) {
this.pattern = pattern;
this.keep_delimiters = keep_delimiters;
}
public TextSplitter(String pattern, boolean keep_delimiters) {
this(Pattern.compile(pattern == null ? "" : pattern), keep_delimiters);
}
public TextSplitter(String pattern) {
this(pattern, true);
}
public String[] split(String text) {
if (text == null) {
text = "";
}
int last_match = 0;
LinkedList<String> splitted = new LinkedList<String>();
Matcher m = this.pattern.matcher(text);
while (m.find()) {
splitted.add(text.substring(last_match, m.start()));
if (this.keep_delimiters) {
splitted.add(m.group());
}
last_match = m.end();
}
splitted.add(text.substring(last_match));
return splitted.toArray(new String[splitted.size()]);
}
}
There are many addLinks() methods on Linkify, one of which may let you accomplish your aims, if your goal is to start an activity from those links.
You can also examine the source code to Linkify to see how you might create your own that meets your needs.

Categories

Resources