I am recently struggling with creating a java based code on Android Studio which I am working on since 2days now. Unfortunately, I cannot find any resolution for my problem on the stackoverflow or any other forum..
I try to highlight a button when clicked in red or green depending on if the buttons text is text1 or text2 of a string-array.
If I run the application it always shows me an error or the button simply doesn't change it's color when I press it. I guess that this has to do with the if-clause, but I don't really know how to solve this problem in any other way.
I would really appreciate any help on this matter!
XML code for green button
<item
android:state_pressed="true"
android:drawable="#81c784"/>
<item
android:state_selected="true"
android:drawable="#color/#4caf50"/>
XML code for red button
<item
android:state_pressed="true"
android:drawable="#FF4081"/>
<item
android:state_selected="true"
android:drawable="#d50000"/>
Java code:
Button button1;
Button button2;
String[] txtString;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.first_layout);
txtString = getResources().getStringArray(R.array.optiontxt);
String random = txtString[new random().nextInt(txtString.length)];
button1 = (Button)findViewById(R.id.btn1);
button2 = (Button)findViewById(R.id.btn2);
if (random == txtString[0])
{
button1.setText(txtString[0]);
button1.setBackgroundResource(R.drawable.button_green);
button2.setText(txtString[1]);
button2.setBackgroundResource(R.drawable.button_red);
}
else
{
button1.setText(txtString[1]);
button1.setBackgroundResource(R.drawable.button_red);
button2.setText(txtString[0]);
button2.setBackgroundResource(R.drawable.button_green);
} button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {}}; button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {}};
I also tried varies other codes for setting the background of the buttons which didn't work aswell, e.g.
button1.setBackground(Drawable.createFromPath("/drawable/button_green"));
or
button1.getBackground().setState(new int[]{R.drawable.button_green});
or
button1.setBackgroundResource(R.drawable.button_green);
I would be very thankful for any help.
Thank you very much in advance!
Did you try to call button1.setsetBackgroundResource in the onCreate method?
Related
I'm trying to make a simple calculator with Embarcadero C++Builder. I'm still a novice. How can I extract text from a button? When I press the button, I want to see "3" on a TEdit field (for example). Surely the event is OnClick. But after that, what must I do to redirect this button to TEdit?
As you said, TButton has an OnClick event; if you want to append a certain character to the text of a TEdit:
// Somewhere declared and istantiated:
//TButton *Button1;
//TEdit *Edit1;
//----------------------------------
void __fastcall TForm1::Button1Click(TObject* Sender)
{
Edit1->Text = Edit1->Text + "3";
}
I've spent better half of today trying to resolve seemingly trivial QListWidget behavior customization: when used presses mouse left button and moves mouse cursor, the content of ListWidget is scrolled and selection is moved to another item that happens to appear under mouse cursor. I am alright with scrolling, but I want to avoid selecting all consequtive items because this causes timely operation in my program. Finally I would like to keep list content scrolling on mouse press and move, but select items only by clicking directly on them.
Drag-n-drop is disabled for this list (which is default behavior) and it should be; I've tried to disable it explicitly: no changes whatsoever.
I have read all available docs on Qt related classes like QListWidget, QListWidgetItem, QListView, you name it! Tried to make sense of source code for these widgets; dug up StackOverflow and Google... but sadly no result :(
Here is all relevant code for my QListWidget: single selection, nothing fancy:
QListWidget* categoryListWidget;
...
categoryListWidget = new QListWidget();
categoryListWidget->move(offsetX, offsetY);
categoryListWidget->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
categoryListWidget->setSelectionMode(QAbstractItemView::SingleSelection);
categoryListWidget->setFocusPolicy(Qt::NoFocus);
categoryListWidget->setStyleSheet(listQSS);
...
categoryListWidget->clear();
new QListWidgetItem(tr("1 - Sample Category 1"), categoryListWidget);
new QListWidgetItem(tr("2 - Sample Category 2"), categoryListWidget);
new QListWidgetItem(tr("3 - Sample Category 3 with a very long name"), categoryListWidget);
new QListWidgetItem(tr("4 - Sample Category 4"), categoryListWidget);
C++/Qt 5.5 if that's somehow relevant, both Win and Mac platforms share similar behavior.
For the sake of whoever stumbles upon the same question, here is my solution: subclass QListWidget and make child class ignore mouseMove events when leftButton is pressed.
Header:
class QtListWidget: public QListWidget
{ // QListWidget clone that suppresses item selection on mouse click+drag
private:
bool mousePressed;
public:
QtListWidget():QListWidget(), mousePressed(false) {}
protected:
virtual void mousePressEvent(QMouseEvent *event);
virtual void mouseMoveEvent(QMouseEvent *event);
virtual void mouseReleaseEvent(QMouseEvent *event);
};
Source:
//////////////////////////////////////////////////////////////////////////
void QtListWidget::mousePressEvent(QMouseEvent *event){
// qDebug() << "QtListWidget::mousePressEvent";
if(event->button() == Qt::LeftButton)
mousePressed = true;
QListWidget::mousePressEvent(event);
}
void QtListWidget::mouseMoveEvent(QMouseEvent *event){
// qDebug() << "QtListWidget::mouseMoveEvent";
if(!mousePressed) // disable click+drag
QListWidget::mouseMoveEvent(event);
}
void QtListWidget::mouseReleaseEvent(QMouseEvent *event){
// qDebug() << "QtListWidget::mouseReleaseEvent";
if(event->button() == Qt::LeftButton)
mousePressed = false;
QListWidget::mouseReleaseEvent(event);
}
//////////////////////////////////////////////////////////////////////////
Usage is trivial, for as many List Widgets as you need:
QtListWidget* categoryListWidget;
// all original code above would still work as expected
...
Want it done right? then do it yourself! :)
Your solution killed scrolling for me. I am using QListView. Here's another way:
In the constructor of the QListView's parent:
ui->listView->setSelectionMode(QAbstractItemView::NoSelection);
connect(ui->listView, SIGNAL(clicked(QModelIndex)), this, SLOT(on_listview_clicked(QModelIndex)));
In the connected slot:
on_listview_clicked(const QModelIndex &index)
{
if (index.isValid())
{
ui->listView->selectionModel->select(index, QItemSelectionModel::Toggle | QItemSelectionModel::Rows);
}
}
So, it only selects on a click.
I am a newcomer in android. Please forgive me if i am asking anything stupid.
I want to show/hide an element (TextView) based on the user input in an EditText element.
Basically there are 3 textview . Based on what is being entered in the edittext, only one of them should be shown ( in this example if mometasone is entered in the edittext, the textview with id strongsteroidtext should be shown and others should hide)
Here is the code pattern that I am using.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
EditText creamname = (EditText) findViewById(R.id.creamname);
TextView nosteroid = (TextView) findViewById(R.id.nosteroidtext);
TextView weaksteroid = (TextView) findViewById(R.id.weaksteroidtext);
TextView strongsteroid = (TextView) findViewById(R.id.strongsteroidtext);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
final String cream = (creamname.getText().toString().trim());
weaksteroidlist = R.string.weaksteroidlist;
{if (cream.equals("beclomethasone")) {
weaksteroid.setVisibility(View.VISIBLE);
nosteroid.setVisibility(View.INVISIBLE);
}
if (cream.equals("mometasone")) {
strongsteroid.setVisibility(View.VISIBLE);
nosteroid.setVisibility(View.INVISIBLE);
} else weaksteroid.setVisibility(View.INVISIBLE);
strongsteroid.setVisibility(View.INVISIBLE);
nosteroid.setVisibility(View.VISIBLE);
}
Now, when I am running this, apparently the "else" statement is only working, which means the "nosteroid" text that is supposed to be visible by this is visible. But when mometasone is being entered, nothing happens ( means the if statement is not working).
What am I getting wrong? please guide me.
OnCreate() method is called only the first time the view is created, not every time the text changes in ur EditText. Study android activity life circle first.
What you want can be achieved by registering ur editText with onKeyListener or onTextChangeListener
And aware this:
else
statement 1;
statement 2;
Is equal to
else {
statement 1;
}
statement 2;
I am trying to show a card so I know everything up to that point works. However, when I try to display the card, it just goes straight to the home card. The card I was trying to show was just going to display what was said in the voice recognizer before but that didn't work so I just put plain text and that didn't work either. Application goes - voice trigger --> voice recognizer --> this service:
public class MedMinderService extends Service {
public String MedName;
public String voiceResults;
private static final String TAG = "ShowData";
private static final String LIVE_CARD_ID = "showdata";
public static final String PREFS_NAME = "MyPreferencesFile";
private TimelineManager mTimelineManager;
private LiveCard mLiveCard;
#Override
public void onCreate() {
super.onCreate();
mTimelineManager = TimelineManager.from(this);
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
public int onStartCommand(Intent intent, int flags, int startId) {
String voiceResults = intent.getExtras()
.getString(RecognizerIntent.EXTRA_RESULTS);
String MedName = voiceResults; //MedName declared
SharedPreferences MedInfo = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = MedInfo.edit();
editor.putString("MedName", MedName.toString());
editor.commit();
mLiveCard = mTimelineManager.getLiveCard(LIVE_CARD_ID);
Intent i = new Intent(this, ShowDataActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);
return START_STICKY;
}
}
The intent at the bottom goes to this activity:
public class ShowDataActivity extends Activity {
private LiveCard mLiveCard;
public static final String PREFS_NAME = "MyPreferencesFile";
private GestureDetector mGestureDetector;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SharedPreferences MedInfo = getSharedPreferences(PREFS_NAME, 0);
Card ShowDataCard = new Card(this);
ShowDataCard.setText("IT WORKS!");
//ShowDataCard.setText(MedInfo.getString("MedName", "your medication"));
View ShowDataCardView = ShowDataCard.toView();
setContentView(ShowDataCardView);
}
The "ShowDataCard" that has been commented out is what I was origonally trying to do with the voice recognition but it wouldn't even work with the text "IT WORKS!"
Again: I am just trying to show a card with the text "IT WORKS"
thanks
The easiest way to get a live card to appear with just text is using widgets that are compatible with RemoteViews. You can find a list of them in the GDK documentation here:
https://developers.google.com/glass/develop/gdk/ui/live-cards
under the Creating low-frequency live cards section.
Here is some sample code (based on your code above) that can get that working quickly:
final String LIVE_CARD_ID = "showdata";
mLiveCard = mTimelineManager.getLiveCard(LIVE_CARD_ID);
RemoteViews remoteViews =
new RemoteViews(getPackageName(), R.layout.layout_helloglass);
mLiveCard.setViews(remoteViews);
// Make sure Glass navigates to LiveCard immediately
mLiveCard.setNonSilent(true);
mLiveCard.publish();
The layout file can look like this for layout_helloglass.xml:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:text="Hello, Glass!" />
</FrameLayout>
If you still want to navigate to another Activity from your LiveCard, you need to associate the Activity with a PendingIntent and then associate that PendingIntent with the LiveCard's action. This would happen immediately before the LiveCard.publish() method:
Intent i = new Intent(this, ShowCardActivity.class);
mLiveCard.setAction(PendingIntent.getActivity(this, 0, i, 0));
That should get you up and running! Hopefully this will help.
There was a bug in the GDK Sneak Peek that prevented voice prompts from creating Services. If one inserted a Log.d() call in a Service's onStartCommand() override, they would discover that it were never called.
This bug has been fixed in the GDK Preview. This behavior should not appear again.
This question was rewritten after the GDK Preview launch to remove this outdated answer. Thanks to user Falcon for notifying me.
I belive my question is kinda simple for most experienced Android developers but not for me!
I am trying to set the name in a menuItem and make the text WHITE colored. First of all the text gets displayed only if I klick on the menuItem, or rather when I click on the menuItem the text turns white and is readable. What I dont know is if the text gets displayed only when I click on the menuItem or if it for some reason changes color to WHITE when clicked so I am able to see it? Any useful help how I can make the text white and visible all the time in the menuItem?
item.setTitle(this.task.getName()); is supposed to be White and visible all the time in the menuItem!. Thx alot!
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
MenuInflater inflater = getMenuInflater();
inflater.inflate( R.menu.show_task_feedback_menu, menu );
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch ( item.getItemId() )
{
case R.id.show_task_feedback_menu_add_feedback: item.setTitle(this.task.getName()); <------------- Here is the problem!!!!!!!!!!
this.startTaskFeedback();
return true;
default: return true;
}
}