I am setting up a textView Keyboard for a vocabulary game. I am looking to clean up my code and was wondering if I could iterate all 26 letters. As of now I declare them all
individually as shown in the code.
I would like to use a for loop and have experimented with no luck.
private void setupKeyBoard() {
A = (TextView) getView().findViewById(R.id.A);
A.setTextSize(20 * getResources().getDisplayMetrics().density);
A.setText("A");
A.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
checkGuess('A');
A.setClickable(false);
A.setAlpha((float) .1);
}
});
B = (TextView) getView().findViewById(R.id.B);
B.setTextSize(20 * getResources().getDisplayMetrics().density);
B.setText("B");
B.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
checkGuess('B');
B.setClickable(false);
B.setAlpha((float) .1);
}
});
C = (TextView) getView().findViewById(R.id.C);
C.setTextSize(20 * getResources().getDisplayMetrics().density);
C.setText("C");
C.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
checkGuess('C');
C.setClickable(false);
C.setAlpha((float) .1);
}
});
} //stop at Z
I would recommend this method :
for(char letter = 'A'; letter <= 'Z';letter ++){
int letterID = getResources().getIdentifier(""+letter, "id", getPackageName());
TextView txtview = (TextView) getView().findViewById(letterID);
txtview .setTextSize(20 * getResources().getDisplayMetrics().density);
txtview .setText(letter);
txtview .setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
checkGuess(letter);
txtview.setClickable(false);
txtview.setAlpha((float) .1);
}
});
}
A better to make the textviews is create your own textviews in a loop and store it in a hashmap with a single id so you can get each one with out a problem. But if you want to get all one maybe you can do this from a parent you can do this:
String[] lettersMap = {"A", "B", "C",....,"Z"};
HashMap<String, TextView> map = new HashMap<String, TextView>();
// ll is your linear layout or your relative (i.e. your parent of all the textviews)
int childcount = ll.getChildCount();
for (int i=0, letMap = 0; i < childcount; i++){
View v = ll.getChildAt(i);
if (v instanceof TextView) {
TextView tv = (TextView) v;
tv.setTextSize(20 * getResources().getDisplayMetrics().density);
tv.setText(lettersMap[letMap]);
tv.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
checkGuess(lettersMap[letMap]);
tv.setClickable(false);
tv.setAlpha((float) .1);
}
});
map.put(lettersMap[letMpa], tv);
}
}
Related
I have created dynamic layouts, but I don't know how to access their information,search on the interent and I got to this code, but it does not enter the first if
Button add, send,delete;
EditText size;
LinearLayout list, list2,list3;
ArrayList<String> text = new ArrayList<>();
Context context;
#SuppressLint("MissingInflatedId")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
add = findViewById(R.id.add);
size = findViewById(R.id.size);
send = findViewById(R.id.send);
list =findViewById(R.id.list);
list2 =findViewById(R.id.list2);
list3 =findViewById(R.id.list3);
delete = findViewById(R.id.delete);
context = this;
//Toast.makeText(context,""+et.getText().toString(),Toast.LENGTH_SHORT).show();
send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.e("tag","4444444");
for (int i = 0; i<4-list.getChildCount(); i++){
Log.e("tag","555555");
if (list.getChildAt(i) instanceof LinearLayoutCompat) {
Log.d("tag","333333");
LinearLayoutCompat ll = (LinearLayoutCompat) list.getChildAt(i);
for (int j = 0; j < ll.getChildCount() ; j++) {
Log.d("tag","77777");
if(ll.getChildAt(j) instanceof EditText)
{
Log.d("tag","22222222");
EditText et = (EditText) ll.getChildAt(j);
if(et.getId() == R.id.size){
Log.d("tag","1111111");
Toast.makeText(context,""+et.getText().toString(),Toast.LENGTH_SHORT).show();
}
}
}
}
}
}
});
add.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
addView();
}
});
}
what I expected was that in the for it would print the values that I enter in my textView through the toast
I couldn't phrase the question perfectly with my problem, but basically what I want to achieve is this:-
I have recyclerview of items that contains textview for example, when the item is clicked; a custom dialog will show containing the same content of the clicked element.
so far so good, in the same dialog there's two arrow (left & right) at each of its sides, the arrows buttons should navigate between the recyclerview items and update the content according to the new position.
Here's what I did:
#Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
holder.tvTitle.setText(data.get(position).getTitle());
holder.itemView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
//Initializing the custom dailog
final Dialog dialog = new Dialog(context);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.getWindow() .setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
dialog.getWindow().getAttributes().gravity = Gravity.TOP;
dialog.setContentView(R.layout.dailog);
dialog.show();
ImageView RightArrow = (ImageView) dialog.findViewById(R.id.dia_right_arrow);
ImageView LeftArrow = (ImageView) dialog.findViewById(R.id.dia_left_arrow);
final TextView textViewTitle = (TextView) dialog.findViewById(R.id.dia_tvTtile);
textViewTitle.setText(data.get(position).getTitle());
RightArrow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int curPosi = 0;
if (data.size() != 0) {
curPosi = position+1;
}
textViewTitle.setText(data.get(position).getTitle());
}
});
LeftArrow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int curPosi = 0;
if (data.size() != 0) {
curPosi = position-1;
}
textViewTitle.setText(data.get(position).getTitle());
} });
}});
}
The Result:
When I click on the right arrow it works 100% , but if I click again nothing happens !!
And If click the left arrow at anytime it gives crash with this exception:
java.lang.ArrayIndexOutOfBoundsException: length=10; index=-1
Is it possible to achieve a loop effect, what I mean is when I reach
the last index and the click again it shows the first index and vice
versa..!
Any help?
It seems the issue is from how you check your click limits. You can try this
Add curPosi as a class member variable
private int curPosi;
#Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
holder.tvTitle.setText(data.get(position).getTitle());
holder.itemView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
curPosi = position
//Initializing the custom dailog
final Dialog dialog = new Dialog(context);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.getWindow() .setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
dialog.getWindow().getAttributes().gravity = Gravity.TOP;
dialog.setContentView(R.layout.dailog);
dialog.show();
ImageView RightArrow = (ImageView) dialog.findViewById(R.id.dia_right_arrow);
ImageView LeftArrow = (ImageView) dialog.findViewById(R.id.dia_left_arrow);
final TextView textViewTitle = (TextView) dialog.findViewById(R.id.dia_tvTtile);
textViewTitle.setText(data.get(position).getTitle());
RightArrow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int lastIndex = data.size()-1;
if (lastIndex == curPosi ) { // this prevents the crash, so if the next button is clicked while the last index is showing it will reset and show the first one..!
curPosi = 0;
} else if(curPosi < data.size()) {
curPosi++;
}
textViewTitle.setText(data.get(curPosi).getTitle());
}
});
LeftArrow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//same thing here with this "if", when the previous button clicked from the first; it will show the last item..!
if (curPosi == 0) {
curPosi = data.size();
}
if (curPosi > 0) {
curPosi--;
}
textViewTitle.setText(data.get(curPosi).getTitle());
} });
}});
}
Basically what I am trying to accomplish is storing editText view Strings in an array and returning the value of a randomly selected array element. The editText views can be dynamically added and removed so I had to take that into account. I've gone over my method and cannot find what I'm getting wrong.
the problem is is getAnswer(). Currently this is crashing the app
Java:
public class MainActivity extends AppCompatActivity {
private LinearLayout mEditTextContainer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mEditTextContainer = (LinearLayout)findViewById(R.id.linearLayoutDecisions);
setContentView(activity_main);
//Button to choose random editText contents
final Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getAnswer();
}
});
//Button to add editText Field
final Button add_button = (Button) findViewById(R.id.add_button);
add_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Add_Line();
}
});
//Button to remove editText Field
final Button remove_button = (Button) findViewById(R.id.remove_button);
remove_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Remove_Line();
}
});
}
public void Add_Line() {
LinearLayout ll = (LinearLayout)findViewById(R.id.linearLayoutDecisions);
// add edittext
EditText et = new EditText(this);
LinearLayout.LayoutParams p = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
et.setLayoutParams(p);
et.setText(null);
et.setHint("Enter Answer #" + (mEditTextContainer.getChildCount()+1));
et.setGravity(Gravity.CENTER);
mEditTextContainer.addView(et);
}
public void Remove_Line() {
int count = mEditTextContainer.getChildCount();
if(count == 2)
return;
else
mEditTextContainer.removeViewAt(mEditTextContainer.getChildCount()-1);
}
public void getAnswer() {
//get number of possible answers
int count = mEditTextContainer.getChildCount();
//create array to hold answers
String[] options = new String[count--];
//create temporary view to store editText view contents
View tempView;
//Loop to collect and store editText contents
for(int i = 1; i < count-1; i++) {
tempView = mEditTextContainer.getChildAt(i);
if(tempView instanceof EditText){
String tempText = ((EditText) tempView).getText().toString();
if(tempText != null){
options[i] = tempText;
}
else
return;
}
}
int number = (int)(Math.random() * count-1);
String answer = options[number];
TextView answerBox = (TextView)findViewById(R.id.textView7);
answerBox.setText(answer);
}
}
For anyone curious, I found the answer. The variable 'count' should not have been decremented by 1 in my method. Changing this fixed the whole thing.
I have button which starts the same activity. How can I get next image from array, after start activity? Here is code of button
Button btnNext = (Button) dialog.findViewById(R.id.btnNext);
btnNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
finish();
startActivity(getIntent());
}
});
Here is array
int[] array_images = {
R.drawable.apple,
R.drawable.p_dolor
};
Why you exactly want to restart activity every-time, You can just change your resource on button click without Restarting the activity. For example -
int index = 0;
int[] imgRes = {R.id.image1, R.id.image2, R.id.image3, R.id.image4};
Button btnNext = (Button) dialog.findViewById(R.id.btnNext);
btnNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
updateImage();
}
});
private void updateImage(){
index++;
if(index >= imgRes.lenght)
index = 0;
ImageView imageView = findViewById(R.id.myImage);
imageView.setResource(imgRes[index])
}
Hope it will help :)
You can try the below one you have to manage array indexing for that like below:-
int index = 0;
int[] array_images = {R.id.image1, R.id.image2, R.id.image3, R.id.image4};
Button btnNext = (Button) dialog.findViewById(R.id.btnNext);
ImageView imageView = (ImageView)findViewById(R.id.myImage);
setImageRes();
btnNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
setImageRes();
}
});
private void setImageRes(){
index++;
if(index < array_images.lenght){
imageView.setResource(array_images[index])
}
}
You can do this:
int index = 0;
int[] array_images = {R.id.image1, R.id.image2};
Button btnNext = (Button) dialog.findViewById(R.id.btnNext);
ImageView imageView = (ImageView)findViewById(R.id.myImage);
setImageRes(getIntent().getIntExtra());
btnNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
index = getIntent().getIntExtra();
dialog.dismiss();
finish();
Intent intent = new Intent(this,CallActivity.class);
intent.putExtra("position",index++);
}
});
private void setImageRes(int position){
imageView.setResource(array_images[position])
}
I apologize if this code looks a bit like a mess (considering the length); I figured I'd just include everything that goes on in my program at the moment.
I'm attempting to create a fairly simple Tic Tac Toe app for Android. I've set up my UI nicely so far so that there are a "grid" of TextViews. As a sort of "debug" right now, I have it so that when one clicks on a TextView, it should display the value of buttonId in a message box. Right now, it displays the correct assigned value for the first element I click, but no matter what I click afterwards, it always just displays the first value buttonID had. I attempted to debug it but couldn't exactly find a point where it would pull the old value (to the best of my knowledge, it reassigned the value).
There's a good possibility I'm missing something small, because this is my first Android project (of any note). Can someone help get different values of buttonId to appear or point out the error in my logic?
The code:
package com.TicTacToe.app;
import com.TicTacToe.app.R;
//Other import statements
public class TicTacToe extends Activity {
public String player = "X";
public int ALERT_ID;
public int buttonId;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//Sets up instances of UI elements
final TextView playerText = (TextView)findViewById(R.id.CurrentPlayerDisp);
final Button button = (Button) findViewById(R.id.SetPlayer);
final TextView location1 = (TextView)findViewById(R.id.location1);
final TextView location2 = (TextView)findViewById(R.id.location2);
final TextView location3 = (TextView)findViewById(R.id.location3);
final TextView location4 = (TextView)findViewById(R.id.location4);
final TextView location5 = (TextView)findViewById(R.id.location5);
final TextView location6 = (TextView)findViewById(R.id.location6);
final TextView location7 = (TextView)findViewById(R.id.location7);
final TextView location8 = (TextView)findViewById(R.id.location8);
final TextView location9 = (TextView)findViewById(R.id.location9);
playerText.setText(player);
//Handlers for events
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
if (player.equals("X")){
player = "O";
playerText.setText(player);
}
else if(player.equals("O")){
player = "X";
playerText.setText(player);
}
//Sets up the dialog
buttonId = 0;
ALERT_ID = 0;
onCreateDialog(ALERT_ID);
showDialog(ALERT_ID);
}
});
location1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Sets up the dialog
buttonId = 1;
ALERT_ID = 0;
onCreateDialog(ALERT_ID);
showDialog(ALERT_ID);
}
});
location2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Sets up the dialog
buttonId = 2;
ALERT_ID = 0;
onCreateDialog(ALERT_ID);
showDialog(ALERT_ID);
}
});
location3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Sets up the dialog
buttonId = 3;
ALERT_ID = 0;
onCreateDialog(ALERT_ID);
showDialog(ALERT_ID);
}
});
location4.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Sets up the dialog
buttonId = 4;
ALERT_ID = 0;
onCreateDialog(ALERT_ID);
showDialog(ALERT_ID);
}
});
location5.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Sets up the dialog
buttonId = 5;
ALERT_ID = 0;
onCreateDialog(ALERT_ID);
showDialog(ALERT_ID);
}
});
location6.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Sets up the dialog
buttonId = 6;
ALERT_ID = 0;
onCreateDialog(ALERT_ID);
showDialog(ALERT_ID);
}
});
location7.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Sets up the dialog
buttonId = 7;
ALERT_ID = 0;
onCreateDialog(ALERT_ID);
showDialog(ALERT_ID);
}
});
location8.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Sets up the dialog
buttonId = 8;
ALERT_ID = 0;
onCreateDialog(ALERT_ID);
showDialog(ALERT_ID);
}
});
location9.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Sets up the dialog
buttonId = 9;
ALERT_ID = 0;
onCreateDialog(ALERT_ID);
showDialog(ALERT_ID);
}
});
}
protected Dialog onCreateDialog(int id){
String msgString = "You are on spot " + buttonId;
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(msgString)
.setCancelable(false)
.setNeutralButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
return alert;
}
}
You shouldn't be calling onCreateDialog() yourself. Android does that for you when you call showDialog().
I'm sure it only calls onCreateDialog() once and caches the value internally, which is why you're only getting the correct value the first time, and then getting the same value for the rest.
You'll have to think of another way to do what you're trying to do. Perhaps passing a different ID to showDialog() (be sure to handle that ID by creating the correct dialog in onCreateDialog()) is the way to go.
Also, don't import R manually.