Generate any number of Views - java

I want to generate multiple TextViews based on how many semicolons the users enters between inputs in an EditText.
And it works so far, the only problem is that all TextViews are on top of each other, so I need to have the second TextView be positioned below the first and so on.
I tried to use setY but it did not change the position of the Views or they disappeared completely.
Is there a method to achieve this or is this a case for the LayoutInflater?
public class MainActivity extends AppCompatActivity {
private EditText et1;
private ScrollView sv1;
private ConstraintLayout cl1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et1 = findViewById(R.id.editText);
sv1 = findViewById(R.id.scrollView);
cl1 = new ConstraintLayout(this);
sv1.addView(cl1);
}
public void splitToChips(View v) {
String content = et1.getText().toString();
String[] products = content.split(";");
TextView[] textViews = new TextView[products.length];
for(int i = 0; i<products.length; i++) {
textViews[i] = new TextView(this);
cl1.addView(textViews[i]);
textViews[i].setText(products[i]);
}
}
}

You should add views to LinearLayout. In my case, I created a layout with a Button, EditText, and LinearLayout along with a vertical orientation inside of a ScrollView. Then, in the Java code, I simply added the following line to the loop:
mLinearLayout.addView(textViews[i]);

Related

How do I create a new TextView and display it? (with programming)

I'm still new to Android Studio, and for practice I want to make a simple To-Do list app. I'm troubles with creating a new TextView and displaying it.
I know that I probably need to manually insert the TextView into the layout, but I have no idea how to do that.
Here's my MainActivity code:
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
Button submitBtn;
EditText userInput;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
submitBtn = (Button)findViewById(R.id.submitBtn);
userInput = (EditText)findViewById(R.id.userInput);
submitBtn.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if(v.getId() == R.id.submitBtn) {
String userInputString = userInput.getText().toString();
TextView listItem = new TextView(this);
listItem.setText(userInputString);
}
}
}
I am using ConstraintLayout for my layouting. If somebody could help guide me to the right direction, that would be greatly appreciated, thanks in advance!
In the simplest case, you get your ConstraintLayout using its ID and then call addView(View) with your TextView as the parameter on it.
Assuming your ConstraintLayout has the id myLayout:
ConstraintLayout layout = (ConstraintLayout)findViewById(R.id.myLayout);
layout.addView(listItem);

My Android App crashes after adding an OnclickListener

I tried to build an easy Android App using Java and, obviously, Android studio. After adding an OnClickListener the app keeps crashing on the emulator.
public class MainActivity extends AppCompatActivity {
EditText first = findViewById(R.id.firstInput);
EditText second = findViewById(R.id.secondInput);
EditText result = findViewById(R.id.result);
private Button add;
private View.OnClickListener onClickListener = new View.OnClickListener() {
#Override
public void onClick(View view) {
clicked();
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
add = new Button(this);
add.setOnClickListener(onClickListener);
};
void clicked(){
int i = Integer.parseInt(first.getText().toString());
int z = Integer.parseInt(second.getText().toString());
int r = i + z;
result.setText(r);
}
};
Wrong location of object declaration
It should be below the setContentView
EditText first = findViewById(R.id.firstInput);
EditText second = findViewById(R.id.secondInput);
EditText result = findViewById(R.id.result);
Button haven't added to the layout
add = new Button(this);
addContentView(add, new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));
Note: This is impractical, you should have added this on your layout xml unless you wanted to create dynamic layout
Warning issue of setting a text by integer
From:
result.setText(r);
To:
result.setText(String.valueOf(r));

How to get Button Value from another class on android studio

I have 2 class, which the first class i created Loop button
and second class i want to get button value from first class..
Here is my code
public class FirstClass extends AppCompatActivity {
public static Button[] btn = new Button[8];
#Override
protected void onCreate(Bundle savedInstanceState) {
RelativeLayout relativeLayout = (RelativeLayout) findViewById(R.id.rlid);
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,RelativeLayout.LayoutParams.WRAP_CONTENT);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
for(int i=0; i<btn.length; i++)
{
btn[i] = new Button(this);
btn[i].setTextColor(Color.BLUE);
btn[i].setText((i + 0) + " ");
btn[i].setLayoutParams(lp);
relativeLayout.addView(btn[l]);
}
}
}
public class SecondClass extends Activity {
Button btn2= (Button) findViewById(R.id.btn2);
btn2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Button bb = FirstClass.btn[2]; //get button no 2 from 1st class
bb.setTextColor(Color.YELLOW); // try to change into yellow but nothing happen
}
});
Although bad practice of using views as static fields, your code should work.
Another problem is that you have created buttons in the first activity and done nothing with them. You should probably add them to some layout of the activity.
The good practice would be not to store buttons or any views in static fields, and get results using Intents. https://developer.android.com/training/basics/intents/result.html

Why I can't seem to update my gridview from oncreate?

I have the following OnCreateMethod()
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_siege_main);
mContext = getApplicationContext();
gridview = (GridView) findViewById(R.id.gridview_board);
initialBoard = new Board();
initialBoard.generate(Globals.rand_width,
Globals.rand_height,
Globals.rand_low,
Globals.rand_high);
gridview.setAdapter(new BoardAdapter(this));
gridview.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
//updateGameState(initialBoard);
}
});
updateGameState(initialBoard);
//typography
TextView boardName = (TextView) findViewById(R.id.textview_board_name);
boardName.setText("Uncharted Territory");
Toast.makeText(SiegeMainActivity.this, "Uncharted Territory loaded", Toast.LENGTH_SHORT).show();
Typeface face = Typeface.createFromAsset(getAssets(),
"fonts/calibri-1.ttf");
boardName.setTypeface(face);
TextView pl1Name = (TextView) findViewById(R.id.textViewPlayer1Name);
face = Typeface.createFromAsset(getAssets(),
"fonts/calibri-1.ttf");
pl1Name.setTypeface(face);
TextView pl2Name = (TextView) findViewById(R.id.textViewPlayer2Name);
face = Typeface.createFromAsset(getAssets(),
"fonts/calibri-1.ttf");
pl2Name.setTypeface(face);
}
and my updateGameState() method is like this:
private void updateGameState(Board b) {
int [] vals = b.getLinearVals();
int [] plays = b.getLinearPlays();
int [] score = b.getScore();
int turns = b.getTurns();
Button tile;
//updating board
for(int i=0;i<gridview.getChildCount();i++){
tile = (Button)gridview.getChildAt(i);
tile.setText(""+vals[i]);
if(plays[i]==1)
tile.setBackgroundDrawable(mContext.getResources().getDrawable(R.drawable.btn_default_normal_green));
else if (plays[i]==2)
tile.setBackgroundDrawable(mContext.getResources().getDrawable(R.drawable.btn_default_normal_blue));
}
//Setting the score
Button pl1Score, pl2Score;
pl1Score = (Button) findViewById(R.id.buttonPlayer1Score);
pl2Score = (Button) findViewById(R.id.buttonPlayer2Score);
pl1Score.setText(""+score[0]);
pl2Score.setText(""+score[1]);
}
When I call updateGameState() in OnCreate after creating the adapter, it should fill the buttons with some values. But it doesn't seem to work. But when I do the same thing on a click (commented out in the click listener), it seems to work fine. I want to populate the values on loading the page. Can somebody help me?
You need to let the GridView know that the data has changed. If you are dynamically changing the data in the ArrayAdapter, you need to call BoardAdapter.notifyDataSetChanged() so the GridView can "refresh" itself with the new data.
In your case, you need to create a reference to you new BoardAdapter and then use that to call the notifyDataSetChange() method.
private BoardAdapter boardAdapter = null;
protected void onCreate(Bundle savedInstanceState) {
// your things
boardAdapter = new BoardAdapter(this);
gridview.setAdapter(boardAdapter);
// more things
}
private void updateGameState(Board b) {
// update your data
boardAdapter.notifyDataSetChanged();
}
Edit: You mentioned in the comment that you tried using an ArrayAdapter and it didn't work for you... maybe try this, which says to use the GridViews invalidateViews() method. gridView.invalidateViews()
Have a look at this SO question & answer here:
How to refresh a GridView?
I had a similar problem, but couldn't get it to even refresh on a button click, even tho items were being changed and added. In my case, the trick, as it turns out, was to recreate the (in your case) BoardAdapter with the new/updated list of items, and then reassign it to the gridview.
gridViewAdapter = new MyGridViewAdapter(this, blah, yourUpdatedItems);
discoverGridView.InvalidateViews();
discoverGridView.Adapter = gridViewAdapter;
I am sure there has to be a better, more reactive, way of doing it, but this at least got my proof of concept up and running.

Android: Create EditText on Runtime

I'm trying to create a view where the user can click a "plus" button, and have additional EditTexts be created. The goal is to have a base of 2 EditTexts, and each time the user clicks the button, add another 2 EditTexts.
How can I do this? I can add EditTexts from Java, but I can't figure out how to add and handle a list of them dynamically.
I was hoping to take however many pairs of EditTexts, and push it into a key/value HashMap or something.
Any ideas of how to do this? Thanks!
public class MyActivity extends Activity {
private LinearLayout main;
private int id = 0;
private List<EditText> editTexts = new ArrayList<EditText>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
main = new LinearLayout(this);
main.setOrientation(LinearLayout.VERTICAL);
Button addButton = new Button(this);
addButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
addEditText();
}
});
Button submit = new Button(this);
submit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
for (EditText editText : editTexts) {
editText.getText().toString();
// whatever u want to do with the strings
}
}
});
main.addView(addButton);
main.addView(submit);
setContentView(main);
}
private void addEditText() {
LinearLayout editTextLayout = new LinearLayout(this);
editTextLayout.setOrientation(LinearLayout.VERTICAL);
main.addView(editTextLayout);
EditText editText1 = new EditText(this);
editText1.setId(id++);
editTextLayout.addView(editText1);
editTexts.add(editText1);
EditText editText2 = new EditText(this);
editText2.setId(id++);
editTextLayout.addView(editText2);
editTexts.add(editText2);
}
Do it in a ListView.
Then you can just add them to a ListAdapter.
And then use adapter.notifyDatasetChanged()
May be I am not clear but Instead of adding Individual edit text you can add as Group View like Linear layout here you can use any flag values to add dynamic name conversions also.
That view you can update into List View like inflating rows in the List View....

Categories