I am trying to return a button object from a view to subsequently run setText against.
I am having trouble converting it though.
Any advice appreciated.
public Button aiPlayerPick() {
Button btn = null;
TableLayout tableLayout = (TableLayout) findViewById(R.id.tableLayout);
for (int rowIndex = 0; rowIndex < tableLayout.getChildCount(); rowIndex++) {
View tableLayoutChild = tableLayout.getChildAt(rowIndex);
if (tableLayoutChild instanceof TableRow) {
for (int i = 0; i < ((ViewGroup) tableLayoutChild).getChildCount(); i++) {
View view = ((ViewGroup) tableLayoutChild).getChildAt(i);
if (view instanceof Button && view.getTag() == aiPickedButton) {
View btn_v = view.findViewWithTag(aiPickedButton);
System.out.println("Button: " + btn_v);
btn = (Button) findViewById(R.id.btn_v); // Problem is here, I can't get that view to be seen as a button
break;
} else {
i++;
}
}
}
}
return btn;
}
You've already retrieved the View (parent of the Button) to your code with:
View btn_v = view.findViewWithTag(aiPickedButton);
So the only thing you need to do is cast it to be a Button with btn = (Button) someView. Your code would look like:
View btn_v = view.findViewWithTag(aiPickedButton);
System.out.println("Button: " + btn_v);
btn = (Button) btn_v;
System.out.println("Button: " + btn);
Related
This is my code for a button. Whenever i click this the app shuts down!I am unable to understand why it's happening?
In my code, I am trying to check if values from dynamically created EditText field has been stored on my variable array values[] and bValues[];
I looked for many answers here on how to retrieve value from dynamic edittext fields. And I came up with this from my understanding.
Can anyone tell me where am I going wrong? And a corrected demo code will be of help!
public class MainActivity extends AppCompatActivity {
private static int a;
private static EditText ainput;
private static Button btn, set;
TextView equal_sign;
private static TableLayout tableLayout;
private static LinearLayout bMatrix;
List<EditText> allEds = new ArrayList<EditText>(a*a);
double[] values = new double[(allEds.size())];
List<EditText> bMatrixValues = new ArrayList<EditText>(a);
double[] bValues = new double[bMatrixValues.size()];
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ainput = (EditText) findViewById(R.id.a);
btn = (Button) findViewById(R.id.btn);
set = (Button)findViewById(R.id.set);
tableLayout = (TableLayout) findViewById(R.id.table1);
equal_sign = (TextView) findViewById(R.id.equal_sign);
bMatrix = (LinearLayout) findViewById(R.id.bMatrix);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
a = Integer.parseInt(ainput.getText().toString());
tableLayout.removeAllViews();
createMatrix();
}
});
set.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
for (int i = 0; i < allEds.size(); i++){
values[i] = Double.parseDouble(allEds.get(i).getText().toString());
}
for (int j = 0 ; j < bMatrixValues.size(); j++){
bValues[j] = Double.parseDouble(bMatrixValues.get(j).getText().toString());
}
if (allEds.size() > 0 && bMatrixValues.size() > 0){
Toast.makeText(MainActivity.this, "Main Matrix Values inserted!", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(MainActivity.this, "Insertion failed!", Toast.LENGTH_SHORT).show();
}
}
});
}
private void createMatrix() {
int p = 1;
for (int i = 0; i < a; i++) {
TableRow row = new TableRow(this);
TableRow.LayoutParams lp = new
TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT,
TableRow.LayoutParams.WRAP_CONTENT);
lp.gravity = Gravity.CENTER;
row.setLayoutParams(lp);
EditText magicField;
for (int j = 0; j < a; j++) {
magicField = new EditText(MainActivity.this);
allEds.add(magicField);
magicField.setId((p));
magicField.setHint("et-" + (Integer.toString(p)));
magicField.setGravity(Gravity.CENTER);
magicField.setWidth(100);
row.addView(magicField, j);
p++;
}
tableLayout.addView(row, i);
}
bMatrix.removeAllViews();
equal_sign.setText("=");
equal_sign.setTextSize(30);
createBMatrix();
}
private void createBMatrix() {
int id = (a * a) + 1;
for (int s = 0; s < a; s++) {
final EditText b = new EditText(this);
bMatrixValues.add(b);
b.setId(id);
b.setHint("b-" + (Integer.toString(s + 1)));
b.setGravity(Gravity.CENTER);
b.setWidth(100);
bMatrix.addView(b);
id++;
}
}
}
And this is the output screen!
Matrix style edit text field gets created nicely. But when i give values to those fields and click on set value button app shuts down..
Using Button on a row in the ListView and am able to make a single row Spannable and data from database but when i click it is not responding to click here is my code from MyAdapter Class where am entering values from database to Listview
public View getView(int i, View view, ViewGroup viewGroup) {
Realm realm=Realm.getDefaultInstance();
Word toEdit = realm.where(Word.class)
.equalTo("id", 10).findFirst();
int id_to_seperate=toEdit.getLang();
LayoutInflater inflater= (LayoutInflater) Main.context.getSystemService(Main.context.LAYOUT_INFLATER_SERVICE);
View row= inflater.inflate(R.layout.layout,viewGroup,false);
TextView word= (TextView) row.findViewById(R.id.word_name);
TextView meaning= (TextView) row.findViewById(R.id.word_define);
Word temp=list.get(i);
int idz=temp.getId();
word.setText(temp.getWord());
if(id_to_seperate==idz){
String span[] = temp.getMeaning().substring(1).split(" ") ;
SpannableString ss = new SpannableString(temp.getMeaning().substring(1));
ClickableSpan spans[] = new ClickableSpan[span.length];
for(int spanCount = 0 ; spanCount < span.length ; spanCount++){
spans[spanCount] = new ClickableSpan() {
#Override
public void onClick(View textView) {
TextView v = (TextView)textView ;
String text = v.getText().toString() ;
Log.d("View" , text);
}
};
}
int start = 0 ;
int end =0;
try {
for(int spanCount = 0 ; spanCount <span.length ; spanCount++){
if(spanCount==0) {
end += span[spanCount].length();
}else{
end += span[spanCount].length()+1;
}
ss.setSpan(spans[spanCount], start, end , Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
start += span[spanCount].length()+1;
}
} catch (Exception e) {
e.printStackTrace();
}
meaning.setText(ss);
}else {
meaning.setText(temp.getMeaning().substring(1));
}
return row;
}
am able to get result from a specific row in a list
to this But click Functionality not working, I would be thankful if anyone can tell me what mistake I have done
Regards
Before return add
meaning.setMovementMethod(LinkMovementMethod.getInstance());
This method enabled clicable on link.
In a listview, on each row, I have 10 buttons. When any of those buttons pressed, color of the buttons should changed (its like filling the bar based on where you pressed) .
Here is what I've done so far:
I have added references of each button to an ArrayList called buttons.
Also, I have an ArrayList which has colors strings.
This is click listener that is assigned to each button.
This is complete code form my adapter class of the listview.
public class TeacherRatingAdapter extends ArrayAdapter<Votes> {
private ArrayList<String> colors = new ArrayList();
private ArrayList<Button> buttons = new ArrayList<>();
private LayoutInflater inflater;
private ArrayList<Votes> mItems = new ArrayList<>();
private ArrayList<Votes> mItemsTemp = new ArrayList<>();
private int teacher;
private boolean myTeacher;
private ArrayList<Pair<Integer, Integer>> questionHint = new ArrayList<>();
private static int givenMark;
private HashMap<String, Integer> givenMarks = new HashMap<>();
ViewHolder viewHolder;
public TeacherRatingAdapter(Context context, TeacherRating teacherRating) {
super(context, -1, teacherRating.getVotes());
mItems = teacherRating.getVotes();
if(mItems.size()==0){
for(int i = 0; i<10; i++){
mItems.add(new Votes());
}
}
for(int i = 0; i<teacherRating.getVotes().size(); i++){
givenMarks.put(String.valueOf(i+1), teacherRating.getVotes().get(i).getAll().get(i));
}
teacher = teacherRating.getTeacher();
myTeacher = teacherRating.isMy_teacher();
questionHint.add(new Pair<>(R.string.question1, R.string.questionHint1));
questionHint.add(new Pair<>(R.string.question2, R.string.questionHint2));
questionHint.add(new Pair<>(R.string.question3, R.string.questionHint3));
questionHint.add(new Pair<>(R.string.question4, R.string.questionHint4));
questionHint.add(new Pair<>(R.string.question5, R.string.questionHint5));
questionHint.add(new Pair<>(R.string.question6, R.string.questionHint6));
questionHint.add(new Pair<>(R.string.question7, R.string.questionHint7));
questionHint.add(new Pair<>(R.string.question8, R.string.questionHint8));
questionHint.add(new Pair<>(R.string.question9, R.string.questionHint9));
questionHint.add(new Pair<>(R.string.question10, R.string.questionHint10));
colors.add("#E77272");
colors.add("#E77D72");
colors.add("#E78D72");
colors.add("#E7A472");
colors.add("#E8B472");
colors.add("#E8C272");
colors.add("#E8C272");
colors.add("#E6E773");
colors.add("#c3e874");
colors.add("#89e874");
}
#Override
public int getCount() {
return mItems.size() > 0 ? mItems.size() : 1;
}
#Override
public boolean isEnabled(int position) {
return mItems.size() != 0;
}
View.OnClickListener clickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
Button button = (Button) v;
String text = button.getText().toString();
if(text.equals("1")){
givenMark = 1;
}else if(text.equals("2")){
givenMark = 2;
}else if(text.equals("3")){
givenMark = 3;
}else if(text.equals("4")){
givenMark = 4;
}else if(text.equals("5")){
givenMark = 5;
}else if(text.equals("6")){
givenMark = 6;
}else if(text.equals("7")){
givenMark = 7;
}else if(text.equals("8")){
givenMark = 8;
}else if(text.equals("9")){
givenMark = 9;
}else if(text.equals("10")){
givenMark = 10;
}
colorButton(givenMark, viewHolder);
// button.setBackgroundColor(Color.parseColor(colors.get(givenMark)));
mItems.get(Integer.valueOf(button.getTag().toString())).addOne(Integer.valueOf(text));
// mItems.get(Integer.valueOf(button.getTag().toString())).setScore(Integer.valueOf(text), givenMark);
// givenMarks.put(button.getTag().toString(), givenMark);
notifyDataSetChanged();
}
};
#Override
public View getView(int position, View convertView, ViewGroup parent) {
inflater = LayoutInflater.from(getContext());
if (mItems.size() == 0) {
if (!Common.isNetworkConnected(getContext())) {
convertView = inflater.inflate(R.layout.list_item_no_internet, null, false);
} else {
convertView = inflater.inflate(R.layout.list_item_no_content, null, false);
}
return convertView;
} else {
if (convertView == null) {
buttons.clear();
convertView = inflater.inflate(R.layout.list_item_teacher_rating, parent, false);
viewHolder = new ViewHolder();
viewHolder.mQuestionTextView = (TextView) convertView.findViewById(R.id.question);
viewHolder.mHintTextView = (TextView) convertView.findViewById(R.id.question_hint);
viewHolder.button1 = (Button) convertView.findViewById(R.id.question_button_1);
viewHolder.button2 = (Button) convertView.findViewById(R.id.question_button_2);
viewHolder.button3 = (Button) convertView.findViewById(R.id.question_button_3);
viewHolder.button4 = (Button) convertView.findViewById(R.id.question_button_4);
viewHolder.button5 = (Button) convertView.findViewById(R.id.question_button_5);
viewHolder.button6 = (Button) convertView.findViewById(R.id.question_button_6);
viewHolder.button7 = (Button) convertView.findViewById(R.id.question_button_7);
viewHolder.button8 = (Button) convertView.findViewById(R.id.question_button_8);
viewHolder.button9 = (Button) convertView.findViewById(R.id.question_button_9);
viewHolder.button10 = (Button) convertView.findViewById(R.id.question_button_10);
viewHolder.button1.setOnClickListener(clickListener);
viewHolder.button2.setOnClickListener(clickListener);
viewHolder.button3.setOnClickListener(clickListener);
viewHolder.button4.setOnClickListener(clickListener);
viewHolder.button5.setOnClickListener(clickListener);
viewHolder.button6.setOnClickListener(clickListener);
viewHolder.button7.setOnClickListener(clickListener);
viewHolder.button8.setOnClickListener(clickListener);
viewHolder.button9.setOnClickListener(clickListener);
viewHolder.button1.setOnClickListener(clickListener);
viewHolder.button1.setTag(position);
viewHolder.button2.setTag(position);
viewHolder.button3.setTag(position);
viewHolder.button4.setTag(position);
viewHolder.button5.setTag(position);
viewHolder.button6.setTag(position);
viewHolder.button7.setTag(position);
viewHolder.button8.setTag(position);
viewHolder.button9.setTag(position);
viewHolder.button1.setTag(position);
buttons.add(viewHolder.button1);
buttons.add(viewHolder.button2);
buttons.add(viewHolder.button3);
buttons.add(viewHolder.button4);
buttons.add(viewHolder.button5);
buttons.add(viewHolder.button6);
buttons.add(viewHolder.button7);
buttons.add(viewHolder.button8);
buttons.add(viewHolder.button9);
buttons.add(viewHolder.button10);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.mQuestionTextView.setText(questionHint.get(position).getValue0());
viewHolder.mHintTextView.setText(questionHint.get(position).getValue1());
Votes item = getItem(position);
int count = 0;
double score = 0;
for(int i = 0; i<item.getAll().size(); i++){
score += (i+1) * item.getAll().get(i);
count +=item.getAll().get(i);
}
if(count>0){
score = score/count;
}
if(score==0){
score = 10;
}
// double diff = (10-Math.round(score));
colorButton(Math.round(score), viewHolder);
// colorButton((int) score);
// for (int j = 9; j >= diff; j--) {
// Button button = buttons.get(j);
// button.setBackgroundColor(Color.WHITE);
// button.setTextColor(Color.BLACK);
// }
}
return convertView;
}
private void colorButton(long givenMark, ViewHolder viewHolder){
for(int i=0; i<buttons.size();i++){
buttons.get(i).setBackgroundColor(Color.WHITE);
}
for (int j = 0; j <= givenMark; j++) {
Button button = buttons.get(j);
button.setBackgroundColor(Color.parseColor(colors.get(j)));
}
}
private static class ViewHolder {
TextView mQuestionTextView;
TextView mHintTextView;
Button button1;
Button button2;
Button button3;
Button button4;
Button button5;
Button button6;
Button button7;
Button button8;
Button button9;
Button button10;
}
}
It looks like this:
So, when I press button 3, all colors beyond 3, must become white. Or when I press button 9, all buttons before it must have its colors, and buttons in fron of it must be white. But this does not happen, and there is no error.
Thank you for any help.
Isn't that rating bar?
OnClickListener is wrong, I meant not the right listener, you got the idea wrong. What's the enclosing View?
This is a sample try code. I am adding checkbox and textview in the table row by using loop. Everything is working fine except that whenever I am trying to take out(checkBox, Textview) from another method, I am not able to get it. I don't know how to solve this. I tried setId but I couldn't get the Id.
protected void onCreate(Bundle savedInstanceState) {
TableLayout tl = (TableLayout)findViewById(R.id.tableLayout1);
TableRow[] row = new TableRow[5];
TextView tv[] = new TextView[5];
CheckBox[] cb = new CheckBox[5];
Button clickTestRow;
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
for(int j = 0; j < 5; j ++){
row[j] = new TableRow(this);
tl.addView(row[j]);
tv[j] = new TextView(this);
cb[j] = new CheckBox(this);
tv[j].setText("This is text");
row[j].addView(cb[j]);
row[j].addView(tv[j]);
if(j == 0)
cb[j].setChecked(true);
}
clickTestRow = (Button) findViewById(R.id.clickTestRow);
clickTestRow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
TableLayout tlid = (TableLayout) findViewById(R.id.tableLayout1);
for(int i = 0; i < 5; i ++){
if(cb[i].isChecked()){
tlid.removeView(row[i]);
}
}
}
});
This is untested, but try this for now.
Key points here are
Fields for your views
Call setContentView before using findViewById
final variables for those that you are trying to use within an anonymous class (the onClickListener)
public class MainActivity extends Activity {
private TableLayout tl;
private Button clickTestRow;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tl = (TableLayout)findViewById(R.id.tableLayout1);
clickTestRow = (Button) findViewById(R.id.clickTestRow);
final TableRow[] row = new TableRow[5];
final TextView tv[] = new TextView[5];
final CheckBox[] cb = new CheckBox[5];
for(int j = 0; j < 5; j ++){
row[j] = new TableRow(this);
tl.addView(row[j]);
tv[j] = new TextView(this);
cb[j] = new CheckBox(this);
tv[j].setText("This is text");
row[j].addView(cb[j]);
row[j].addView(tv[j]);
}
cb[0].setChecked(true);
clickTestRow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
for(int i = 0; i < 5; i ++){
if(cb[i].isChecked()){
tl.removeView(row[i]);
}
}
}
});
}
}
I have an Activity that has a ScrollView of 125 buttons. The 125 buttons are Levels in my game that slowly get unlocked (think of Candy Crush Saga). Right now if the user is on the level, let's say, 88 of 125 then the user has to manually scroll all the way down to button 88.
My question is, how would I make it so that when the Activity loads, it automatically scrolls down and centers the ScrollView on a certain button?
Below is my code of how the buttons are created and populated programmatically.
ScrollView scrollView;
#Override
public void onCreate(Bundle savedInstanceState) {
LinearLayout lay = (LinearLayout)findViewById(R.id.linearlayout);
for(int i = 0; i < 125; i++) {
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, 0);
params.weight = 1;
params.gravity = Gravity.CENTER;
if(i == 0) {
TextView textview = new TextView(this);
textview.setLayoutParams(params);
textview.setTextSize(15);
textview.setText(c.getResources().getString(R.string.l1to5));
TextView textview2 = new TextView(this);
textview2.setLayoutParams(params);
textview.setTextSize(15);
textview2.setText(c.getResources().getString(R.string.goal100));
TextView textview3 = new TextView(this);
textview3.setLayoutParams(params);
textview.setTextSize(15);
textview3.setText(c.getResources().getString(R.string.catRandom));
if((getResources().getConfiguration().screenLayout &
Configuration.SCREENLAYOUT_SIZE_MASK) ==
Configuration.SCREENLAYOUT_SIZE_LARGE) {
textview.setTextSize(22);
textview2.setTextSize(22);
textview3.setTextSize(22);
} else if((getResources().getConfiguration().screenLayout &
Configuration.SCREENLAYOUT_SIZE_MASK) ==
Configuration.SCREENLAYOUT_SIZE_XLARGE) {
textview.setTextSize(22);
textview2.setTextSize(22);
textview3.setTextSize(22);
}
lay.addView(textview);
lay.addView(textview2);
lay.addView(textview3);
View ruler = new View(this);
ruler.setBackgroundColor(0xFFC2BEBF);
lay.addView(ruler, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 2));
}
if(i == 5) {
// ....
}
Button button = new Button(this);
int _id = getResources().getIdentifier("b" + (i + 1), "id", this.getPackageName());
button.setTag(_id);
button.setLayoutParams(params);
if((getResources().getConfiguration().screenLayout &
Configuration.SCREENLAYOUT_SIZE_MASK) ==
Configuration.SCREENLAYOUT_SIZE_LARGE) {
button.setTextSize(22);
} else if((getResources().getConfiguration().screenLayout &
Configuration.SCREENLAYOUT_SIZE_MASK) ==
Configuration.SCREENLAYOUT_SIZE_XLARGE) {
button.setTextSize(22);
}
button.setText("Level " + (i + 1));
final int x = i + 1;
button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
singleton.setLevelJustPlayed(x);
// ...
} else {
// ...
Intent intent = new Intent(Levels.this, Categories.class);
startActivity(intent);
}
}
});
lay.addView(button);
if(singleton.getLevel() >= (i + 1)) {
button.setEnabled(true);
} else {
button.setEnabled(false);
}
}
// end the onCreate() method
try
yourScrollView.scrollTo(0, (int) button.getY());
For Kotlin user
your_scrollview.post( { your_scrollview.scrollTo(0, your_view_inside_SV.getY().toInt()) })