I wrote a quiz game in android. I want every time that game goes to next question, all buttons texts also update with each string that exists in string.xml. My string.xml file has include <string> values like below for every questios:
<!-- Second question-->
<string name="secondQ_A1">Oracle</string>
<string name="secondQ_A2">Apple</string>
<string name="secondQ_A3">Sun Microsystems</string> <!-- Right answer -->
<string name="secondQ_A4">IBM</string>
And here's the code:
private Question[] questions = new Question[] {
new Question(R.drawable.first, R.string.first_question_text, R.string.firstQ_A2),
new Question(R.drawable.second, R.string.second_question_text, R.string.secondQ_A3),
new Question(R.drawable.third, R.string.third_question_text, R.string.thirdQ_A2),
};
private ImageView questionImage;
private TextView questionText;
private Button[] answerButtons;
private int currentQuestion = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game_play);
//Initializing
initializeFields();
int textQ = questions[currentQuestion].getResQuestionText();
questionText.setText(textQ);
int imageQ = questions[currentQuestion].getResQuestionImg();
questionImage.setImageResource(imageQ);
for (Button button : answerButtons) {
button.setOnClickListener(v -> {
if (currentQuestion + 1 < questions.length) {
currentQuestion += 1;
updateQuestion();
}
});
}
}
public void updateQuestion() {
int textQ = questions[currentQuestion].getResQuestionText();
questionText.setText(textQ);
int imageQ = questions[currentQuestion].getResQuestionImg();
questionImage.setImageResource(imageQ);
List<Integer> firstQ_answers = new LinkedList<>();
firstQ_answers.add(R.string.firstQ_A1);
firstQ_answers.add(R.string.firstQ_A2);
firstQ_answers.add(R.string.firstQ_A3);
firstQ_answers.add(R.string.firstQ_A4);
for (int i = 0; i< answerButtons.length; i++) {
questions[currentQuestion].setOptions(firstQ_answers);
answerButtons[i].setText(questions[currentQuestion].getOptions().get(i));
}
}
And also Question class:
public class Question {
private int resQuestionText;
private int resQuestionImg;
private int resAnswer;
public Question(int resQuestionImg, int resQuestionText, int resAnswer) {
this.resQuestionImg = resQuestionImg;
this.resQuestionText = resQuestionText;
this.resAnswer = resAnswer;
}
public int getResQuestionText() {
return resQuestionText;
}
public int getResQuestionImg() {
return resQuestionImg;
}
public int getResAnswer() {
return resAnswer;
}
}
The updateQuestion() method just work for question's image and text, but the buttons has no text. I want to update buttons text with that string.xml file values above. Actually I got no idea about it, anyone can guide me?
From your code , you are not even updating it , so you have to do something like this in your updateQueation() method :
answerButtons[0].setText(getString(R.string.secondQ_A1));
answerButtons[1].setText(getString(R.string.secondQ_A2));
answerButtons[2].setText(getString(R.string.secondQ_A3));
answerButtons[3].setText(getString(R.string.secondQ_A4));
As best practice you should define a global two dimensional array to hold all questions index and its options like :
int[][] myOptions ={{allFirstQuestionAnswersResHere},{second},{third},...};
And then in updateQuestion() use question number to get the options from your global array like :
for(int i=0;i<answerButtons.length();i++){
answerButtons[i].setText(myOptions[questionIndex][i]);
}
Enjoy !
you are using int as a text in your question that's why it cant be set so
questionText.setText(" "+textQ);
or change int questionText to String questionText.
You can achieve the same by changing your question class like this
public class Question {
private int resQuestionText;
private int resQuestionImg;
private int resAnswer[];
public Question(int resQuestionImg, int resQuestionText, int resAnswer[]) {
this.resQuestionImg = resQuestionImg;
this.resQuestionText = resQuestionText;
this.resAnswer = resAnswer;
}
public int getResQuestionText() {
return resQuestionText;
}
public int getResQuestionImg() {
return resQuestionImg;
}
public int [] getResAnswer() {
return resAnswer;
}
}
and then in your updateQuestion method
public void updateQuestion() {
// you can get array of button text for each question like below and can update your buttons text by iterating through this array
int buttonTexts[] = questions[currentQuestion].getResAnswer();
int textQ = questions[currentQuestion].getResQuestionText();
questionText.setText(textQ);
int imageQ = questions[currentQuestion].getResQuestionImg();
questionImage.setImageResource(imageQ);
}
Related
I really need your help. I've searched Google many days with many keywords, but I couldn't get it. So, I decided to ask to you.
So, here it is. Actually, I have one button in RecyclerView, but this button is repeated as much amount of data available, there are: Button with text "Baca 3x", "Baca 4x", and so on. I want, if I click button with text "Baca 3x" 3 times, it will change to "Baca 2x" >> "Baca 1x" >> remove item. Also if I click button with text "Baca 4x" 4 times, it will change to "Baca 3x" >> "Baca 2x" >> "Baca 1x" >> remove item.
But my problem is, I can't treat every button with different treatment, because every time the item has been deleted, position of data changes automatically. Because of this, I can't get specific button. For example: There is two button,
1. Button "Baca 3x" on position 0
2. Button "Baca 4x" on position 1
If button "Baca 3x" on position 0 has been deleted, so button "Baca 4x" changed it's position automatically to 0. The problem lays here.
Until now I just get every button based on their positions, which is a problem for me. Because of this I am thinking about How to Delete Item Without Deleting Position in Recycler View? Can you guys solve my problem? Should I use DiffUtil?And how to use it? Below the complete code I use:
ModelDoa.java
public class ModelDoa {
public static final int DOA_PAGI = 0;
public static final int DOA_SORE = 1;
public static final int DOA_MASJID = 2;
public static final int DOA_BANGUNT = 3;
public static final int DOA_MAU_TIDUR = 4;
private String mName;
private String bName;
private int mType;
public ModelDoa(String name, String butong, int type) {
this.mName = name;
this.bName = butong;
this.mType = type;
}
public String getName() {
return mName;
}
public void setName(String name) {
this.mName = name;
}
public int getType() {
return mType;
}
public void setType(int type) { this.mType = type; }
public String ambilName() {
return bName;
}
public void setNama(String butonk) {
this.bName = butonk;
}
}
AdapterDoa.java
public class AdapterDoa extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
public List<ModelDoa> mList;
public AdapterDoa(List<ModelDoa> list) {
this.mList = list;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
switch (viewType) {
case DOA_PAGI:
View vieu = LayoutInflater.from(parent.getContext()).inflate(R.layout.content_doa, parent, false);
PagiViewHolder rcv = new PagiViewHolder(vieu, this);
return rcv;
case DOA_SORE:
View doa = LayoutInflater.from(parent.getContext()).inflate(R.layout.content_doa, parent, false);
SoreViewHolder mdoa = new SoreViewHolder(doa);
return mdoa;
case DOA_MASJID:
View dMasjid = LayoutInflater.from(parent.getContext()).inflate(R.layout.content_doa, parent, false);
MasjidViewHolder mMasjid = new MasjidViewHolder(dMasjid);
return mMasjid;
case DOA_BANGUNT:
View dBangunt = LayoutInflater.from(parent.getContext()).inflate(R.layout.content_doa, parent, false);
BanguntViewHolder mBangunt = new BanguntViewHolder(dBangunt);
return mBangunt;
case DOA_MAU_TIDUR:
View regut = LayoutInflater.from(parent.getContext()).inflate(R.layout.content_doa, parent, false);
MauTidurViewHolder turu = new MauTidurViewHolder(regut);
return turu;
}
return null;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
ModelDoa object = mList.get(position);
if (object != null) {
switch (object.getType()) {
case DOA_PAGI:
((PagiViewHolder) holder).mTitle.setText(object.getName());
((PagiViewHolder) holder).tombolbaca.setText(object.ambilName());
break;
case DOA_SORE:
((SoreViewHolder) holder).mTitle.setText(object.getName());
((SoreViewHolder) holder).tombolbaca.setText(object.ambilName());
break;
case DOA_MASJID:
((MasjidViewHolder) holder).mTitle.setText(object.getName());
((MasjidViewHolder) holder).tombolbaca.setText(object.ambilName());
break;
case DOA_BANGUNT:
((BanguntViewHolder) holder).mTitle.setText(object.getName());
((BanguntViewHolder) holder).tombolbaca.setText(object.ambilName());
break;
case DOA_MAU_TIDUR:
((MauTidurViewHolder) holder).mTitle.setText(object.getName());
((MauTidurViewHolder) holder).tombolbaca.setText(object.ambilName());
break;
}
}
}
public void deleteItem(int position) {
mList.remove(position); // hapus list
notifyItemRemoved(position); // hapus tampilan
// notifyItemRangeChanged( position, mList.size());
}
#Override
public int getItemCount() {
if (mList == null)
return 0;
return mList.size();
}
#Override
public int getItemViewType(int position) {
if (mList != null) {
ModelDoa object = mList.get(position);
if (object != null) {
return object.getType();
}
}
return 0;
}
}
PagiViewHolder.java
public class PagiViewHolder extends RecyclerView.ViewHolder {
public TextView mTitle;
public Button tombolbaca;
public Button teksbaca;
public Button tombolshare;
private RelativeLayout rl2;
private int klik10 = 10;
private AdapterDoa myAdapter;
public PagiViewHolder(View itemView, AdapterDoa myAdapter) {
super(itemView);
this.myAdapter = myAdapter;
itemView.setOnClickListener(mainViewClickListener);
mTitle = (TextView) itemView.findViewById(R.id.titleTextView);
tombolbaca = (Button) itemView.findViewById(R.id.buttonbaca);
tombolshare = (Button) itemView.findViewById(R.id.buttonshare);
tombolbaca.setOnClickListener(bacaClickListener);
tombolshare.setOnClickListener(shareClickListener);
rl2 = (RelativeLayout) itemView.findViewById(R.id.relmasjid);
}
private View.OnClickListener bacaClickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
teksbaca = (Button) v.findViewById(R.id.buttonbaca);
// Baca 10x
if( getAdapterPosition() ==0 ) {
klik10--;
teksbaca.setText("Baca " + klik10 + "x");
if (klik10 <= 0)
{
// modify listItems however you want... add, delete, shuffle, etc
myAdapter.deleteItem(getAdapterPosition());
}
}
} // onclick
};
private View.OnClickListener shareClickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
// Do button click handling here
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, mTitle.getText().toString() + "\n \n download aplikasinya di: http://www.tauhid.or.id" );
sendIntent.setType("text/plain");
Intent.createChooser(sendIntent,"Share via");
v.getContext().startActivity(sendIntent);
}
};
private View.OnClickListener mainViewClickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
// Do button click handling here
}
};
}
DoaPagi.java
public class DoaPagi extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_doa_pagi);
// toolbar
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//this line shows back button
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
List<ModelDoa> rowListItem = getData();
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(DoaPagi.this);
RecyclerView mRecyclerView = (RecyclerView) findViewById(R.id.recyclerView);
mRecyclerView.setLayoutManager(linearLayoutManager);
mRecyclerView.setHasFixedSize(true);
AdapterDoa rcAdapter = new AdapterDoa(rowListItem);
mRecyclerView.setAdapter(rcAdapter);
}
private List<ModelDoa> getData() {
String[] data = getResources().getStringArray(R.array.doapagi);
String[] baca = getResources().getStringArray(R.array.bacapagi);
List<ModelDoa> list = new ArrayList<ModelDoa>();
for (int i = 0; i < data.length; i++) {
list.add(new ModelDoa(data[i], baca[i], ModelDoa.DOA_PAGI));
}
return list;
}
// Agar back button pada halaman induk settings berfungsi
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
this.finish();
return true;
}
return super.onOptionsItemSelected(item);
}
}
UPDATE (FIX CODE) By: Krishna Sharma:
https://github.com/seadclark/RecyclerViewWithButtonClicks
Here is the fix. just update the ModelDoa constructor as below. I have verified myself and working as expected now. Also sent you pull request on github.
public ModelDoa(String name, String butong, int type) {
this.mName = name;
this.bName = butong;
this.mType = type;
String[] data = butong.split("\\s");
if (data.length > 0) {
String count = data[1].substring(0, data[1].length() - 1);
read10 = Integer.parseInt(count);
}
}
Instead of removing the item from your list AND updating the interface, have two methods. One of them (deleteItem) will only delete the item and the other (deleteItemAndUpdate) will delete the item and update the interface.
public void deleteItem(int position) {
mList.remove(position); // hapus list
}
public void deleteItemAndUpdate(int position) {
mList.remove(position); // hapus list
notifyItemRemoved(position); // hapus tampilan
}
In the future, you can decide whether you want to only remove the item from your list OR remove the item and update the UI.
EDIT 1:
You need to keep track of the amount of times that each item was clicked. We can call this value readCount. Every time that the item is clicked, we subtract 1 from this value. When this value reaches 0, we remove it from the list.
ModelDoa:
public class ModelDoa {
private int readCount = 10;
public int getReadCount() {
return this.readCount;
}
public void setReadCount(int readCount) {
this.readCount = readCount;
}
}
PagiViewHolder:
private View.OnClickListener bacaClickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
teksbaca = (Button) v.findViewById(R.id.buttonbaca);
ModelDoa modelDoa = mAdapter.getItem(getAdapterPosition());
if (modelDoa != null) {
modelDoa.setReadCount(modelDoa.getReadCount() - 1);
if (modelDoa.getReadCount() <= 0) {
myAdapter.deleteItem(getAdapterPosition());
}
teksbaca.setText("Baca " + modelDoa.getReadCount() + "x");
}
}
};
AdapterDoa:
public ModelDoa getItem(int position) {
if (position > -1 && position < getItemCount()) {
return this.mList.get(position);
} else {
return null;
}
}
EDIT 2:
The idea is to set the readCount variable when you instantiate the object. You do not have multiple variables that do the same thing. You just change the single readCount variable to be either 7 or 10 when you are creating it and use the same getItem method when retrieving the model (not variable!) itself.
ModelDoa:
public class ModelDoa {
private String name;
private String butong;
private int type;
private int readCount;
public ModelDoa(String name, String butong, int type, int readCount) {
this.mName = name;
this.bName = butong;
this.mType = type;
this.readCount = readCount;
}
public int getReadCount() {
return this.readCount;
}
public void setReadCount(int readCount) {
this.readCount = readCount;
}
}
DoaPagi:
private List<ModelDoa> getData() {
String[] data = getResources().getStringArray(R.array.doapagi);
String[] baca = getResources().getStringArray(R.array.bacapagi);
List<ModelDoa> list = new ArrayList<ModelDoa>();
for (int i = 0; i < data.length; i++) {
// Here is where you would set the value of readCount.
list.add(new ModelDoa(data[i], baca[i], ModelDoa.DOA_PAGI, i));
}
return list;
}
Greeting peeps, need help on this error. trying googling but did not solve the issue. i did put remarks in which lines the errors occur.
notice below code have 2 different java class
[IMG="screenshot"]http://i.imgur.com/XYFHZOz.png[/IMG]
public class QuestionAndAnswer {
public List<String> allAnswers; // distractors plus real answer
public String answer;
public String question;
public String selectedAnswer;
public int selectedId = -1;
public QuestionAndAnswer(String question, String answer, List<String> distractors) {
this.question = question;
this.answer = answer;
allAnswers = new ArrayList<String>(distractors);
// Add real answer to false answers and shuffle them around
allAnswers.add(answer);
Collection.shuffle(allAnswers); //error on this line
}
public boolean isCorrect() {
return answer.equals(selectedAnswer);
}
}
public class UjiSalah extends Activity {
RadioGroup rg;
int currentQuestion = 0;
TextView tv;
List<QuestionAndAnswer> quiz = new ArrayList<QuestionAndAnswer>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.uji_salah);
tv = (TextView) findViewById(R.id.tvque);
rg = (RadioGroup) findViewById(R.id.radioGroup1);
// Setup a listener to save chosen answer
rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
if(checkedId > -1) {
QuestionAndAnswer qna = quiz.get(currentQuestion);
qna.selectedAnswer = ((RadioButton) group.findViewById(checkedId)).getText().toString();
qna.selectedId = checkedId;
}
}
});
String[] question = {"Bilangan Rokaat Solah Zuhur ?","Bilangan Rokaat Solat Subuh ?","Bilangan Rokaat Solat Maghrib ?"};
String[] answer = { "4 rokaat","2 rokaat","3 rokaat" };
String[] distractor = { "5 rokaat","1 rokaat","4 rokaat","2 rokaat","3 rokaat","4 rokaat","4 rokaat","5 rokaat","3 rokaat" };
ArrayList<String> distractorList = Arrays.asList(distractor); //error on this line
int length = question.length;
for(int i = 0; i < length; i++)
quiz.add(new QuestionAndAnswer(question[i], answer[i], distractorList.subList(i * 3, (i + 1) * 3)));
Collection.shuffle(quiz); //error here
fillInQuestion();
}
public void fillInQuestion() {
QuestionAndAnswer qna = quiz.get(currentQuestion);
tv.setText(qna.question);
// Set all of the answers in the RadioButtons
int count = rg.getChildCount();
for(int i = 0; i < count; i++)
((RadioButton) rg.getChildAt(i)).setText(qna.allAnswers.get(i));
// Restore selected answer if exists otherwise clear previous question's choice
if(qna.selectedId > -1)
rg.check(qna.selectedId);
else
rg.clearCheck();
}
}
+1#Prerak Sola, you can either declare allAnswers as ArrayList or cast it like so:
Collection.shuffle((ArrayList)allAnswers);
List doesn't implement Collection interface, but ArrayList does:
https://docs.oracle.com/javase/7/docs/api/java/util/Collection.html
List quiz = new ArrayList<>();
to
ArrayList<QuestionAndAnswer> quiz = new ArrayList<>();
i have this small app that chooses values in a number picker and is supposed to dynamically change the background color. through log messages i have seen that the hex color value is generated correctly, but when i call set background color an error pops up and the program crashes.
the error java.lang.NumberFormatException: Invalid int: "0xFF010000"....
the issue (i think) is in the setBackground() call at the bottom of ActivityMain.
here is my code:
package com.example.android.test;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.NumberPicker;
import android.widget.NumberPicker.OnValueChangeListener;
public class MainActivity extends Activity {
static final int MIN_VAL = 0;
static final int MAX_VAL = 255;
NumberPicker alphaPicker, redPicker, greenPicker, bluePicker;
View colorView;
Color bgColor = new Color();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
alphaPicker = (NumberPicker) findViewById(R.id.alphaPicker);
redPicker = (NumberPicker) findViewById(R.id.redPicker);
greenPicker = (NumberPicker) findViewById(R.id.greenPicker);
bluePicker = (NumberPicker) findViewById(R.id.bluePicker);
alphaPicker.setMinValue(MIN_VAL);
alphaPicker.setMaxValue(MAX_VAL);
alphaPicker.setWrapSelectorWheel(false);
redPicker.setMinValue(MIN_VAL);
redPicker.setMaxValue(MAX_VAL);
redPicker.setWrapSelectorWheel(false);
greenPicker.setMinValue(MIN_VAL);
greenPicker.setMaxValue(MAX_VAL);
greenPicker.setWrapSelectorWheel(false);
bluePicker.setMinValue(MIN_VAL);
bluePicker.setMaxValue(MAX_VAL);
bluePicker.setWrapSelectorWheel(false);
colorView = findViewById(R.id.color_box);
colorView.setBackgroundColor(0xFF000000);
redPicker.setOnValueChangedListener(new OnValueChangeListener() {
#Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
bgColor.setRedVal(newVal);
Log.v(bgColor.getRedVal(), " = redVal");
Log.v(bgColor.getColorCode(), " = color code");
colorView.setBackgroundColor(bgColor.getColorCodeAsInt());
}
});
}
}
and the color class incase you are wondering how i generated the hex value:
package com.example.android.test;
public class Color {
private String redVal;
private String blueVal;
private String greenVal;
private String alphaVal;
private String colorCode;
public Color (){
alphaVal = "FF";
redVal = "00";
greenVal = "00";
blueVal = "00";
colorCode = "0xFF000000";
}
public void generateColorCode() {
StringBuilder theColor = new StringBuilder("0x")
.append(this.alphaVal)
.append(this.redVal)
.append(this.greenVal)
.append(this.blueVal);
colorCode = theColor.toString();
}
public String getRedVal() {
return redVal;
}
public void setRedVal(Integer redVal) {
this.redVal = String.format("%02x", redVal);
generateColorCode();
}
public String getBlueVal() {
return blueVal;
}
public void setBlueVal(Integer blueVal) {
this.blueVal = String.format("%02x", blueVal);
}
public String getGreenVal() {
return greenVal;
}
public void setGreenVal(Integer greenVal) {
this.greenVal = String.format("%02x", greenVal);
}
public String getAlphaVal() {
return alphaVal;
}
public void setAlphaVal(Integer alphaVal) {
this.alphaVal = String.format("%02x", alphaVal);
}
public String getColorCode() {
return colorCode;
}
public Integer getColorCodeAsInt() {
return Integer.parseInt(colorCode, 16);
}
}
I would actually use the standard Android Color API to get the color.
Color.parseColor(colorCode);
http://developer.android.com/reference/android/graphics/Color.html#parseColor%28java.lang.String%29
1) Your int is too big, because the Integer.parseInt() function only takes a signed int as an argument.
0xFF010000 == 4294901760 // your number
0x7FFFFFFF == 2147483647 // maximum signed Integer Value
You can fix this easily by using parseLong instead
0xFFFFFFFF == 4294967295 // RGBA color format maximum
Long.MAX_VALUE == 9223372036854775807L // maximum signed Long value
Implemented in your code it would look like this:
public int getColorCodeAsInt() {
return (int)Long.parseLong(colorCode, 16);
}
2) As Alexander pointed out in his answer, don't include the "0x"-bit, the 'x' will mess up the parser.
---EDIT---
Thanks to Alexander I came up with another solution, you could always do this:
public int getColorCodeAsInt() {
// this would return hex value 0xFFFFFFF8;
return (Integer.parseInt("FFFFFFF", 16) * 16) // first 7 digits
+ Integer.parseInt("8", 16); // last digit
}
This works because the datatype int itself actually can contain RGBA data.
Exclude "0x" part from your number string
I use the example here: https://gwt-dnd.appspot.com/#InsertPanelExample with only one column.
The column is a VerticalPanel which contains many Widgets.
Using the VerticalPanelDropController I can register:
#Override
public void onDrop(DragContext context) {
super.onDrop(context);
final Widget widget = context.draggable;
final int newIndex = columnPanel.getWidgetIndex(widget);
}
#Override
public void onPreviewDrop(DragContext context) throws VetoDragException {
super.onPreviewDrop(context);
int newIndex = ???
}
in onDrop() I can get the new position of a widget in the columnPanel with columnPanel.getWidgetIndex(widget) but in onPreviewDrop() I cannot do it because the widget is not inside the columnPanel at this time.
How do I get the target index where a dropped Widget should be dropped into the columnPanel in onPreviewDrop()? I want to know where the widget should be inserted before it is inserted. This way I can cancel the insertion.
The following does only work if the positioner widget has the same structure as the placeholder when the row was dragged.
int newIndex = dropTarget.getWidgetIndex(newPositioner(context));
I use the following code to get the correct index:
#Override
public void onPreviewDrop(DragContext context)
throws VetoDragException {
super.onPreviewDrop(context);
int newIndex = -1;
String positionerClass = newPositioner(context).getElement()
.getClassName();
for (int i = 0; i < dropTarget.getWidgetCount(); i++) {
String widgetClass = dropTarget.getWidget(i).getElement()
.getClassName();
if (widgetClass.equals(positionerClass)) {
newIndex = i;
}
}
};
You need to call
dropTarget.getWidgetIndex(newPositioner(context));
like this:
#Override
public void onPreviewDrop(DragContext context) throws VetoDragException {
super.onPreviewDrop(context);
int newIndex = dropTarget.getWidgetIndex(newPositioner(context));
}
i would like to generate 24 string values on 24 textview which i created the xml file in android and also i code for the getid and set listener but not mentioned here.
In the override oncick method i define the click fun method.
In this code i simply code for the integer values but now i would like to compare from the string array which has static values like
String[] value = {11,12,13,14,15,16,17,18,19,20,21,22,11,12,13,14,15,16,17,18,19,20,21,22};
Please help me to resolve my problem.
public class GameDemo extends Activity implements AnimationListener, OnClickListener
{
FrameLayout iv1,iv2,iv3,iv4,iv5,iv6,iv7,iv8,iv9,iv10,iv11,iv12,iv13,iv14,iv15,iv16,iv17,iv18,iv19,iv20,iv21,iv22,iv23,iv24;
TextView tv1,tv2,tv3,tv4,tv5,tv6,tv7,tv8,tv9,tv10,tv11,tv12,tv13,tv14,tv15,tv16,tv17,tv18,tv19,tv20,tv21,tv22,tv23,tv24;
Animation an1,an2;
int i1,counter,score,rev_count,level_counter;
boolean r_c,s_c;
Integer[] no;
FrameLayout[] count,rem,revise;
final Context context = this;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game_demo);
an1 = AnimationUtils.loadAnimation(this,R.anim.flip1);
an1.setAnimationListener(this);
an2 = AnimationUtils.loadAnimation(this,R.anim.flip1);
an2.setAnimationListener(this);
level_counter=24;
getIDForAll();
setListnerForAll();
counter=1;
rev_count=0;
no = new Integer[25];
count = new FrameLayout[3];
rem = new FrameLayout[3];
revise = new FrameLayout[8];
int i=0;
for(i=0 ; i<24 ; i++)
{
Random r = new Random();
i1 = r.nextInt(25 - 1) + 1;
if(i!=0)
{
while(Arrays.asList(no).contains(i1))
{
r = new Random();
i1 = r.nextInt(25 - 1) + 1;
}
no[i]= i1 ;
}
else
{
no[i]= i1 ;
}
}
public void click_fun(FrameLayout arg0, TextView arg1, int n)
{
if(counter<2)
{
arg0.setAnimation(an1);
if(no[n]<=12)
{
arg1.setText(""+no[n]);
arg0.setBackgroundResource(android.R.color.white);
}
else
{
arg1.setText(""+(no[n]-12));
arg0.setBackgroundResource(android.R.color.white);
}
arg0.setTag(no[n]);
count[counter] = arg0;
counter++;
Log.i("animate", "anim2");
}
else
{
Log.i("animate", "animo1");
arg0.setAnimation(an1);
if(no[n]<=12)
{
arg1.setText(""+no[n]);
arg0.setBackgroundResource(android.R.color.white);
}
else
{
arg1.setText(""+(no[n]-12));
arg0.setBackgroundResource(android.R.color.white);
}
arg0.setTag(no[n]);
count[counter] = arg0;
counter++;
Log.i("animate", "animo2");
Uri uri = Uri.parse("android.resource://com.game/drawable/ic_launcher");
int temp1 = (Integer) count[1].getTag();
int temp2 = (Integer) arg0.getTag();
Log.i("animate", "animo3");
if((temp1-temp2)==-12 || temp1-temp2==12)
{
rem[1]=count[1];
rem[2]=count[2];
s_c=true;
score=score+10;
score_lbl.setText("Score : "+score);
score=score+10;
score_lbl.setText("Score : "+score);
level_counter=level_counter-2;
}
else
{
rev_count++;
revise[rev_count]=count[1];
rev_count++;
revise[rev_count]=count[2];
r_c=true;
score=score-2;
score_lbl.setText("Score : "+score);
}
counter=1;
}
}
I don't think I understand your situation fully.
1. Create an array of String resources:
private Integer[] Strings = { many, strings, R.string.stringa };
2. Call a method to get a random resource:
getRandomString(int);
3. Return a random String:
private String getRandomString(int random)
return getString( Strings[ random ] );