the_big_blackbox the_big_blackbox - 1 year ago 84
Android Question

2 layouts and a popupWindow

please can someone assist, I am fairly new to android development.

I have 1 button on my mainActivity that launches a popupwindow. The popupwindow is in a separate resource layout file - and consists of a tablelayout, each button within this table layout has an image and text. The images are resized.

The popupWindow has a transparent background to allow the user to still see what is going on the background activity - mainActivity.

I have the following code however when I run it does not launch the app.

package mobi.blessd.user.blessd;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.PopupWindow;
import android.widget.TableLayout;
import android.widget.TableRow;

public class MainActivity extends AppCompatActivity {

protected void onCreate(Bundle savedInstanceState) {

final Button btn_show = (Button) findViewById(;
if (btn_show != null) {
btn_show.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {

LayoutInflater layoutInflater = (LayoutInflater) getBaseContext().getSystemService(LAYOUT_INFLATER_SERVICE);
View layout = layoutInflater.inflate(R.layout.activity_alert_dialog, null);
final PopupWindow popup = new PopupWindow(layout, LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);

popup.showAsDropDown(btn_show, 20, -50);

//Resize elements in the table
TableLayout layout = (TableLayout) findViewById(;
for (int i = 0; i < layout.getChildCount(); i++) {

View child = layout.getChildAt(i);

if (child instanceof TableRow) {
TableRow row = (TableRow) child;

for (int x = 0; x < row.getChildCount(); x++) {
Button button = (Button) row.getChildAt(x);
Drawable drawable = (Drawable) button.getCompoundDrawables()[1];

drawable.setBounds(0, 0, (int) (drawable.getIntrinsicWidth() * 0.5),
(int) (drawable.getIntrinsicHeight() * 0.5));

float scaleWidth = 20;
float scaleHeight = 20;
ScaleDrawable sd = new ScaleDrawable(drawable, 0, scaleWidth, scaleHeight);

button.setCompoundDrawables(null, sd.getDrawable(), null, null);


The error I receive nullpointerexception caused by layout.getChildCount() at the following line: for (int i = 0; i < layout.getChildCount(); i++)

Answer Source

These lines:

//Resize elements in the table
TableLayout layout = (TableLayout) findViewById(;
for (int i = 0; i < layout.getChildCount(); i++) {

should be inside the onclick method not outside

and you need to reference the TableLayout from the popup layout

change this line:

TableLayout layout = (TableLayout) findViewById(;


TableLayout tbLayout = (TableLayout) layout.findViewById(;

where layout is

View layout = layoutInflater.inflate(R.layout.activity_alert_dialog, null);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download