How to refresh layout that is created programmatically? - android

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.

Related

Text out of text view

I am currently having a problem with Android application. I am using a table layout with some views in it. The problem is that it seems like the TextView does not wraps the text correctly. However, when I change swipe between fragments it just resizes and it fits as how its supposed to.
This is what is looks like in the first place when the onCreate function is called.
And this is how it looks when I swipe between fragments.
This is the method I used to set up the views inside the table.
private void initializeBookTable(final List<Book> bookList, View view, final Button modifyBtn, final Button deleteBtn)
{
//Get screen width
DisplayMetrics displaymetrics = new DisplayMetrics();
((Activity)getContext()).getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
int screenWidth = displaymetrics.widthPixels;
TableLayout table = view.findViewById(R.id.book_tableLayout);
//Border for the text views
final GradientDrawable gd = new GradientDrawable();
gd.setColor(getResources().getColor(R.color.colorTeal));
gd.setCornerRadius(2);
gd.setStroke(2, 0xFF000000);
//Font for the text views
Typeface font = Typeface.create("casual",Typeface.BOLD);
//Header row
TableRow headerRow = new TableRow(this.getContext());
TableLayout.LayoutParams headerRowParams = new TableLayout.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT,TableRow.LayoutParams.WRAP_CONTENT);
headerRowParams.setMargins(0,1,0,0);
headerRow.setLayoutParams(headerRowParams);
//Header name text view
TextView headerName = new TextView(this.getContext());
headerName.setText(getResources().getString(R.string.book_NAME));
headerName.setBackground(gd);
headerName.setPadding(20,0,20,0);
headerName.setTypeface(font);
headerName.setTextColor(Color.BLACK);
headerName.setMinWidth(screenWidth/4);
headerRow.addView(headerName);
//Header chapter text view
TextView headerChapter = new TextView(this.getContext());
headerChapter.setText(getResources().getString(R.string.book_CHAPTER));
headerChapter.setBackground(gd);
headerChapter.setPadding(20,0,20,0);
headerChapter.setTypeface(font);
headerChapter.setTextColor(Color.BLACK);
headerChapter.setMinWidth(screenWidth/4);
headerRow.addView(headerChapter);
//Header page text view
TextView headerPage = new TextView(this.getContext());
headerPage.setText(getResources().getString(R.string.book_PAGE));
headerPage.setBackground(gd);
headerPage.setPadding(20,0,20,0);
headerPage.setTypeface(font);
headerPage.setTextColor(Color.BLACK);
headerPage.setMinWidth(screenWidth/4);
headerRow.addView(headerPage);
//Header name text view
TextView headerStatus = new TextView(this.getContext());
headerStatus.setText(getResources().getString(R.string.book_STATUS));
headerStatus.setBackground(gd);
headerStatus.setPadding(20,0,20,0);
headerStatus.setTypeface(font);
headerStatus.setTextColor(Color.BLACK);
headerStatus.setMinWidth(screenWidth/4);
headerRow.addView(headerStatus);
//Add row to table
table.addView(headerRow);
for(int i = 0; i < bookList.size(); i++)
{
TableRow row = new TableRow(this.getContext());
//Set text views parameters
TableRow.LayoutParams textViewParams = new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT, TableRow.LayoutParams.WRAP_CONTENT);
textViewParams.setMargins(0,1,0,1);
row.setLayoutParams(textViewParams);
//Set text views parameters
TextView name = new TextView(this.getContext());
name.setText(bookList.get(i).getName());
name.setBackground(gd);
name.setPadding(20,0,20,0);
name.setLayoutParams(textViewParams);
TextView chapter = new TextView(this.getContext());
chapter.setText(bookList.get(i).getChapter());
chapter.setBackground(gd);
chapter.setPadding(20,0,20,0);
chapter.setLayoutParams(textViewParams);
TextView page = new TextView(this.getContext());
page.setText(bookList.get(i).getPage());
page.setBackground(gd);
page.setPadding(20,0,20,0);
page.setLayoutParams(textViewParams);
TextView status = new TextView(this.getContext());
status.setText(bookList.get(i).getStatus());
status.setBackground(gd);
status.setPadding(20,0,20,0);
status.setLayoutParams(textViewParams);
//Add text views to the row
row.addView(name);
row.addView(chapter);
row.addView(page);
row.addView(status);
row.setClickable(true);
//Click listener for each row
row.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
TableRow tableRow = (TableRow) view;
selectedRow = tableRow;
//If the row is already selected (in red) deselect it
TextView textViewCheck = (TextView) tableRow.getChildAt(0);
if(selection && textViewCheck.getText().toString().equals(selectedBook.getName()))
{
for(int i = 0; i < 4; i++)
{
TextView textView = (TextView) tableRow.getChildAt(i);
textView.setBackground(gd);
}
//Disable add and modify buttons when row is deselected
modifyBtn.setEnabled(false);
deleteBtn.setEnabled(false);
selection = false;
selectedBook = null;
}
//If the row is not in red check if there is already a selected row
else
{
if(selection)
{
String message = "Please select only one";
Toast.makeText(getContext(), message, LENGTH_SHORT).show();
}
else
{
for(int i = 0; i < 4; i++)
{
TextView textView = (TextView) tableRow.getChildAt(i);
textView.setBackgroundColor(Color.RED);
}
//Enable add and modify buttons when row is selected
modifyBtn.setEnabled(true);
deleteBtn.setEnabled(true);
TextView nameView = (TextView) tableRow.getChildAt(0);
selectedBook = storage.findBook(nameView.getText().toString());
selection = true;
}
}
}
});
//Set row parameters
TableRow.LayoutParams tableRowParams = new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT,TableRow.LayoutParams.WRAP_CONTENT);
tableRowParams.setMargins(0,1,0,1);
row.setLayoutParams(tableRowParams);
table.addView(row);
}
}
This is my onCreate
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.books_fragment,container,false);
storage = InternalStorage.getInstance(this.getContext());
final Button modifyBtn = view.findViewById(R.id.modifyBtn);
final Button deleteBtn = view.findViewById(R.id.deleteBtn);
//Disable modify and delete buttons
modifyBtn.setEnabled(false);
deleteBtn.setEnabled(false);
this.initializeBookTable(storage.getBookList(),view, modifyBtn, deleteBtn);
Button addBtn = view.findViewById(R.id.addBtn);
addBtn.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view) {
Intent intent = new Intent(getActivity(), AddModifyBook.class);
startActivity(intent);
}
});
modifyBtn.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
Intent intent = new Intent(getActivity(), AddModifyBook.class);
//Passing the selected book to the AddModifyBook activity
intent.putExtra("selectedBook",selectedBook);
startActivity(intent);
selectedBook = null;
selection = false;
}
});
final TableLayout table = view.findViewById(R.id.book_tableLayout);
deleteBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
storage.removeBook(selectedBook);
selectedBook = null;
selection = false;
modifyBtn.setEnabled(false);
deleteBtn.setEnabled(false);
table.removeView(selectedRow);
}
});
return view;
}
And for onResume I have the default.
Another thing that is happening is that if I just set the background of the name (the first column) with the gradient drawable gd then it works but If I set the rest background of the rest of the columns then I have the problem that I have already explained.
So apparently I have managed to solve the issue by using a gradient drawable for the name and a different gradient drawable for the other properties.

Cannot add View To the relative Layout

i am making a activity that takes int position from another activity to get a class formula that have the formula, some variables and the title , so i want to create the activity by taking that formula and setting the title , making some edit text views for variables so that the user add values for them and then i return the result by a dialogue the problem is that the views that i add programitically are not displayed, plz help
public class DisplayFomula extends AppCompatActivity {
#TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_fomula);
DB db = new DB(this);
Bundle extra = getIntent().getExtras();
int pos = extra.getInt("id");
final Formula form = db.getFormula(pos);
RelativeLayout layout=new RelativeLayout(this);
TextView tw1 =(TextView) findViewById(R.id.textView11);
tw1.setText(form.title);
final String[] var = form.var;
int i=0;
final EditText[] ed = new EditText[50];
for(;i<var.length;i++){
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
ed[i]= new EditText(this);
ed[i].setId(i);
ed[i].setHint(var[i]);
ed[i].setTextAlignment(View.TEXT_ALIGNMENT_CENTER);
ed[i].setLayoutParams(params);
if(i!=0) params.addRule(RelativeLayout.BELOW,ed[i-1].getId());
else params.addRule(RelativeLayout.BELOW,R.id.textView11);
layout.addView(ed[i],params);}
Button btn = new Button(this);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
btn.setId(i);
params.addRule(RelativeLayout.CENTER_IN_PARENT);
btn.setLayoutParams(params);
btn.setText("Go!");
layout.addView(btn,params);
params = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT);
addContentView(layout,params);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
double[] varin=new double[var.length];
for(int i =0;i<var.length;i++){
Double dbl = Double.parseDouble(ed[i].getText().toString());
varin[i]=dbl;
}
String res = String.valueOf(form.result(varin));
}
});
}
}
You are adding all the views to RelativeLayout layout. But i think u have'nt add layout view to any activity_display_fomula view.
get a viewgroup from activity_display_fomula and add your RelativeLayout layout to it..

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
}
}

How to add set text programmatically one below another?

I have set notification listener in my code. Whenever I receive a notification I want to put a Text view in my linear layout activity which has nothing initially.
When second notification arrives I want to add one more text view below the previous text view.
public class InformationActivity extends Activity
{
public static VideoInformationClass vidInfo = new VideoInformationClass() ;
public static LinearLayout lv ;
public static LayoutParams textViewParams;
public static TextView tv ;
public static TextView tv1,tv2,tv3,tv4,tv5,tv6,tv7,tv8,tv9,tv10;
static int fieldFrequency;
static int numberOfFrameLines;
static int numberOfVisibleLines;
static int numberOfVisiblePixels;
static int interlace;
static int imageFormat;
static int videoCoding;
static int scanType;
VideoPropertiesParams GetParams;
VideoPropertiesParams VP;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.information_activity);
Context context = getBaseContext();
LinearLayout lv = new LinearLayout(this);
lv.setOrientation(LinearLayout.VERTICAL);
LinearLayout.LayoutParams textViewParams = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
// tv = new TextView(this);
}
#Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
onFieldFrequencyChanged();
onImageFormatChanged();
onInterlacedChanged();
/*vidInfo.RegisterVidPropertyListener();
vidInfo.RegisterSignalAndPresenceListener();
vidInfo.RegisterThreeDChangeListener();*/
if (ControlUnit.flag) {
GetParams = vidInfo.GetVideoProperty();
Log.i("TvPlayerFunctionalTestApp","Get Video Property called");
fieldFrequency = GetParams.fieldFrequency;
numberOfFrameLines = GetParams.numberOfFrameLines;
numberOfVisibleLines = GetParams.numberOfVisibleLines;
numberOfVisiblePixels = GetParams.numberOfVisiblePixels;
interlace = GetParams.interlace;
imageFormat = GetParams.imageFormat;
videoCoding = GetParams.videoCoding;
scanType = GetParams.scanType;
}
/* tv.setText("Something");
tv.setLayoutParams(textViewParams);
lv.addView( tv );*/
}
#Override
protected void onStop() {
// TODO Auto-generated method stub
super.onStop();
/*vidInfo.UnRegisterSignalAndPresenceListener();
vidInfo.UnRegisterThreeDChangeListener();
vidInfo.UnRegisterVidPropertyListener();*/
}
public void onFieldFrequencyChanged(){
String info = "On field frequency changed , value is " + vidInfo.ChangedFrequency;
tv = new TextView(this);
tv.setText(String.valueOf(info));
LinearLayout.LayoutParams textViewParams = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
tv.setLayoutParams(textViewParams);
lv.addView(tv);
}
public void onImageFormatChanged() {
String info = "On Image Format changed , value is " + vidInfo.ChangedFormat;
tv1 = new TextView(this);
tv1.setText(String.valueOf(info));
LinearLayout.LayoutParams textViewParams = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
tv1.setLayoutParams(textViewParams);
lv.addView(tv1 );
}
public void onInterlacedChanged() {
String info = "On Interlaced changed , value is " + vidInfo.InterlaceChange;
tv.setText(String.valueOf(info));
LinearLayout.LayoutParams textView
Params = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
tv.setLayoutParams(textViewParams);
lv.addView(tv);
}
Just declare your Linear layout with vertical orientation
<LinearLayout
android:id="#+id/linear"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
LinearLayout lv = (LinearLayout)findViewById(R.id.linear);
TextView tv = new TextView(this);
tv.setLayoutParams(InformationActivity.textViewParams);
tv.setText(String.valueOf(info));
lv.addView(tv );//not InformationActivity.tv just write tv
It will automatically add next view below the the another
Make sure your LinearLayout has orientation set to vertical. Then just add one more item:
LinearLayout layout = // your layout
TextView textView = // new text view
layout.addView(textView);
Just make a Linear Layout whose oreientation is vertacal and add TextView to it.
You need a object from the main ViewGroup(RelativeLayout, LinearLayout etc.),
TextView text = new TextView(this); RelativeLayout r = (RelativeLayout)findViewById(Id);r.add(text);
this lines of code will add a new textView object to the end of the r viewGroup.

Android adding textview programmatically

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);
}

Categories

Resources