Android adding textview programmatically - android

I am trying to add textview in a layout programmatically the textview is added on layout but it's not visible.
I have created a method setSelectedContactTextView() which is called from onResume() the method adds textview but not make them visible on screen.
Here is my code:
protected void onResume() {
if(Constants.fbContactListArrayList!=null && Constants.fbContactListArrayList.size()!=0){
setSelectedContactTextView(Constants.fbContactListArrayList);
}
super.onResume();
}
//SET SELECTED CONTACTS IN TEXTVIEW FORMS
public void setSelectedContactTextView(final ArrayList<Object> list){
//Constants.progressDialog=ProgressDialog.show(this, "", Constants.MSG_PROGESSDIALOG);
new Thread(new Runnable() {
#Override
public void run() {
while(i<list.size()){
ContactBean contactBean=(ContactBean)list.get(i);
if(contactBean.isSelected()==true){
TextView contactTextView=new TextView(NewEventShowDetails.this);
contactTextView.setText(contactBean.getUserName().toString());
fbContactTextLinearLayout.addView(contactTextView);
}
i++;
}
}
});
}

You may try refering to this code
LinearLayout linearLayout = (LinearLayout)findViewById(R.id.info)
...
linearLayout.addView(valueTV);
also make sure that the layout params you're creating are LinearLayout.LayoutParams...
Or try this code
LinearLayout layout = (LinearLayout) findViewById(R.id.linear);
String[] informations = new String[] { "one", "two", "three" };
TextView informationView;
for (int i = 0; i < informations.length; i++) {
View line = new View(this);
line.setLayoutParams(new LayoutParams(1, LayoutParams.MATCH_PARENT));
line.setBackgroundColor(0xAA345556);
informationView = new TextView(this);
informationView.setText(informations[i]);
layout.addView(informationView, 0);
layout.addView(line, 1);
}

Related

How to refresh layout that is created programmatically?

I've a case like I'm creating custom layout programmatically inside onCreateView(). For example :
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return createLayout(cView);
}
View createLayout(View view) {
LinearLayout linLayout = new LinearLayout(activity);
linLayout.setOrientation(LinearLayout.VERTICAL);
LinearLayout.LayoutParams linLayoutParam = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
linLayout.setLayoutParams(linLayoutParam);
for (int i = 0; i <= 3; i++) {
TextView tv = new TextView(activity);
tv.setId(i);
tv.setText("TextView");
tv.setLayoutParams(lpView);
linLayout.addView(tv);
}
view = linLayout;
return view;
}
#Override
public void onResume() {
super.onResume();
}
Nah, all I want to ask is how to refresh textview that has an ID from onResume() ? Thanks.
You can hold your textview in hashmap with the key of textview's id. then on your resume. you can get that textview by id and refresh it.
private HashMap<Integer,TextView> textViews = new HashMap<>();
in your on create method when you create this textviews you need to put textview in hashmap.
for (int i = 0; i <= 3; i++) {
TextView tv = new TextView(activity);
tv.setId(i);
tv.setText("TextView");
tv.setLayoutParams(lpView);
linLayout.addView(tv);
textViews.put(i,tv);
}
your onResume method should look like below
#Override
protected void onResume() {
super.onResume();
TextView tv = textViews.get(yourId);
tv.setText("Your Text");
}
Make TextView tv as global and update this tv as usual.

Adding onClick to buttons that are created programmatically

A TextView and Button are programmatically created and added to a pre-existing vertical layout making it look like a vertical list of views. These views are only created based off the user entering data into an edittext and that data being saved into an ArrayList.
How can I add an onClick function to my 'trash' buttons that are programmatically created that would allow them to remove the view they are associated with.
public static ArrayList<String> deckNameArray = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LinearLayout mainLayout = (LinearLayout)findViewById(R.id.mainLayout);
for(int i = 0; i < deckNameArray.size(); i++)
{
LinearLayout layout = new LinearLayout(this);
if ((i % 2) == 0) {
layout.setBackgroundColor(Color.CYAN);
} else {
layout.setBackgroundColor(Color.WHITE);
}
layout.setOrientation(LinearLayout.HORIZONTAL);
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
layout.setLayoutParams(layoutParams);
layout.setPadding(10, 5, 10, 5);
layout.setWeightSum(5);
mainLayout.addView(layout);
LinearLayout.LayoutParams textViewParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT, 4f);
TextView deckName = new TextView(this);
deckName.setText(deckNameArray.get(i));
deckName.setTextColor(Color.BLACK);
deckName.setTextSize(18);
deckName.setGravity(Gravity.CENTER_VERTICAL);
deckName.setLayoutParams(textViewParams);
layout.addView(deckName);
LinearLayout.LayoutParams imageButtonParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT, 1f);
ImageButton remove = new ImageButton(this);
remove.setImageResource(R.mipmap.trash);
if ((i % 2) == 0) {
remove.setBackgroundColor(Color.CYAN);
} else {
remove.setBackgroundColor(Color.WHITE);
}
remove.setLayoutParams(imageButtonParams);
layout.addView(remove);
}
remove.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
}
});
See http://developer.android.com/reference/android/widget/Button.html
You can set a click listener on any View, using code similar to the sample below:
View myView;
myView.setOnClickListener(new OnClickListener() {
#Override public void onClick(View v) {
// TODO your logic here
}
}

refresh activity with dynamic content

I have an activity with some dynamic content.
For each item of an array, there is a different content (number of textViews, checkboxes, ..)
The user clicks on a "save" button and then the screen has to refresh itself to display the content of the next item.
I was wondering if it was a good practice to reload my activity like this :
Intent refresh = new Intent(this, conflictActivity.class);
startActivity(refresh)
finish()
instead of removing all the views in my layouts, etc ...
I think it's easier to reload it.
Is there another way to do it ?
EDIT : added Code.
public class ConflicFieldTest extends Activity {
private int nbField;
private int nbChecked;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.conflict);
final Button saveButton = (Button) findViewById(R.id.save);
final LinearLayout leftLayout = (LinearLayout) findViewById(R.id.leftLayout);
final LinearLayout rightLayout = (LinearLayout) findViewById(R.id.rightLayout);
final TextView fieldName = new TextView(this);
final LinearLayout editLayoutRight = new LinearLayout(this);
final LinearLayout editLayoutLeft = new LinearLayout(this);
final LinearLayout fieldRight = new LinearLayout(this);
final LinearLayout fieldLeft = new LinearLayout(this);
final ArrayList<String> allIdInConflict = getAllIdInConflict();
for (int i = 0; i < allIdInConflict.size(); i++) {
new AccountSyncTask() {
#Override
public void onPostExecute(
final ArrayList<ArrayList<String>> result) {
nbField = 0;
nbChecked = 0;
final Map<String, Object> fieldsInConflict = conflict
.conflictWithFields(memoAccountMap,
serverAccountMap, modifiedAccountMap);
for (Iterator<Map.Entry<String, Object>> field = fieldsInConflict
.entrySet().iterator(); field.hasNext();) {
final Map.Entry<String, Object> entry = field.next();
fieldName.setText(entry.getKey() + " : ");
final EditText[] editTextArrayRight = new EditText[fieldsInConflict
.size()];
final EditText[] editTextArrayLeft = new EditText[fieldsInConflict
.size()];
final CheckBox[] checkboxRight = new CheckBox[fieldsInConflict
.size()];
final CheckBox[] checkboxLeft = new CheckBox[fieldsInConflict
.size()];
checkboxRight[nbField] = new CheckBox(
ConflicFieldTest.this);
checkboxLeft[nbField] = new CheckBox(
ConflicFieldTest.this);
editLayoutLeft.setGravity(Gravity.CENTER_HORIZONTAL);
editLayoutRight.setGravity(Gravity.CENTER_HORIZONTAL);
fieldRight.setGravity(Gravity.CENTER_HORIZONTAL);
fieldLeft.setGravity(Gravity.CENTER_HORIZONTAL);
editLayoutRight.setOrientation(LinearLayout.HORIZONTAL);
fieldRight.setOrientation(LinearLayout.VERTICAL);
fieldLeft.setOrientation(LinearLayout.VERTICAL);
rightLayout
.addView(
editLayoutRight,
new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.FILL_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT));
leftLayout
.addView(
editLayoutLeft,
new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.FILL_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT));
editTextArrayRight[nbField] = new EditText(
ConflicFieldTest.this);
editTextArrayRight[nbField].setText((String) entry
.getValue());
editTextArrayRight[nbField].setTextColor(Color.BLACK);
editTextArrayRight[nbField].setFocusable(false);
editTextArrayRight[nbField].setClickable(false);
editTextArrayRight[nbField].setWidth(180);
editTextArrayRight[nbField].setPadding(0, 10, 0, 0);
editTextArrayLeft[nbField] = new EditText(
ConflicFieldTest.this);
editTextArrayLeft[nbField]
.setText((String) serverAccountMap.get(entry
.getKey()));
editTextArrayLeft[nbField].setTextColor(Color.BLACK);
editTextArrayLeft[nbField].setFocusable(false);
editTextArrayLeft[nbField].setClickable(false);
editTextArrayLeft[nbField].setWidth(180);
editTextArrayLeft[nbField].setPadding(0, 10, 0, 0);
final int i1 = nbField;
checkboxLeft[i1]
.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
}
});
checkboxRight[i1]
.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
}
});
editLayoutLeft.addView(fieldName);
editLayoutRight
.addView(
editTextArrayRight[nbField],
new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT));
editLayoutLeft
.addView(
editTextArrayLeft[nbField],
new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT));
editLayoutRight.addView(checkboxRight[nbField]);
editLayoutLeft.addView(checkboxLeft[nbField]);
nbField++;
}
saveButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
//save data & update UI
}
}
.execute(appState.getSessionName(), id, "getObjectOnServer");
}
}
Sorry for the code, it is a litle bit dirty (i have deleted some parts), i am reworking it.
int flag = 0;
public void updateUI() {
if(flag == 0) {
//your normal codes...
} else {
//display view with user given data
}
}
Call this function in oncreate. At first flag will be set to zero. When u enter the data in textview and tick checkboxes, update the flag with some value. Then on save Button click call this function again. Now flag is set. So it will display the updated UI.
I think this will give u an idea..

TableRow within TableLayout's content out of screen

This problem is pretty simple, I think.
The thing is: My TextView (Which is in a TableRow which is in a TableLayout) gets out of the visible screen.
A screenshot should clarify:
I tried
tvValue.setLinksClickable(true);
tvValue.setEllipsize(TruncateAt.MIDDLE);
1) No truncation is applied
2) Obviously, they show links, but they are not clickable!
As its a highly dynamic thing i need to do all initialization in code.
So, here's the code:
public class StartUp extends Activity {
private TableLayout mTableLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final Context appContext = getApplicationContext();
mTableLayout = new TableLayout(appContext);
mTableLayout.setBackgroundColor(0xffffffff);
String[] h = new String[] { "email", "facebook", "youtube" };
String[] v = new String[] { "lol#xd.de", "http://www.facebook.com/010101010101010", "http://www.youtube.com/lalala" };
LayoutParams rowLayoutParams = new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
for (int i = 0; i < h.length; ++i) {
TableRow row = new TableRow(appContext);
row.setLayoutParams(rowLayoutParams);
TextView tvHead = new TextView(appContext);
tvHead.setTextColor(0xff336699);
tvHead.setPadding(0, 0, 10, 0);
tvHead.setText(h[i]);
TextView tvValue = new TextView(appContext);
tvValue.setTextColor(0xff191919);
tvValue.setLinksClickable(true);
tvValue.setText(v[i]);
tvValue.setEllipsize(TruncateAt.MIDDLE);
row.addView(tvHead);
row.addView(tvValue);
mTableLayout.addView(row);
}
setContentView(mTableLayout);
}
}
Have you tried setColumnShrinkable()?
http://developer.android.com/reference/android/widget/TableLayout.html#setColumnShrinkable%28int,%20boolean%29

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