private void adjustBarSize() {
    /*
    RelativeLayout backlayout = (RelativeLayout)adjustSizeview.findViewById(R.id.undergroundBar);
    RelativeLayout.LayoutParams params =(RelativeLayout.LayoutParams) backlayout.getLayoutParams();
      	params.height = (int)(screenHeight*0.1);
      	backlayout.setLayoutParams(params);
      	*/

    sure = (Button) adjustSizeview.findViewById(R.id.sure);
    cancel = (Button) adjustSizeview.findViewById(R.id.cancel);

    sure.setWidth((int) (screenWidth * 0.5));
    //		sure.setHeight((int)(screenHeight*0.1));
    cancel.setWidth((int) (screenWidth * 0.5));
    //		cancel.setHeight((int)(screenHeight*0.1));
  }
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    DBHelper dbHelper = DBHelper.getInstance(getApplicationContext());

    setContentView(R.layout.activity_buoc);

    LinearLayout gardenLayout = (LinearLayout) findViewById(R.id.gardenLayoutLinear);

    // create buttons to put inside linear layout
    int counter = 1;
    for (int rows = 0; rows < 10; rows++) {
      LinearLayout currentLinear = new LinearLayout(this);
      currentLinear.setOrientation(LinearLayout.HORIZONTAL);

      for (int cols = 0; cols < 3; cols++) {
        final Button currButton = new Button(this);
        LinearLayout.LayoutParams param;
        param =
            new LinearLayout.LayoutParams(
                Toolbar.LayoutParams.WRAP_CONTENT, Toolbar.LayoutParams.WRAP_CONTENT, 1.0f);
        currButton.setLayoutParams(param);
        currButton.setWidth(50);
        currButton.setHeight(125);
        currButton.setGravity(Gravity.CENTER);
        currButton.setId(counter);
        currButton.setOnClickListener(
            new View.OnClickListener() {
              @Override
              public void onClick(View v) {
                redirectToBedOptions(currButton);
              }
            });
        currButton.setText("" + currButton.getId());
        currentLinear.addView(currButton);
        counter++;
      }
      gardenLayout.addView(currentLinear);
    }

    // Grab the first five garden notes and display them in the notes section
    // for now we will mock up data to show.
    final ListView gardenNotePreviewList = (ListView) findViewById(R.id.gardenNotePreviewList);
    Note mock_up_data[] = null;
    try {
      mock_up_data = new Note[5];
      mock_up_data[0] = new Note("Warning signs around garden", "");
      mock_up_data[1] = new Note("Cleaned around garden.", "");
      mock_up_data[2] = new Note("Created new Garden Worksheet.", "");
      mock_up_data[3] = new Note("subject 4", "");
      mock_up_data[4] = new Note("subject 5", "");

    } catch (Exception ex) {
      ex.printStackTrace();
    }

    GardenLayoutNotePreviewListAdapter adapter =
        new GardenLayoutNotePreviewListAdapter(this, R.layout.custom_garden_note, mock_up_data);
    gardenNotePreviewList.setAdapter(adapter);
  }
  private void initGameBoard() {

    mTableLayout = (TableLayout) findViewById(R.id.table_layout);
    mTableLayout.setStretchAllColumns(true);
    // mTableLayout.setBackgroundResource(R.color.blue);

    int counter = 1;
    for (int row = 0; row < 3; row++) {
      TableRow tableRow = new TableRow(this);
      for (int col = 0; col < 3; col++) {

        Button button = new Button(this);

        button.setTag(counter);

        // button.setText(row+","+col+"\nTag:"+button.getTag());

        button.setOnClickListener(this);
        button.setWidth(300);
        button.setHeight(300);
        button.setTextSize(40);

        tableRow.addView(button);

        counter++;
      }

      mTableLayout.addView(tableRow, new TableLayout.LayoutParams(FP, WC));
    }
  }
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    // TODO 自動生成されたメソッド・スタブ
    super.onCreate(savedInstanceState);
    setContentView(R.layout.private_status);
    linear = (LinearLayout) findViewById(R.id.linear);
    Bundle list;
    list = getIntent().getExtras();
    Name = (TextView) findViewById(R.id.name);
    color4 = getResources().getColor(R.color.color4);

    if (list != null) {
      name = list.getString("name");
      status = list.getInt("status");
      position = list.getInt("position");
    }
    linear.setBackgroundColor(color4);
    Name.setText(name);

    Display display = getWindowManager().getDefaultDisplay();
    Point p = new Point();
    display.getSize(p);

    Button button1 = (Button) findViewById(R.id.lab);
    button1.setOnClickListener(this);
    button1.setWidth(p.x / 3);
    button1.setHeight(p.y / 4);
    Button button2 = (Button) findViewById(R.id.campus);
    button2.setOnClickListener(this);
    button2.setWidth(p.x / 3);
    button2.setHeight(p.y / 4);
    Button button3 = (Button) findViewById(R.id.home);
    button3.setOnClickListener(this);
    button3.setWidth(p.x / 3);
    button3.setHeight(p.y / 4);
    Button button4 = (Button) findViewById(R.id.back);
    button4.setOnClickListener(this);
    button4.setWidth(p.x / 3);
    button4.setHeight(p.y / 4);
    Button button5 = (Button) findViewById(R.id.Contact);
    button5.setOnClickListener(this);
    button5.setWidth(p.x / 3);
    button5.setHeight(p.y / 4);
    ImageView imageView = (ImageView) findViewById(R.id.imageview1);
    // imageView.setImageBitmap(CustomAdapter.circle(position));
  }
  private void set_sizes() {
    int button_width =
        (((WindowManager) getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay().getWidth())
            / 3;
    int height =
        ((WindowManager) getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay().getHeight();

    LinearLayout ll1 = (LinearLayout) findViewById(R.id.LL_buttons_first);
    ll1.setMinimumHeight(height / 3);
    LinearLayout ll2 = (LinearLayout) findViewById(R.id.LL_buttons_second);
    ll2.setMinimumHeight(height / 3);
    button_rewind.setWidth(button_width);
    button_foward.setWidth(button_width);
    button_stop.setWidth(button_width);
    button_mute.setWidth(button_width);
    button_quit.setWidth(button_width);
    button_fullscreen.setWidth(button_width);
    button_playpause.setWidth(button_width);
  }
 void createButtons() {
   for (int i = 0; i < 9; i++) {
     Button a = new Button(this);
     a.setWidth(50);
     a.setHeight(20);
     a.setText("9");
     a.setTag(i);
     a.setOnClickListener(this);
     buttons.add(a);
   }
 }
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    LinearLayout layoutMain = new LinearLayout(this);
    layoutMain.setOrientation(LinearLayout.VERTICAL);
    layoutMain.setBackgroundColor(Color.CYAN);

    LinearLayout layoutTitle = new LinearLayout(this);
    layoutTitle.setOrientation(LinearLayout.VERTICAL);
    layoutTitle.setGravity(Gravity.TOP);
    layoutMain.addView(layoutTitle);

    TextView heading = new TextView(this);
    heading.setText("DETECTING INPUT EVENTS \n (Click Or Long Press)");
    heading.setHeight(100);
    heading.setGravity(Gravity.TOP | Gravity.CENTER);
    heading.setBackgroundColor(Color.YELLOW);
    heading.setTextSize(TypedValue.COMPLEX_UNIT_SP, 25);
    heading.setTypeface(Typeface.SANS_SERIF, Typeface.BOLD);
    layoutTitle.addView(heading);

    LinearLayout layoutBody = new LinearLayout(this);
    layoutBody.setOrientation(LinearLayout.VERTICAL);
    layoutBody.setGravity(Gravity.CENTER_HORIZONTAL);
    layoutMain.addView(layoutBody);

    Button btn1 = new Button(this);
    btn1.setWidth(10);
    btn1.setGravity(Gravity.CENTER);
    btn1.setTextSize(TypedValue.COMPLEX_UNIT_SP, 25);
    btn1.setTypeface(Typeface.SANS_SERIF, Typeface.BOLD);
    btn1.setText("Click Me With Any Style");
    layoutBody.addView(btn1);

    btn1.setOnClickListener(this);
    btn1.setOnLongClickListener(
        new View.OnLongClickListener() {
          public boolean onLongClick(View v) {
            result.setText("You long pressed the button !!");
            return true;
          }
        });

    result = new TextView(this);
    result.setHeight(200);
    result.setGravity(Gravity.CENTER);
    result.setTextSize(TypedValue.COMPLEX_UNIT_SP, 20);
    result.setTypeface(Typeface.SANS_SERIF, Typeface.BOLD);
    layoutBody.addView(result);

    setContentView(layoutMain);
  }
Exemple #8
0
 private void initWidgets() {
   // TODO Auto-generated method stub
   this.add = (Button) this.findViewById(R.id.add);
   add.setOnClickListener(this);
   this.info = (TextView) this.findViewById(R.id.info);
   this.beforeone = (Button) this.findViewById(R.id.beforeone);
   beforeone.setOnClickListener(this);
   this.nextone = (Button) this.findViewById(R.id.nextone);
   nextone.setOnClickListener(this);
   this.spelling = (TextView) this.findViewById(R.id.spelling);
   Typeface tf = Typeface.createFromAsset(getAssets(), "fonts/SEGOEUI.TTF");
   info.setTypeface(tf);
   this.speak = (ImageButton) this.findViewById(R.id.ImageButton01);
   tts = new TextToSpeech(this, ttsInitListener);
   speak.setOnClickListener(this);
   DisplayMetrics dm = new DisplayMetrics();
   dm = getApplicationContext().getResources().getDisplayMetrics();
   int screenWidth = dm.widthPixels;
   add.setWidth(screenWidth / 3);
   beforeone.setWidth(screenWidth / 3);
   nextone.setWidth(screenWidth / 3);
 }
 public void setTitleAndRightImageButton(
     CharSequence title,
     int backid,
     onRightImageButtonClickListener onRightImageButtonClickListener) {
   setDefaultTitle(title);
   mLayoutRightContainer.setVisibility(View.VISIBLE);
   if (mRightImageButton != null && backid > 0) {
     mRightImageButton.setWidth(PixelUtil.dp2px(30));
     mRightImageButton.setHeight(PixelUtil.dp2px(30));
     mRightImageButton.setTextColor(getResources().getColor(R.color.transparent));
     mRightImageButton.setBackgroundResource(backid);
     setOnRightImageButtonClickListener(onRightImageButtonClickListener);
   }
 }
 public void setTitleAndRightButton(
     CharSequence title,
     int backid,
     String text,
     onRightImageButtonClickListener onRightImageButtonClickListener) {
   setDefaultTitle(title);
   mLayoutRightContainer.setVisibility(View.VISIBLE);
   if (mRightImageButton != null && backid > 0) {
     mRightImageButton.setWidth(PixelUtil.dp2px(45));
     mRightImageButton.setHeight(PixelUtil.dp2px(40));
     mRightImageButton.setBackgroundResource(backid);
     mRightImageButton.setText(text);
     setOnRightImageButtonClickListener(onRightImageButtonClickListener);
   }
 }
 void testPositioning() {
   for (int i = 0; i < 9; i++) {
     Button a = new Button(this);
     a.setWidth(50);
     a.setHeight(20);
     a.setText("9");
     buttons.add(a);
   }
   firstTop.addView(buttons.get(0));
   secondTop.addView(buttons.get(1));
   thirdTop.addView(buttons.get(2));
   firstBottom.addView(buttons.get(3));
   secondBottom.addView(buttons.get(4));
   thirdBottom.addView(buttons.get(5));
   firstCenter.addView(buttons.get(6));
   secondCenter.addView(buttons.get(7));
   thirdCenter.addView(buttons.get(8));
 }
 @Override
 public View getView(int position, View convertView, ViewGroup parent) {
   Button button;
   if (convertView == null) {
     button = new Button(ctx);
     button.setText("" + (data[position]));
   } else {
     button = (Button) convertView;
   }
   if (position >= levelMax) {
     button.setEnabled(false);
     button.setAlpha(0.5f);
   }
   button.setId(data[position]);
   button.setTextSize(diametr * 0.2f);
   button.setWidth(diametr);
   button.setHeight(diametr);
   if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
     button.setBackground(
         ctx.getApplicationContext().getResources().getDrawable(R.drawable.button_sm));
   }
   button.setOnClickListener(
       new View.OnClickListener() {
         @Override
         public void onClick(View v) {
           int lv = v.getId();
           Intent intent = new Intent(ctx, GameActivity.class);
           SharedPreferences spref = ctx.getSharedPreferences("MyPref", Context.MODE_PRIVATE);
           SharedPreferences.Editor ed = spref.edit();
           ed.putInt("Level", lv);
           ed.putBoolean("start", true);
           for (int i = 1; i <= 4; i++) {
             ed.putInt("figure" + i + "position", 0);
             ed.putInt("figure" + i + "rotation", 1);
           }
           ed.commit();
           ctx.startActivity(intent);
         }
       });
   return button;
 }
  public void customTitleBar(String text) {
    // set up custom title
    if (customTitleSupported) {
      Window window = getWindow();
      window.setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.titlebar_items);
      Button leftButton = (Button) findViewById(R.id.controlBackBtn);
      Button titleCenter = (Button) findViewById(R.id.titleCenter);

      Display display = getWindowManager().getDefaultDisplay();
      int width = display.getWidth(); // deprecated
      int oneBox = display.getWidth() / 10;
      int left = oneBox * 1; // 40
      int center = oneBox * 7; // 240
      int right = oneBox * 1; // 40

      // log.debug("Window width:"+width);
      // log.debug("text:"+text.length());

      // leftButton.setWidth(left+20);
      titleCenter.setWidth(center + 10);
      titleCenter.setText(text);
    }
  }
  /** @param context */
  public ChapterView(Context context, Book bok, BookViewController controller) {
    super(context);
    // TODO Auto-generated constructor stub
    mContext = context;
    this.book = bok;
    mBookViewController = controller;
    display = ((Activity) context).getWindowManager().getDefaultDisplay();
    setBackgroundColor(Color.WHITE);

    prefsManager = new PrefsManager(mContext);
    hasHistory = prefsManager.hashistory();

    int btnWidth = display.getWidth() / 2;

    layout = new LinearLayout(context);
    layout.setOrientation(LinearLayout.VERTICAL);
    layout.setGravity(Gravity.CENTER_HORIZONTAL);

    continuBtn = new Button(context);
    continuBtn.setId(0);
    continuBtn.setText("¼ÌÐøÉÏ´ÎÔĶÁ");
    continuBtn.setOnClickListener(this);
    continuBtn.setEnabled(hasHistory);
    layout.addView(continuBtn, LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);

    for (int i = 0; i < book.getFlatNavPoints().size(); i++) {
      NavPoint np = book.getFlatNavPoints().get(i);
      Button b = new Button(context);
      b.setId(i + 1);
      b.setText(np.getLabel());
      b.setWidth(btnWidth);
      b.setOnClickListener(this);
      layout.addView(b, LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
    }

    addView(layout);
  }
Exemple #15
0
 @Override
 public void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   requestWindowFeature(Window.FEATURE_NO_TITLE);
   try { // try to get matrix config
     String fname = "battleship";
     File file = getBaseContext().getFileStreamPath(fname);
     if (file.exists()) { // read from file
       DataInputStream in = new DataInputStream(openFileInput(fname));
       for (int i = 0; i < 10; i++) {
         for (int j = 0; j < 10; j++) {
           P1[i][j] = Integer.parseInt(in.readUTF());
         }
       }
       for (int i = 0; i < 10; i++) {
         for (int j = 0; j < 10; j++) {
           P2[i][j] = Integer.parseInt(in.readUTF());
         }
       }
       in.close();
     }
   } catch (IOException e) {
     Log.i("Data Input Sample", "I/O Error");
   }
   RelativeLayout hugelay = new RelativeLayout(this);
   ScrollView largelay = new ScrollView(this);
   largelay.setId(10000);
   TableLayout layout = new TableLayout(this);
   layout.setLayoutParams(new TableLayout.LayoutParams(300, 300));
   layout.setPadding(1, 1, 1, 1);
   int i, j;
   for (i = 0; i <= 9; i++) {
     TableRow tr = new TableRow(this);
     for (j = 0; j <= 9; j++) {
       ImageButton b = new ImageButton(this);
       if (P2[i][j] == 0) {
         b.setImageResource(R.drawable.water);
       } else if (P2[i][j] == 99) {
         b.setImageResource(R.drawable.explosion);
       } else if (P2[i][j] == 88) {
         b.setImageResource(R.drawable.x);
       } else {
         b.setImageResource(R.drawable.water2);
       }
       b.setId(i * 10 + j);
       b.setOnClickListener(this);
       tr.addView(b, 72, 72);
     } // for
     layout.addView(tr);
   } // for
   largelay.addView(layout);
   hugelay.setBackgroundResource(R.drawable.battleshipbg);
   Button btn = new Button(this);
   btn.setText("MY MAP");
   btn.setBackgroundResource(R.color.transparent);
   btn.setHeight(134);
   btn.setWidth(134);
   btn.setId(1000);
   btn.setOnClickListener(this);
   RelativeLayout.LayoutParams lp =
       new RelativeLayout.LayoutParams(
           RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
   lp.addRule(RelativeLayout.RIGHT_OF, largelay.getId());
   lp.addRule(RelativeLayout.CENTER_VERTICAL);
   hugelay.addView(largelay);
   hugelay.addView(btn, lp);
   super.setContentView(hugelay);
 } // ()
  private void GetAnswers(Integer _id) {

    openDatabaseConnection();

    String WhereStatement = "QUESTIONITEM " + "= " + String.valueOf(_id);
    String[] Columns = {"CORRECT", "ANSWERTEXT", "REASON"};

    Cursor c = myDbHelper.query("ANSWERS", Columns, WhereStatement, null, null, null, null);

    if (c.getCount() > 0) {

      c.moveToFirst();

      List<Answer> list = new ArrayList<Answer>();
      CorrectAnswerList = new ArrayList<Answer>();
      CorrectAnswerInHTMLList = new ArrayList<String>();
      do {
        Answer ans = new Answer();
        ans.set_Correct(c.getInt(c.getColumnIndex("CORRECT")));
        ans.set_AnswerText(c.getString(c.getColumnIndex("ANSWERTEXT")));
        ans.set_Reason(c.getString(c.getColumnIndex("REASON")));
        list.add(ans);
        // if the answer is correct keep the string in HTML
        if (ans.get_Correct() == 1) {
          String CorrectAnswerInHTML = ans.get_AnswerText();
          CorrectAnswerReasonInHTML = ans.get_Reason();
          CorrectAnswerList.add(ans); // Collection of correct answers
          CorrectAnswerInHTMLList.add(CorrectAnswerInHTML);
          CorrectAnswerInHTMLListCounter++;
        }
      } while (c.moveToNext());

      c.close();
      myDbHelper.close();

      // Add the number of Answer to the CorrectAnswerListCounter
      CorrectAnswerListCounter = CorrectAnswerList.size();

      // Initialize button array
      ButtonArray = new ArrayList<Button>();

      for (int current = 0; current < list.size(); current++) {
        Answer ThisAns = list.get(current);
        // Create a table row
        TableRow tr = new TableRow(this);
        tr.setId(1000 + current);
        tr.setGravity(Gravity.CENTER);

        tr.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));

        /*TextView Tv = new TextView(this);
        Tv.setId(1000+current);
        Tv.setText(Html.fromHtml(ThisAns.get_AnswerText()));
        Tv.setTextColor(Color.WHITE);

           tr.addView(Tv);

           Table.addView(tr);*/

        // Configure each button and add to row and then add row to table
        Button bt = new Button(this);
        bt.setId(1000 + current);
        bt.setText(Html.fromHtml(ThisAns.get_AnswerText()));
        bt.setTextColor(Color.BLACK);
        bt.setGravity(Gravity.CENTER);
        bt.setWidth(420);
        bt.setHeight(LayoutParams.WRAP_CONTENT);
        bt.setTextSize(12);
        // Add the correct answer to the button
        bt.setTag(ThisAns.get_Correct());

        bt.setOnClickListener(this);
        // Add button the button array
        ButtonArray.add(bt);

        tr.addView(bt);

        Table.addView(tr);
      }
    }
  }
    private void addNavButtons(ViewGroup vg) {

      addSpace(vg, 6, 6);

      LinearLayout.LayoutParams lpChild1 =
          new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, 1);
      LinearLayout.LayoutParams lpWrap10 =
          new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, 10);

      Context context = vg.getContext();
      LinearLayout hl = new LinearLayout(context);
      hl.setLayoutParams(lpWrap10);
      hl.setOrientation(LinearLayout.HORIZONTAL);

      // zoom out button
      Button bZoomOut = new Button(context);
      bZoomOut.setLayoutParams(lpChild1);
      bZoomOut.setText("-");
      bZoomOut.setWidth(40);
      bZoomOut.setOnClickListener(
          new OnClickListener() {
            @Override
            public void onClick(View v) {
              zoomOut();
            }
          });
      hl.addView(bZoomOut);

      // zoom in button
      Button bZoomIn = new Button(context);
      bZoomIn.setLayoutParams(lpChild1);
      bZoomIn.setText("+");
      bZoomIn.setWidth(40);
      bZoomIn.setOnClickListener(
          new OnClickListener() {
            @Override
            public void onClick(View v) {
              zoomIn();
            }
          });
      hl.addView(bZoomIn);

      addSpace(hl, 6, 6);

      // prev button
      Button bPrev = new Button(context);
      bPrev.setLayoutParams(lpChild1);
      bPrev.setText("<");
      bPrev.setWidth(40);
      bPrev.setOnClickListener(
          new OnClickListener() {
            @Override
            public void onClick(View v) {
              prevPage();
            }
          });
      hl.addView(bPrev);

      // page button
      mBtPage = new Button(context);
      mBtPage.setLayoutParams(lpChild1);
      String maxPage = ((mPdfFile == null) ? "?" : Integer.toString(mPdfFile.getNumPages()));
      mBtPage.setText(mPage + "/" + maxPage);
      mBtPage.setOnClickListener(
          new OnClickListener() {
            @Override
            public void onClick(View v) {
              gotoPage();
            }
          });
      hl.addView(mBtPage);

      // next button
      Button bNext = new Button(context);
      bNext.setLayoutParams(lpChild1);
      bNext.setText(">");
      bNext.setWidth(40);
      bNext.setOnClickListener(
          new OnClickListener() {
            @Override
            public void onClick(View v) {
              nextPage();
            }
          });
      hl.addView(bNext);

      addSpace(hl, 20, 20);

      // exit button
      Button bExit = new Button(context);
      bExit.setLayoutParams(lpChild1);
      bExit.setText("Back");
      bExit.setWidth(60);
      bExit.setOnClickListener(
          new OnClickListener() {
            @Override
            public void onClick(View v) {
              finish();
            }
          });
      hl.addView(bExit);

      vg.addView(hl);

      addSpace(vg, 6, 6);
    }
  // Method to create a button, giving different functionality dependent on mode
  public void createButton(
      String name,
      final BluetoothDevice device,
      final BluetoothSocket socket,
      String mode,
      Boolean prox) {
    Button b = new Button(this);
    b.setAlpha(0f);
    b.setMinimumWidth(300);
    b.setMinimumHeight(80);
    b.setText(name);
    b.setTextColor(Color.argb(255, 0, 162, 232));

    Button.OnClickListener btnclick = null;

    // If device is an IA
    if (mode.equals("IA")) {
      // Check if device should be activated on proximity
      if (prox) {
        OutputStream outStream;
        try {
          outStream = socket.getOutputStream();
          String message = "1";
          byte[] toSend = message.getBytes();
          outStream.write(toSend);
        } catch (IOException e) {
          e.printStackTrace();
        }
      }

      b.setCompoundDrawablesWithIntrinsicBounds(R.drawable.light_off, 0, 0, 0);
      btnclick =
          new Button.OnClickListener() {
            @Override
            public void onClick(View v) {
              final InputStream inStream;
              final OutputStream outStream;
              try {
                // Request current output level
                outStream = socket.getOutputStream();
                String message = "r";

                byte[] toSend = message.getBytes();
                outStream.write(toSend);
                inStream = socket.getInputStream();

                // Data collection is pending
                gotData = 1;

                // Run timer in thread to prevent stalling
                Thread getInput =
                    new Thread(
                        new Runnable() {
                          @Override
                          public void run() {
                            try {
                              // Give small delay
                              Thread.sleep(100);

                              byte byt[] = new byte[1];

                              // Check if reply from IA
                              if (inStream.available() > 0) {
                                int received = inStream.read(byt, 0, 1);
                                inStream.read();
                                inStream.read();

                                if (received == 1) {
                                  // Toggle output power level
                                  if (((int) byt[0] & 0xff) == '0') {
                                    String message = "1";
                                    byte[] toSend = message.getBytes();
                                    outStream.write(toSend);
                                  } else if (((int) byt[0] & 0xff) == '1') {
                                    String message = "0";
                                    byte[] toSend = message.getBytes();
                                    outStream.write(toSend);
                                  }
                                }
                                // Data received
                                gotData = 2;

                                // Else no reply, IA has lost connection
                              } else {
                                // No data received
                                gotData = 0;
                              }

                            } catch (Exception e) {
                              e.getLocalizedMessage();
                            }
                          }
                        });
                getInput.start();

                // Wait until gotData is 0 or 2
                while (gotData == 1) {}

                // If not data then notify and refresh
                if (gotData == 0) {
                  Toast.makeText(getBaseContext(), R.string.no_data, Toast.LENGTH_LONG).show();
                  refresh();
                }

              } catch (IOException e) {
                e.printStackTrace();
              }
            }
          };

      // Or if device is TA
    } else if (mode.equals("TA")) {
      b.setCompoundDrawablesWithIntrinsicBounds(R.drawable.tv_icon, 0, 0, 0);
      btnclick =
          new Button.OnClickListener() {
            @Override
            public void onClick(View v) {
              television(device.getAddress());
            }
          };
    }

    b.setOnClickListener(btnclick);

    final Button settingsButton = new Button(this);

    settingsButton.setHeight(60);
    settingsButton.setWidth(60);
    settingsButton.setBackgroundResource(R.drawable.settings);
    settingsButton.setTextColor(Color.argb(255, 0, 162, 232));
    // Set associated variables
    settingsButton.setTag(R.string.zero, device.getAddress());
    settingsButton.setTag(R.string.one, b);

    Button.OnClickListener popup = null;

    // TA settings
    if (mode.equals("TA")) {

      popup =
          new Button.OnClickListener() {

            @Override
            public void onClick(final View v) {
              PopupMenu popup = new PopupMenu(getApplicationContext(), settingsButton);

              // Use layout for TA settings
              popup.getMenuInflater().inflate(R.menu.device_options, popup.getMenu());

              popup.setOnMenuItemClickListener(
                  new PopupMenu.OnMenuItemClickListener() {
                    public boolean onMenuItemClick(MenuItem item) {

                      // If rename button was pressed
                      if (item.getTitle().equals("Rename")) {
                        rename(v.getTag(R.string.zero), v.getTag(R.string.one));
                      }
                      return true;
                    }
                  });

              popup.show();
            }
          };

      // IA settings
    } else if (mode.equals("IA")) {

      popup =
          new Button.OnClickListener() {

            @Override
            public void onClick(final View v) {
              PopupMenu popup = new PopupMenu(getApplicationContext(), settingsButton);
              popup.getMenuInflater().inflate(R.menu.ia_device_options, popup.getMenu());

              popup.setOnMenuItemClickListener(
                  new PopupMenu.OnMenuItemClickListener() {
                    public boolean onMenuItemClick(MenuItem item) {
                      if (item.getTitle().equals("Rename")) {
                        rename(v.getTag(R.string.zero), v.getTag(R.string.one));
                      }

                      SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
                      SharedPreferences.Editor editor = settings.edit();

                      if (item.getTitle().equals("Activate on proximity")) {
                        editor.putBoolean(device.getAddress() + "prox", true);
                        editor.commit();
                      }
                      if (item.getTitle().equals("Do not activate on proximity")) {
                        editor.putBoolean(device.getAddress() + "prox", false);
                        editor.commit();
                      }

                      return true;
                    }
                  });

              popup.show();
            }
          };
    }
    settingsButton.setOnClickListener(popup);

    // Add button to list and animate
    ViewGroup layout = (ViewGroup) findViewById(R.id.home_page);
    RelativeLayout LL = new RelativeLayout(this);
    LL.setMinimumHeight(90);

    settingsButton.setX(310);
    settingsButton.setY(10);

    Button cover = new Button(this);
    cover.setBackgroundResource(R.drawable.scroll_cover);
    cover.setX(10);
    cover.setHeight(80);

    Button block = new Button(this);
    block.setBackgroundColor(Color.BLACK);
    block.setX(10);
    block.setHeight(80);

    b.setAlpha(1f);
    appear(b);

    appearAndSlide(cover);
    appearAndHide(block);
    deleteObject(cover, 2000);
    deleteObject(block, 1000);

    delayedAppear(settingsButton);

    LL.addView(b);
    LL.addView(settingsButton);
    LL.addView(block);
    LL.addView(cover);
    layout.addView(LL);
  }
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.categoryscreen);

    mTabHost = (TabHost) this.findViewById(R.id.tabhost);
    mTabHost.setup();

    TabSpec tab1 =
        mTabHost
            .newTabSpec("tab_free")
            .setIndicator(getText(R.string.categories_paid).toString())
            .setContent(R.id.LinearLayoutPaid);
    mTabHost.addTab(tab1);

    TabSpec tab2 =
        mTabHost
            .newTabSpec("tab_paid")
            .setIndicator(getText(R.string.categories_free).toString())
            .setContent(R.id.LinearLayoutFree);
    mTabHost.addTab(tab2);

    mTabHost.getTabWidget().getChildAt(PAID).getLayoutParams().height = 40;
    mTabHost.getTabWidget().getChildAt(FREE).getLayoutParams().height = 40;

    TextView textCatName = (TextView) findViewById(R.id.TextViewCategoryName);
    textCatName.setText(
        getIntent().getExtras().getString("name") + " (" + getText(R.string.top) + ")".toString());

    Display display = ((WindowManager) getSystemService(WINDOW_SERVICE)).getDefaultDisplay();
    int width = display.getWidth();

    ///// FREE BUTTONS//////
    Button buttonPrevFree = (Button) findViewById(R.id.ButtonPrevFree);
    // buttonPrevFree.setBackgroundDrawable(this.getResources().getDrawable(android.R.drawable.));
    buttonPrevFree.setWidth(width / 2);
    buttonPrevFree.setOnClickListener(
        new View.OnClickListener() {
          public void onClick(View v) {
            pageFree--;

            updateButtons();

            LoadInfos();
          }
        });

    Button buttonNextFree = (Button) findViewById(R.id.ButtonNextFree);
    buttonNextFree.setWidth(width / 2);
    buttonNextFree.setOnClickListener(
        new View.OnClickListener() {
          public void onClick(View v) {
            pageFree++;

            updateButtons();

            LoadInfos();
          }
        });

    ///// PAID BUTTONS//////
    Button buttonPrevPaid = (Button) findViewById(R.id.ButtonPrevPaid);
    buttonPrevPaid.setWidth(width / 2);
    buttonPrevPaid.setOnClickListener(
        new View.OnClickListener() {
          public void onClick(View v) {
            pagePaid--;

            updateButtons();

            LoadInfos();
          }
        });

    Button buttonNextPaid = (Button) findViewById(R.id.ButtonNextPaid);
    buttonNextPaid.setWidth(width / 2);
    buttonNextPaid.setOnClickListener(
        new View.OnClickListener() {
          public void onClick(View v) {
            pagePaid++;

            updateButtons();

            LoadInfos();
          }
        });

    updateButtons();
    LoadInfos();
  }
  /* (非 Javadoc)
   * @see android.app.Activity#onResume()
   */
  @Override
  protected void onResume() {
    super.onResume();

    db = dbman.getReadableDatabase();

    hasRecord = dbman.hasLubRecords(db, getCAR_ID());

    // プリファレンスのSortOrderの値を読み出し、invertOrderに反映する。
    boolean invertOrder = getMileageOrder();

    // 画面幅を取得
    int displayWidth = getWindowManager().getDefaultDisplay().getWidth();
    // ボタン幅の修正
    btn_add_mileage.setWidth(displayWidth / 2);
    btn_show_stats.setWidth(displayWidth / 2);

    // 各種単位の取得
    priceUnit = dbman.getPriceUnitById(db, getCAR_ID());
    distanceUnit = dbman.getDistanceUnitById(db, getCAR_ID());
    volumeUnit = dbman.getVolumeUnitById(db, getCAR_ID());

    cMileageList = dbman.getRefuelRecordsById(db, getCAR_ID(), invertOrder);

    // Cursorのレコード数に応じ、「統計を表示」ボタンをロックする処理
    if (cMileageList.getCount() == 0) {
      btn_show_stats.setEnabled(false);
    } else {
      btn_show_stats.setEnabled(true);
    }

    String[] from = {
      // "_id",
      "DATE_OF_REFUEL", "LUB_AMOUNT", "VOLUMEUNIT"
    };
    int[] to = {
      // R.id.tv_value_number_refuel,
      R.id.tv_value_dateOfRefuel, R.id.tv_value_amountOfOil, R.id.tv_unit_amountOfOil
    };

    SimpleCursorAdapter sca =
        new SimpleCursorAdapter(
            getApplicationContext(), R.layout.listviewelemnt_mileagelist, cMileageList, from, to);
    lv_mileagelist.setAdapter(sca);

    // ListViewの要素を長押しした時のコンテキストメニューのリスナーをセット
    registerForContextMenu(lv_mileagelist);

    // ListViewの要素をクリックしたときのリスナーを宣言する
    // implementしてないので匿名メソッド
    lv_mileagelist.setOnItemClickListener(
        new AdapterView.OnItemClickListener() {

          @Override
          public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
            // 取得したCursorから給油記録の詳細を取得する
            cLvRow = (Cursor) lv_mileagelist.getItemAtPosition(position);
            for (int i = 0; i < cLvRow.getColumnCount(); i++) {
              Log.i(
                  "onItemClick",
                  "name of Column Index "
                      + String.valueOf(i)
                      + ":"
                      + cLvRow.getColumnName(i)
                      + " value = "
                      + cLvRow.getString(i));
            }

            int rowId = Integer.parseInt(cLvRow.getString(cLvRow.getColumnIndex("_id")));
            Log.d("onItemClick", "rowid is " + String.valueOf(rowId));

            // 給油記録の元ネタをDBから取得する
            Cursor cRefuelRecord = dbman.getRefuelRecordById(db, getCAR_ID(), rowId);
            Log.d("onItemClick", "returned rows = " + cRefuelRecord.getCount());
            for (int i = 0; i < cRefuelRecord.getColumnCount(); i++) {
              Log.i(
                  "onItemClick",
                  "name of Column Index "
                      + String.valueOf(i)
                      + ":"
                      + cRefuelRecord.getColumnName(i)
                      + " value = "
                      + cRefuelRecord.getString(i));
            }

            // AlertDialogに差し込むテキストの生成
            // 値の取得:計算用
            double dblDistance = cRefuelRecord.getDouble(5); // 走行距離
            double dblOilAmount = cRefuelRecord.getDouble(3); // 給油量
            double dblUnitprice = cRefuelRecord.getDouble(4); // 給油単価

            // 給油時の燃費
            double dblMileage = dblDistance / dblOilAmount;
            BigDecimal bd1 = new BigDecimal(dblMileage);
            String strMileage =
                String.valueOf(bd1.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());

            // 給油時のランニングコスト
            double dblRunning = dblOilAmount * dblUnitprice / dblDistance;
            BigDecimal bd2 = new BigDecimal(dblRunning);
            String strRunningCost =
                String.valueOf(bd2.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());

            // 値の取得
            String strRefuelDate = cLvRow.getString(1); // 給油日時
            String strDistance = String.valueOf(dblDistance); // 走行距離
            String strOilAmount = String.valueOf(dblOilAmount); // 給油量
            String strUnitPrice = String.valueOf(dblUnitprice); // 給油単価

            // AlertDialog内にセットするテキストの生成
            String adtext =
                getString(R.string.label_dateOfRefuel)
                    + " : "
                    + strRefuelDate
                    + "\n"
                    + getString(R.string.label_odometer)
                    + " : "
                    + strDistance
                    + " "
                    + distanceUnit
                    + "\n"
                    + getString(R.string.label_amountOfOil)
                    + " : "
                    + strOilAmount
                    + " "
                    + volumeUnit
                    + "\n"
                    + getString(R.string.label_unitPrice)
                    + " : "
                    + strUnitPrice
                    + " "
                    + priceUnit
                    + "\n"
                    + getString(R.string.label_fuelmileage)
                    + strMileage
                    + " "
                    + distanceUnit
                    + "/"
                    + volumeUnit
                    + "\n"
                    + getString(R.string.label_runningcost)
                    + strRunningCost
                    + " "
                    + priceUnit
                    + "/"
                    + distanceUnit;
            adbuilder.setMessage(adtext);

            // AlertDialogを表示する
            adbuilder.create();
            adbuilder.show();

            cRefuelRecord.close();
          }
        });

    btn_add_mileage.setOnClickListener(this);
    btn_show_stats.setOnClickListener(this);

    // 燃費とランニングコストの値を差し込む
    double txtMileage = dbman.getCurrentMileageById(db, getCAR_ID());
    double txtRunning = dbman.getCurrentRunningCostById(db, getCAR_ID());
    tv_value_FuelMileage2.setText(String.valueOf(txtMileage));
    tv_value_RunningCosts2.setText(String.valueOf(txtRunning));

    // 燃費とランニングコストの単位を差し込む
    tv_unit_fuelMileage2.setText(distanceUnit + "/" + volumeUnit);
    tv_unit_runningCosts2.setText(priceUnit + "/" + distanceUnit);

    setTotalAmountOfOil(getCAR_ID());
  }