Creating new Textviews in another activity based onClick android - android

I would like to create a new textview to hold the information sent each time the button is clicked. I have the data I want passing to another screen in a textview but each time i try to put new data it overrides this data because it uses the same textView (textview4). I would like to know if there is a way of creating a new text view to hold my data each time the button is clicked. I hope I was clear enough, thanks.
This code is from a class called CreateWorkout.Java
public void createNewWorkout (View view){
TextView Exercise1TextView = (TextView) findViewById(R.id.Exercise1TextView);
EditText weightEntered = (EditText)findViewById(R.id.WeightLiftedEditText);
EditText reps = (EditText)findViewById(R.id.RepsEditText1);
EditText sets = (EditText)findViewById(R.id.setsEditText1);
Intent getWorkoutIntent = new Intent(this, SelectWorkout.class);
getWorkoutIntent.putExtra("Workout", Exercise1TextView.getText().toString()
+ " " + weightEntered.getText().toString() + "kg"
+ " " + reps.getText().toString() + " reps"
+ " " + sets.getText().toString() + " sets");
startActivity(getWorkoutIntent);
}
This is where the intent is called. This is from SelectWorkout.Java
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.select_workout);
TextView textView4 = (TextView) findViewById(R.id.textView4);
textView4.setText(getIntent().getExtras().getString("Workout"));
}
i want to take the data entered here to the next screen. So the exercise name(Leg Press), weight(50), set(3), reps(10)

creating a new text view to hold my data each time
Not an exact answer, but this should guide you in the right direction. You could do something like the following:
Get your bundle
Iterate bundle
Create Textviews during iteration and add them to "your_main_layout" which is the id of the main layout inside select_workout
The bundle is the extra data you're sending over from the Intent. The Iterate is going through each item you sent over to this new intent, the create part refers to creating a TextView for each item you sent over. I've supplied links to what I found below.
Listing all extras of an Intent
//Get a bundle:
for (String key : bundle.keySet()) {
// This is each value (text) you sent over from the last intent
Object value = bundle.get(key);
//output data to log, so you can see what prints out
Log.d(TAG, String.format("%s %s (%s)", key, value.toString(), value.getClass().getName()));
//adding a textview to a layout called your_main_layout (which can be a linear layout or something)
//with value.toString() as the text
your_main_layout.addView(createATextView(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT, RelativeLayout.ALIGN_PARENT_RIGHT,
value.toString(), 20, 10, 20));
}
How can I add a TextView to a LinearLayout dynamically in Android?
//method to create view:
public TextView createATextView(int layout_widh, int layout_height, int align,
String text, int fontSize, int margin, int padding) {
TextView textView_item_name = new TextView(this);
// LayoutParams layoutParams = new LayoutParams(
// LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
// layoutParams.gravity = Gravity.LEFT;
RelativeLayout.LayoutParams _params = new RelativeLayout.LayoutParams(
layout_widh, layout_height);
_params.setMargins(margin, margin, margin, margin);
_params.addRule(align);
textView_item_name.setLayoutParams(_params);
textView_item_name.setText(text);
textView_item_name.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSize);
textView_item_name.setTextColor(Color.parseColor("#000000"));
// textView1.setBackgroundColor(0xff66ff66); // hex color 0xAARRGGBB
textView_item_name.setPadding(padding, padding, padding, padding);
return textView_item_name;
}

Related

Linearlayout weights not giving what I write

So I want to have a headline that is ALWAYS a third of the screen and then the rest of the 2 thirds of the screen with names. Seems easy but the result is that the headline becomes less than a third if there is many names. It is only 2 lines that does this I wrtite //1 //2 to easily find them but give the whole code since it may affect the result.
Here is a photo.
The top text does not show the whole message and Is not 1 third of the screen as intended
Thanks in advance!
private void showScores() {
float baseTextSize = 100/playerNum;
LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT,
10000.0f //1
);
TextView t = new TextView(this);
String result_msg = getString(R.string.result_msg);
t.setLayoutParams(param);
t.setText(result_msg + "\n");
t.setTextColor(getColor(R.color.white));
if (playerNum>3) {
t.setTextSize(30f);
} else {
t.setTextSize(40f);
}
scoreShower.addView(t);
param.weight = 20000.0f/playerNum; //2
for (int i=0;i<playerNum;i++) {
TextView txt = new TextView(this);
txt.setLayoutParams(param);
if (i == 0) {
txt.setTextSize(baseTextSize + 8f);
txt.setTextColor(getColor(R.color.gold));
} else {
txt.setTextSize(baseTextSize);
txt.setTextColor(getColor(R.color.white));
}
String txtString = (i+1) + ". " + arrayList.get(i).getKey() + " : " + arrayList.get(i).getValue();
txt.setText(txtString);
if (playerNum>6) {
txt.setTextSize(10f);
}
scoreShower.addView(txt);
}
Try using weighted LinearLayout
<LinearLayout
....
...weightSum="3"
...orientation="vertical">
Set the weight of the top view to 2 using
<...
...layout_weight="1">
And the one below set the weight to 2

How to find which dynamic button is clicked in android

i have created dynamic button in activity on button click. When i created more than on button in activity,onclick works for the most recent button as i assigned id to every button. how can i identify which dynamic button is pressed other than most recent button.
Here is the snippet of my code
public void dynamicButton()
{
// int x=0;
preferences = PreferenceManager.getDefaultSharedPreferences(TimeStudy.this);
value = preferences.getInt("value", 0);
//myButton = new Button(this);
// if (value > x)
if ( i <= value) {
myButton= new Button(this);
myButton.setId(value);
BtnId.add(value);
myButton.setTag(value);
LinearLayout ll = (LinearLayout) findViewById(R.id.dynamiclayout);
ll.setOrientation(LinearLayout.VERTICAL);
ll.setPadding(10, 300, 10, 10);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
myButton.setLayoutParams(lp);
btnid= myButton.getId();
myButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
switch (btnid) {
case 1:case 2:case 3:case
Intent intent = new Intent(TimeStudy.this, CollectSample.class);
startActivity(intent);
break;
}
}
});
ll.addView(myButton, lp);
i++;
}
switch (btnid) {
case 1:case 2:case 3:
SharedPreferences average = getSharedPreferences("avg", 0);
String avgbtn = average.getString("btnavg", "");
settings = getSharedPreferences("dynamicbtname", 0);
btnname = settings.getString("btnname", "");
ar.add(btnname);
String styledText = "<font color='#008000'>" + btnname + "</font>" + "&nbsp" + "&nbsp" + "&nbsp"
+ "<small>"
+ avgbtn + "</font>"
+ "<small>";
myButton.setText(Html.fromHtml(styledText));
myButton.setGravity(Gravity.CENTER | Gravity.LEFT);
break;
}
i want result like this even if after creation of all three button and 1 button is clicked no shows on first button.
enter image description here
i get this if i pressed 1 button after creation of 2 or third button data returns to most recent button.
enter image description here
any help appriciated thanks in advance.
THere's two ways.
1)Check by comparing it to the view variable passed in
2)Use an OnClickListener implementation that knows which one it is (by using different classes, or using one class with a parameter in it).

How to add dynamic layout in existing layout ( Android, JSON )

I have an app in which I am showing data from JSON. I am displaying data in a dynamic textview on the right and left side of the relative layout. Now I want to add this layout in an existing layout so that I can apply an OnClickListener on the textview. Right now I am getting data into a string and then setting that string into static textviews in the left and right side of the layout.
How would it be possible to generate textview dynamically on the basis of number of data I am getting from JSON ?
for (Region object : temp.phonelist.regionList)
{
if (object.getCCInfoShortDesc() != null || !(object.getCCInfoShortDesc().equals(null)))
{
Log.i("nullexception", "nullexception");
holder.tvDescription.setText(object.getCCInfoShortDesc());
holder.tvDescription.setVisibility(View.VISIBLE);
}else {
Log.i("nullexception1", "nullexception1");
holder.tvDescription.setVisibility(View.GONE);
}
leftContent += object.getCCInfoLeft() + ":" + "\n";
rightContent += object.getCCInfoRight() + "\n";
}
Log.i("lefftcontent", leftContent);
Log.i("rightcontent", rightContent);
if (leftContent != null) {
holder.tvData2.setText(leftContent);
holder.tvData2.setVisibility(View.VISIBLE);
}
if (rightContent != null) {
holder.tvData1.setText(rightContent);
holder.tvData1.setVisibility(View.VISIBLE);
}
You can do it in this way..
final int Count = < Number of TextViews>; // total number of textviews to add
final TextView[] TextViewsARR = new TextView[N]; // create an empty array;
for (int i = 0; i < Count; i++) {
// create a new textview
final TextView rowTextView = new TextView(this);
// set some properties of rowTextView or something
rowTextView.setText("This is row #" + i);
// add the textview to the linearlayout
myLinearLayout.addView(rowTextView);
// save a reference to the textview for later
TextViewsARR [i] = rowTextView;
}
I have a sample below that generates a checkbox dynamically, If you
observe i am generating the checkbox based on the cursor count.
You can adapt this saple to your needs
Instead of checkbox use a texview
Give any layout like linear, relative etc and generate views
dynamically
private CheckBox chkBoxMealType[] = null;
mCursor = db.rawQuery("SELECT meal_type_id,meal_type_name FROM meal_type_mas", null);
if(mCursor.moveToFirst()){
do{
if(chkBoxMealTypeCnt==0){
chkBoxMealType=new CheckBox[mCursor.getCount()];
}
//create a general view for checkbox
chkBoxMealType[chkBoxMealTypeCnt]= new CheckBox(getActivity());
//Create params for veg-checkbox
//Reason:: we don't need to worry about the data exist in cuisine_type_mas table
chkBoxMealType[chkBoxMealTypeCnt].setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
chkBoxMealType[chkBoxMealTypeCnt].setTextColor(getResources().getColor(R.color.searchGoldLight));
chkBoxMealType[chkBoxMealTypeCnt].setTextSize(TypedValue.COMPLEX_UNIT_SP,12);
chkBoxMealType[chkBoxMealTypeCnt].setTag(mCursor.getString(mCursor.getColumnIndexOrThrow(meal_type_mas.COLUMN_MEAL_TYPE_ID)));
chkBoxMealType[chkBoxMealTypeCnt].setText(WordUtils.capitalizeFully(mCursor.getString(mCursor.getColumnIndexOrThrow(meal_type_mas.COLUMN_MEAL_TYPE_NAME))));
mealTypeContainer.addView(chkBoxMealType[chkBoxMealTypeCnt]);
//since cursor count starts from 0 last count must be allowed
chkBoxMealTypeCnt++;
}while(mCursor.moveToNext());
Log.d("", "");
}
I have another sample..... Download this project(Click Here) and run in your editor
Snapshot::
Firstly you need to add a View in your layout ... Like you may try using LinearLayout or HorizontalLayout ... and then attach/add your dynamic textview to that layout.
Pragmatically you may try like this
packageButtons = new ArrayList<TextView>(); // Create your textview arraylist like this
for(int a = 0; a < your_text_view_from_json.size(); a++){
final TextView rowTextView;
rowTextView = new TextView(getApplicationContext());
rowTextView.setText(taxi_type_spin.get(a).taxi_type);
rowTextView.setTextSize(15);
rowTextView.setTextColor(getResources().getColor(R.color.white));
LinearLayout.LayoutParams lparam = new LinearLayout.LayoutParams(0,
LinearLayout.LayoutParams.WRAP_CONTENT, 1);
//rowTextView.setPadding(0, 0, 0, 0);
packageButtons.add(rowTextView);
rowTextView.setLayoutParams(lparam);
rowTextView.setId(a);
final int b = a;
// get value of clicked item over here ..
rowTextView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Button btn = (Button)v;
String get_value = btn.getText().toString();
//Toast.makeText(getApplicationContext(), "Button name is : " + get_value + " AND ID IS : " + rowTextView.getId(), Toast.LENGTH_LONG).show();
if(taxi_type_spin.get(b).taxi_type.equalsIgnoreCase(Utils.Hourly_Package))
{
setTaxiType(rowTextView.getId(),true);
ll_spin.setVisibility(View.VISIBLE);
}
else
{
setTaxiType(rowTextView.getId(),false);
ll_spin.setVisibility(View.GONE);
}
setSelectedButtonColor(b);
}
});
// add the textview to the linearlayout
myLinearLayout.addView(rowTextView);
NOTE rowTextView .. this is your default view attached to your XML file
Hope it helps!
private void setLayout(LinearLayout llayout,
final ArrayList<String> items) {
for (int i = 0; i < items.size(); i++) {
LinearLayout row = null;
LayoutInflater li = getLayoutInflater();
row = (LinearLayout) li.inflate(R.layout.custom_item,
null);
ImageView image = (ImageView) row.findViewById(R.id.image);
llayout.addView(row);
}
}
I would suggest you to use ArrayList, because the class java.util.ArrayList provides resizable-array, which means that items can be added and removed from the list dynamically.
and get value from ArrayList something like this:
for(int i=0; i<arrayList.size(); i++)
{
textName.setText(object.getName());
}
How it is possible to genrate textview dynamically
on the basis of number of data i am getting from json.
You need to create TextView and add it to the parent layout each time you iterate on the forloop. So you will have textView for each of the element of the temp.phonelist.regionList
sample:
for (Region object : temp.phonelist.regionList)
{
TextView tx = new TextView(context); //creating a new instance if textview
//yourstuff goes here
tx.setText(text_you_want);
yourView.addView(tx); //this is to add the textView on each iteration
}
here is your solution do this way,Take one Layout(Linear or Relative) and add control dynamically....
LayoutParams lp = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
for (int i = 0; i < 4; i++)
{
TextView txtDemo = new TextView(getActivity());
txtDemo .setTextSize(16);
txtDemo .setLayoutParams(lp);
txtDemo .setId(i);
lp.setMargins(0, 10, 0, 0);
txtDemo .setPadding(20, 10, 10, 10);
txtDemo .setText("Text View"+ i);
linearlayout.addView(txtDemo );
}
}

Building xml relative layout programmatically

I'm trying to update/populate xml on run-time. The textViews are displayed fine but it seems like it fails position them correctly after the first item (see the else statement). Is it because getId() is not recognised or am I totally wrong?
for(int x=1; x<13; x++){
String prompt="PROMPT_"+String.valueOf(x);
String promptValue = myTacorCursor.getString(myTacorCursor.getColumnIndex(prompt));
//if not empty draw a row
if (!promptValue.equals("")){
//insert new rows into layout
RelativeLayout myLayout = (RelativeLayout) findViewById(R.id.RelativeLayout1);
TextView promptLabel = new TextView(this);
promptLabel.setTextAppearance(this, android.R.style.TextAppearance_DeviceDefault_Large);
promptLabel.setText(myTacorCursor.getString(myTacorCursor.getColumnIndex("PROMPT_"+String.valueOf(x))));
promptLabel.setId(1);
((RelativeLayout) myLayout).addView(promptLabel);
RelativeLayout.LayoutParams mLayoutParams1=(RelativeLayout.LayoutParams)promptLabel.getLayoutParams();
mLayoutParams1.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
if (i==1){
mLayoutParams1.addRule(RelativeLayout.BELOW,R.id.textView7);
Log.w("ID is:", String.valueOf(promptLabel.getId()));
} else{
mLayoutParams1.addRule(RelativeLayout.BELOW,promptLabel.getId());
Log.w("ID is:", String.valueOf(promptLabel.getId()));
}
i++;
}
}
I'm trying to display:
(textView)LABEL xx R.id.textview7
<-- here would be the inserted columns -->
(text view) prompt 1
(text view) prompt 2
(text view) prompt 3
... etc ...'
Setting ids dynamically is OK. Just some more attentiveness and your code works.
As far as you're in the for loop, it's better to increment index only in one place.
After you've changed the LayoutParams of the View you need to set it back: promptLabel.setLayoutParams(layoutParams)
Try this. It should work:
public class MainActivity extends Activity {
private static final int BASE_ID = 1;
private static final int ITEMS_COUNT = 13;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RelativeLayout rootLayout = (RelativeLayout) findViewById(R.id.root);
for (int index = BASE_ID; index < ITEMS_COUNT; index++) {
String prompt = "PROMPT_" + String.valueOf(index);
// if not empty draw a row
// insert new rows into layout
TextView promptLabel = new TextView(this);
promptLabel.setTextAppearance(this,
android.R.style.TextAppearance_DeviceDefault_Large);
promptLabel.setText(prompt);
promptLabel.setId(index);
rootLayout.addView(promptLabel);
RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) promptLabel
.getLayoutParams();
layoutParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
if (index == BASE_ID) {
layoutParams.addRule(RelativeLayout.BELOW, R.id.top);
Log.d("ID is:", String.valueOf(index));
} else {
layoutParams.addRule(RelativeLayout.BELOW, index - 1);
Log.d("ID is:", String.valueOf(index - 1));
}
promptLabel.setLayoutParams(layoutParams);
}
}
}
You don't need to construct the whole layout programatically. Define it in separate layout xml file and then use layout inflater to inflate it. After that add it where you want it.
I have never seen ids assigned programatically, but with my suggestion you can define them in the xml as usual.
PS: Here is a good example explaining how to use LayoutInflater.

Change image to a button created programmatically

I have created a interface with buttons, but i don't know how many buttons I need to create, so I have created them in java, with this code:
public void criaButton (String nome){
TableLayout tl=(TableLayout)findViewById(R.id.tabBTALERT);
TableRow tr1 = new TableRow(this);
tr1.setPadding(17, 15, 15, 5);
final Button bt = new Button(this);
bt.setText(nome);
bt.setTextColor(Color.BLACK);
bt.setBackgroundResource(R.drawable.botao);
bt.setCompoundDrawablesWithIntrinsicBounds(R.drawable.envelope, 0, 0, 0);
bt.setPadding(10, 20, 20, 20);
bt.setId(id);
tr1.addView(bt);
tl.addView(tr1);
bt.setOnClickListener( new View.OnClickListener() {
public void onClick(View arg0) {
idButton = bt.getId();
nomeButton = (String) bt.getText();
inicia ();
Toast.makeText(Alerta.this, "Nome e ID : " + nomeButton + " " + idButton, Toast.LENGTH_SHORT).show();
}
});
}
with this method I can save the id and the name of every button I create. The problem is, these buttons have an image, and when I start another activity I have to change the image, if the message was read, not read, approved or rejected.
The question is, how can I give the id of the button to change the image and start again the activity with the changed image?? Is this possible?
Save the button ids in an array and then find the buttons by their ids and change their image to the desired one.

Categories

Resources