Android table row onClickListener - java

I am having some problems when trying to trigger events on table layout in Android. These are the codes I used to populate the table layout dynamically:
private void BuildTable() {
try {
DatabaseAdapter mDbHelper = new DatabaseAdapter(Category.this);
mDbHelper.open();
CategoryController cc = new CategoryController(mDbHelper.open());
Cursor mCur = mDb.rawQuery(cc.getAllCat(), null);
if (mCur.getCount() != 0) {
if (mCur.moveToFirst()) {
// Setting table header
TableRow row = new TableRow(this);
row.setLayoutParams(new TableLayout.LayoutParams(
TableLayout.LayoutParams.MATCH_PARENT,
TableLayout.LayoutParams.WRAP_CONTENT));
do {
int cols = mCur.getColumnCount();
row = new TableRow(this);
for (int j = 1; j < cols; j++) {
// Dynamically load data fetch from database
// into table layout
TextView tv = new TextView(this);
tv.setLayoutParams(new TableRow.LayoutParams(
TableRow.LayoutParams.MATCH_PARENT,
TableRow.LayoutParams.WRAP_CONTENT));
tv.setPadding(5, 5, 10, 5);
tv.setGravity(Gravity.LEFT);
tv.setText(mCur.getString(j));
row.addView(tv);
row.setId(j);
}
row.setClickable(true);
row.setOnClickListener(tablerowOnClickListener);
table_layout.addView(row);
} while (mCur.moveToNext());
}
}
} catch (SQLException mSQLException) {
throw mSQLException;
}
}
And here is my table row onClickListener:
private OnClickListener tablerowOnClickListener = new OnClickListener() {
public void onClick(View v) {
//Highlight selected row
v.setBackgroundColor(getResources().getColor(android.R.color.holo_red_light));
final int k = v.getId();
Toast.makeText(Category.this, Integer.toString(k),
Toast.LENGTH_SHORT).show();
}
};
My problem is when I highlighted certain row and I select another row again, the previous highlighted row remains the same highlighted background color. I wonder how to solve it?
Thanks in advance.

Provided table_layout is in the same scope as tablerowOnClickListener, change the Listener as follows:
private OnClickListener tablerowOnClickListener = new OnClickListener()
{
public void onClick(View v)
{
//Highlight selected row
for (int i = 0; i < table_layout.getChildCount(); i++)
{
View row = table_layout.getChildAt(i);
if (row == v)
{
row.setBackgroundColor(getResources().getColor(android.R.color.holo_red_light));
}
else
{
//Change this to your normal background color.
row.setBackgroundColor(getResources().getColor(android.R.color.transparent));
}
}
//...
}
};

Related

How to populate TableLayout programatically

I have literally tried most solutions on adding rows to a blank TableLayout from code; I still get a blank screen.
Below is the code:
public void updateTable(){
bodyTable.removeViews(ROW_OFFSET, bodyTable.getChildCount() - ROW_OFFSET);
for(int row = 0; row < adapter.getRowCount(); row++){
final int rrow = getRealRowOf(row);
TableRow bodyRow = new TableRow(context);
padColStart(bodyTable, bodyRow);
for(int col = 0; col < adapter.getColumnCount(); col++){
final int rcol = getRealColOf(col);
final boolean expandCol = adapter.isColumnExpandable(col);
bodyTable.setColumnStretchable(rcol, expandCol);
TextView bodyText;
if(adapter.isCellEditable(row, col)){
bodyText = new EditText(context);
bodyText.setRawInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_NORMAL);
}else
bodyText = new TextView(context);
setBodyText(bodyText, adapter.getValueAt(row, col).toString());
bodyText.setLayoutParams(getRowLayoutParams());
bodyRow.addView(bodyText/*, rcol*/);
addColumnLine(bodyTable, bodyRow, rcol);
}
bodyRow.setLayoutParams(getRowLayoutParams());
bodyTable.addView(bodyRow/*, rrow*/, getTableLayoutParams());
addRowLine(bodyTable, rrow);
}
}
Below adds vertical cell lines:
private void addColumnLine(TableLayout bodyTable, TableRow bodyRow, int rcol){
for(int col_pad = 1; col_pad < COLUMN_STEP; col_pad++){
View view = getColumnLine();
view.setLayoutParams(getColumnLineLayout());
bodyTable.setColumnStretchable(rcol + col_pad, false);
bodyRow.addView(view/* rcol + col_pad,*/);
}
}
private View getColumnLine(){
View colLine = new View(context);
colLine.setBackgroundColor(0x000000);
return colLine;
}
LayoutParams for vertical cell lines
private TableRow.LayoutParams getColumnLineLayout(){
return new TableRow.LayoutParams(getPxFromDp(2), TableRow.LayoutParams.MATCH_PARENT);
}
below adds horizontal row lines:
private void addRowLine(TableLayout bodyTable, int rrow){
for(int row_pad = 1; row_pad < ROW_STEP; row_pad++){
View view = getRowLine();
view.setLayoutParams(getRowLineLayout());
bodyTable.addView(view/* rrow + row_pad,*/, getTableLayoutParams());
}
}
private View getRowLine(){
View rowLine = new View(context);
rowLine.setBackgroundColor(0x000000);
return rowLine;
}
LayoutParams for row lines:
private TableRow.LayoutParams getRowLineLayout(){
return new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT, getPxFromDp(2));
}
LayoutParams to add to TableRow:
private TableRow.LayoutParams getRowLayoutParams(){
return new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.WRAP_CONTENT);
}
LayoutParams to add to TableLayout:
private TableLayout.LayoutParams getTableLayoutParams(){
return new TableLayout.LayoutParams(TableLayout.LayoutParams.MATCH_PARENT, TableLayout.LayoutParams.WRAP_CONTENT);
}

Can not trigger on Click

Can not trigger on Click listener
I tried
setClickable(true);
but still not working
minimum sdk is 15
the code doesn't have xml file, i need to fix it programmatically
the complete code:
public class MainActivity extends AppCompatActivity {
private static char CHAR = 'a';
private Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
LinearLayout layout = new LinearLayout(this);
layout.setOrientation(LinearLayout.VERTICAL);
int rowNo = ROWS;
int colNo = (screenWidth().widthPixels * ROWS /screenWidth().heightPixels) ;
for (int i = 0; i < 5; i++) {
LinearLayout row = new LinearLayout(this);
row.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, 1.0f));
for (int j = 0; j < 5; j++) {
String txt = String.valueOf(CHAR);
Cell cell = new Cell(this, txt, 50, 50);
cell.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
System.out.println("value is " + txt);
}
});
row.addView(cell);
CHAR += 1;
}
layout.addView(row);
}
setContentView(layout);
}
private class Cell extends LinearLayout{
public Cell(Context context, final String value, int width, int height) {
super(context);
LinearLayout.LayoutParams cellParams = new LinearLayout.LayoutParams(width, height);
setLayoutParams(cellParams);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
setBackground(getGradientDrawable());
}else{
setBackgroundDrawable(getGradientDrawable());
}
}
private GradientDrawable getGradientDrawable() {
GradientDrawable shape = new GradientDrawable();
shape.setShape(GradientDrawable.RECTANGLE);
shape.setColor(Color.TRANSPARENT);
shape.setStroke(2, Color.BLACK);
return shape;
}
}
}
so, why and how to fix it.
at clicking the associated text will be printed
Try onClickListener inside your loop
Cell cell = new Cell(this, txt, 50, 50);
cell.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
System.out.println("value is " + value);
}
});

Android crash when trying to get a view by tag

so when I try to get an EditText view by the tag I assigned to it earlier, the app just crashes(and I'm not sure where to get the error log, the console is empty).
The code:
`public class StartActivity extends AppCompatActivity {
private ListView listPeopleDisplay;
private EditText textCurrentName;
private ArrayAdapter<String> adapter;
private LinearLayout roleCheckboxes;
private int peopleSize;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_starting);
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1);
listPeopleDisplay = (ListView) findViewById(R.id.listPlayers);
listPeopleDisplay.setAdapter(adapter);
textCurrentName = (EditText) findViewById(R.id.editTextPlayers);
peopleSize = 0;
}
public void sendMessage(View view) {
if (view.getId() == R.id.buttonAddPlayer) {
adapter.add(textCurrentName.getText().toString());
textCurrentName.setText("");
++peopleSize;
} else if (view.getId() == R.id.buttonDoneAddingPlayers) {
String[] config = new String[peopleSize];
for (int i = 0; i < peopleSize; i++) {
config[i] = adapter.getItem(i);
}
Configuration.setPeople(config);
setContentView(R.layout.layout_roles);
roleCheckboxes = (LinearLayout) findViewById(R.id.layoutRoles);
for (int i = 0; i < Roles.values().length; i++) {
if (Roles.values()[i] == Roles.MAFIA ||
Roles.values()[i] == Roles.YAKUZA ||
Roles.values()[i] == Roles.CIVILIAN) {
continue;
}
CheckBox cb = new CheckBox(this);
cb.setText(Roles.values()[i].toString());
cb.setChecked(false);
cb.setTag(Roles.values()[i]);
roleCheckboxes.addView(cb);
}
EditText mob = new EditText(this);
mob.setHint("Mafia count");
mob.setInputType(InputType.TYPE_CLASS_NUMBER);
mob.setTag(Roles.MAFIA);
roleCheckboxes.addView(mob);
mob = new EditText(this);
mob.setInputType(InputType.TYPE_CLASS_NUMBER);
mob.setHint("Yakuza count");
mob.setTag(Roles.YAKUZA);
roleCheckboxes.addView(mob);
mob = new EditText(this);
mob.setInputType(InputType.TYPE_CLASS_NUMBER);
mob.setHint("Civilian count");
mob.setTag(Roles.CIVILIAN);
roleCheckboxes.addView(mob);
} else {
int count = 0;
CheckBox civ = (CheckBox)roleCheckboxes.findViewWithTag(Roles.CIVILIAN);
<!-- the rest is irrelevant-->`
It crashes on the last line.
roleCheckboxes is set in the else if (view.getId() == R.id.buttonDoneAddingPlayers) statement, and you are trying to use it in the third else statement which is out of it's initializing scope.You should have the initialization:
setContentView(R.layout.layout_roles);
roleCheckboxes = (LinearLayout) findViewById(R.id.layoutRoles);
and the usage
CheckBox civ = (CheckBox)roleCheckboxes.findViewWithTag(Roles.CIVILIAN);
in the same scope ( for example in teh same if statement) or you should initialize the roleCheckboxes in the onCreate method
As logcat showed, I was trying to cast a CheckBox to an EditText. I am dumb. Sorry for your time.

onClickListener onclicklistener Android Java programming

When i click on the images it doesnt change the display textview, where did i go wrong?
**List<ImageView> fields = new ArrayList<ImageView>();
for(int i = 0; i < 64; i++) {
try{
id = R.id.class.getField("square" + (i+1)).getInt(0);
views.add((ImageView)findViewById(id));
((View) fields).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View fields) {
for(int i=0; i < 64; i++)
{
display = (TextView) findViewById(R.id.textView1);
display.setText("square" + i);
}
}
});
}
catch(Exception e){}
}**
}
}
It looks like you're adding the onClick listener to the ArrayList of views, not the image you added. Change
((View) fields).setOnClickListener
to
findViewById(id).setOnClickListener

android : checkbox problem?

I'm trying to select all the checkbox in list. Why am getting particular checkbox only true. Code is : -
ListView listview = (ListView)findViewById(R.id.listview1);
for(int i=0; i < listview.getChildCount(); i++)
{
AbsoluteLayout itemLayout = (AbsoluteLayout)listview.getChildAt(i);
CheckBox cb = (CheckBox)itemLayout.findViewById(R.id.checkBox1);
if(cb.isChecked())
{
cb.setChecked(false);
}
else
{
cb.setChecked(true);
}
}
Thanks in Advance.
Not sure I understand the question fully..
But I belive:
CheckBox cb = (CheckBox)itemLayout.findViewById(R.id.checkBox1);
will always return the same CheckBox (the one with id checkBox1), even if you have multiple checkboxes in your list.
Try:
for(int i=0; i < listview.getChildCount(); i++)
{
CheckBox cb = (CheckBox)listview.getChildAt(i).findViewById(R.id.checkBox1); //if the child views are properly populated in each row item then on this particular positon ChBox will be found and instantiated
if(cb.isChecked())
{
cb.setChecked(false);
}
else
{
cb.setChecked(true);
}
}
You Can use this with two buttons like selectall & unselectall
public void checkallbtn_Click(View view)
{
ListView lv = (ListView)findViewById(R.id.backuplist);
CheckBox cb;
try
{
for(int i=0;i<lv.getCount();i++)
{
cb = (CheckBox)lv.getChildAt(i).findViewById(R.id.checkBox1);
if(!cb.isChecked())
{
cb.setChecked(true);
}
}
}catch(Exception e) {e.printStackTrace();}
}
public void uncheckallbtn_Click(View view)
{
ListView lv = (ListView)findViewById(R.id.backuplist);
try
{
for(int i=0;i<lv.getCount();i++)
{
CheckBox cb = (CheckBox)lv.getChildAt(i).findViewById(R.id.checkBox1);
if(cb.isChecked())
{
cb.setChecked(false);
}
}
}catch(Exception e)
{
e.printStackTrace();
}
}
Hope this will help you.

Categories