I'm developing an android application. It is an exam app. When a user clicks an answer, the application changes the layout with $setContentView(); in same activity.
But it gives an error for layout Caused by: java.lang.NumberFormatException: unable to parse '#2131230721' as integer
My layout file is below, if you need I can put my project myserver. And I can paste my activity code, but it's a basic setContentView() only. I guess one of my id's is causing the error but i couldn't find it.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#fff"
android:orientation="vertical"
android:weightSum="1" >
<LinearLayout
android:id="#+id/soruNoIleriVeGeri"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="0.01"
android:weightSum="1" >
<LinearLayout
android:id="#+id/SoruLayout"
android:layout_width="fill_parent"
android:layout_height="60dp"
android:background="#drawable/question_top_plain"
android:weightSum="1" >
<LinearLayout
android:id="#+id/OncekiSoru"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:orientation="vertical" >
<ImageButton
android:id="#+id/qIPrevious"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/back_button"
android:onClick="qIPrevious"
android:paddingLeft="5dp" />
</LinearLayout>
<LinearLayout
android:layout_width="57dp"
android:layout_height="wrap_content" >
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<ImageButton
android:id="#+id/imageButton2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/about_question" />
</LinearLayout>
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="fill_parent" >
<ImageButton
android:id="#+id/ImageButton01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/add_favourite" />
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<ImageView
android:id="#+id/goToQuestion"
android:layout_width="56dp"
android:layout_height="wrap_content"
android:onClick="onshowQuestion"
android:src="#drawable/show_question" />
</LinearLayout>
<LinearLayout
android:layout_width="50dp"
android:layout_height="45dp"
android:layout_weight="0.57" >
<ImageButton
android:id="#+id/homeButton"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
android:background="#drawable/tab_home"
android:onClick="goHome" />
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="fill_parent" >
<ImageButton
android:id="#+id/imageButton1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#drawable/next_button"
android:onClick="qINextQuestion" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#drawable/question_top_plain"
android:weightSum="1" >
<LinearLayout
android:id="#+id/resultIconPlain"
android:layout_width="84dp"
android:layout_height="fill_parent"
android:paddingLeft="20dp" >
</LinearLayout>
<LinearLayout
android:layout_width="234dp"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/resultView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1.13"
android:gravity="center_horizontal"
android:text="TextView"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#111" />
</LinearLayout>
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="59dp"
android:background="#drawable/question_top_plain" >
<LinearLayout
android:id="#+id/dogruCevap"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="0.01"
android:weightSum="1" >
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="fill_parent" >
<TextView
android:id="#+id/StatikDogruCevap"
android:layout_width="126dp"
android:layout_height="wrap_content"
android:text="#string/StatikDogruCevap"
android:textStyle="#style/boldText" />
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_weight="0.01" >
<TextView
android:id="#+id/dogruCevapView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:paddingRight="10dp"
android:text="TextView"
android:textStyle="#style/rightAnswer" />
</LinearLayout>
</LinearLayout>
<LinearLayout
android:id="#+id/cevabiniz"
android:layout_width="fill_parent"
android:layout_height="54dp"
android:layout_weight="0.01"
android:weightSum="1" >
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="fill_parent" >
<TextView
android:id="#+id/cevabinizView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:paddingLeft="10dp"
android:text="TextView"
android:textStyle="#style/rightAnswer" />
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="fill_parent" >
<TextView
android:id="#+id/StatikCevap"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/StatikCevap"
android:textStyle="#style/boldText" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
<ScrollView
android:id="#+id/ScrollView01"
android:layout_width="fill_parent"
android:layout_height="350px"
android:fillViewport="true" >
<LinearLayout
android:id="#+id/dogruCevapAyrinti"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="0.60"
android:isScrollContainer="true"
android:minHeight="400px"
android:scrollbarAlwaysDrawHorizontalTrack="true"
android:scrollbars="vertical" >
<TextView
android:id="#+id/dogruCevapAyrintiView"
android:layout_width="fill_parent"
android:layout_height="324dp"
android:scrollHorizontally="false"
android:scrollbarAlwaysDrawHorizontalTrack="true"
android:scrollbars="vertical"
android:text="TextView"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#111" >
</TextView>
</LinearLayout>
</ScrollView>
</LinearLayout>
Here is error codes and myActivity sorry for Turkish variable names
at android.app.Activity.dispatchTouchEvent(Activity.java:2061)
at
com.android.internal.policy.impl.PhoneWindow$DecorView.dispatchTouchEvent(PhoneWindow.java:1643)
at android.view.ViewRoot.handleMessage(ViewRoot.java:1691)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:123)
at android.app.ActivityThread.main(ActivityThread.java:4363)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:521)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:860)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
at dalvik.system.NativeStart.main(Native Method)
java.lang.reflect.InvocationTargetException
at android.widget.TextView.<init>(TextView.java:320)
at java.lang.reflect.Constructor.constructNative(Native Method)
at java.lang.reflect.Constructor.newInstance(Constructor.java:446)
at android.view.LayoutInflater.createView(LayoutInflater.java:500)
... 41 more
java.lang.NumberFormatException: unable to parse '#2131230721' as integer
at java.lang.Integer.parse(Integer.java:374)
at java.lang.Integer.parseInt(Integer.java:363)
at com.android.internal.util.XmlUtils.convertValueToInt(XmlUtils.java:121)
at android.content.res.TypedArray.getInt(TypedArray.java:201)
at android.widget.TextView.<init>(TextView.java:647)
package com.eandroid.workingSet;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.message.BasicNameValuePair;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import android.app.Activity;
import android.app.TabActivity;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.eandroid.entity.Question;
public class QuestionInterfaceActivity extends Activity {
LinearLayout layoutForA;
LinearLayout layoutForB;
LinearLayout layoutForC;
LinearLayout layoutForD;
LinearLayout layoutForE;
LinearLayout choiceATotalPlain;
LinearLayout choiceBTotalPlain;
LinearLayout choiceCTotalPlain;
LinearLayout choiceDTotalPlain;
LinearLayout choiceETotalPlain;
LinearLayout allTotalPlain;
List<Question> questionList = new ArrayList<Question>();
Node node = null;
NodeList nodeList = null;
NodeList nodeListForTestInfo = null;
InputStream is = null;
private TextView choiceA;
private TextView choiceB;
private TextView choiceC;
private TextView choiceD;
private TextView choiceE;
private TextView questionText;
private TextView soruIdText;
private TextView soruIdEv;
private TextView soruBilgileriView;
private TextView cevabinizView;
private TextView dogruCevapView;
private TextView dogruCevapAyrintiView;
private TextView resultView;
private int currentQuestionIndex;
Question currentQuestion = null;
private String testName = null;
HttpClient httpclient;
HttpPost httppost;
ArrayList<NameValuePair> postParameters;
HttpResponse response;
InputStream contentStream;
private String rightAnswers = "";
private String userAnswers = "";
private String resultOfAnswers = "";
private String userId = "1";
private static String testRelationId;
private LinearLayout resultIconPlain;
private static String willPostUrl =
"http://balabanhafriyat.com/SchoolProjectWebSide/postFromPhone/SendDataFromPhone";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState != null) {
Toast.makeText(QuestionInterfaceActivity.this, "Hoşgeldin Hacı",
Toast.LENGTH_SHORT).show();
}
settleOrientation();
Bundle extras = getIntent().getExtras();
if (extras != null) {
testName = extras.getString("testName");
}
try {
is = getAssets().open(testName);
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new InputSource(is));
doc.getDocumentElement().normalize();
nodeList = doc.getElementsByTagName("question");
nodeListForTestInfo = doc.getElementsByTagName("testInfo");
Node testNode = nodeListForTestInfo.item(0);
testRelationId = parseItToStringByName(testNode, "testRelationId");
} catch (Exception e) {
e.printStackTrace();
}
currentQuestionIndex = 1;
showQuestion();
}
public void settleOrientation() {
int setLayout = getResources().getConfiguration().orientation;
switch (setLayout) {
case 1:
setContentView(R.layout.buttontry);
loadDesign();
break;
case 2:
setContentView(R.layout.buttontry);
break;
default:
break;
}
}
public void callEvaluationActivity(int optionToSeeQuestion,
String userAnswer) {
setContentView(R.layout.evaluation_screen);
// resultView = (TextView) findViewById(R.id.resultView);
cevabinizView = (TextView) findViewById(R.id.cevabiniz);
dogruCevapView = (TextView) findViewById(R.id.rightAnswer);
dogruCevapAyrintiView = (TextView)
findViewById(R.id.dogruCevapAyrintiView);
// soruBilgileriView.setText(currentQuestion.getShortInfo());
dogruCevapAyrintiView.setText(currentQuestion.getRightAnswerDetail());
dogruCevapView.setText(currentQuestion.getRightAnswer());
if (optionToSeeQuestion == 2) {
cevabinizView.setText(userAnswer);
if (currentQuestion.getRightAnswer().equals(userAnswer)) {
resultView.setTextColor(Color.GREEN);
resultView.setText("Doğru Cevap");
resultOfAnswers = resultOfAnswers + "1$";
} else {
resultView.setTextColor(Color.RED);
resultView.setText("Cevap Yanlış !!! ");
resultOfAnswers = resultOfAnswers + "0$";
}
userAnswers = userAnswers + userAnswer + "$";
rightAnswers = rightAnswers + currentQuestion.getRightAnswer()
+ "$";
}
}
public void loadDesign() {
allTotalPlain = (LinearLayout) findViewById(R.id.allTotalPlain);
allTotalPlain.setBackgroundResource(R.drawable.yellow_button);
choiceATotalPlain = (LinearLayout) findViewById(R.id.choiceTotalPlain);
choiceBTotalPlain = (LinearLayout) findViewById(R.id.choiceBTotalPlain);
choiceCTotalPlain = (LinearLayout) findViewById(R.id.choiceCTotalPlain);
choiceDTotalPlain = (LinearLayout) findViewById(R.id.choiceDTotalPlain);
choiceETotalPlain = (LinearLayout) findViewById(R.id.choiceETotalPlain);
layoutForA = (LinearLayout) findViewById(R.id.abuttonLayout);
layoutForB = (LinearLayout) findViewById(R.id.bButtonLayout);
layoutForC = (LinearLayout) findViewById(R.id.cButtonLayout);
layoutForD = (LinearLayout) findViewById(R.id.dButtonLayout);
layoutForE = (LinearLayout) findViewById(R.id.ebuttonLayout);
createButton("A");
createButton("B");
createButton("C");
createButton("D");
createButton("E");
}
private void showQuestion() {
questionText = (TextView) findViewById(R.id.soruTextView);
choiceA = (TextView) findViewById(R.id.choiceA);
choiceB = (TextView) findViewById(R.id.choiceB);
choiceC = (TextView) findViewById(R.id.choiceC);
choiceD = (TextView) findViewById(R.id.choiceD);
choiceE = (TextView) findViewById(R.id.choiceE);
currentQuestion = setQuestionFieldById(currentQuestionIndex);
questionText.setText(currentQuestion.getQuestionText());
choiceA.setText(currentQuestion.getChoiceA());
choiceB.setText(currentQuestion.getChoiceB());
choiceC.setText(currentQuestion.getChoiceC());
choiceD.setText(currentQuestion.getChoiceD());
choiceE.setText(currentQuestion.getChoiceE());
/*
* consumerAnswer .setOnCheckedChangeListener(new
* OnCheckedChangeListener() { public void onCheckedChanged(RadioGroup
* group, int checkedId) { if (choiceA.getId() == checkedId) {
* approveAnswer(2, "A"); } if (choiceB.getId() == checkedId) {
*
* approveAnswer(2, "B"); } if (choiceC.getId() == checkedId) {
*
* approveAnswer(2, "C"); } if (choiceD.getId() == checkedId) {
*
* approveAnswer(2, "D"); } if (choiceE.getId() == checkedId) {
*
* approveAnswer(2, "E"); } } });
*/
}
private void approveAnswer(int optionToSeeQuestion, final String userChoice) {
callEvaluationActivity(optionToSeeQuestion, userChoice);
}
// Eger optionToSeeQuestion 1 ise kullanıcının cevap karsılastırılması
// yapılmamalı 2 ise yapılmalı
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK && requestCode == 999) {
if (data.hasExtra("action")) {
String aim = data.getExtras().getString("aim");
Toast.makeText(this, "Ne yapmak istiyorsunuz" + aim,
Toast.LENGTH_LONG).show();
}
}
super.onActivityResult(requestCode, resultCode, data);
}
public void qINextQuestion(View view) {
if (currentQuestionIndex == nodeList.getLength() - 1) {
Toast.makeText(QuestionInterfaceActivity.this, "Son Sorudasınız",
Toast.LENGTH_SHORT).show();
} else {
currentQuestionIndex++;
settleOrientation();
showQuestion();
}
}
public void qIPrevious(View view) {
if (currentQuestionIndex == 1) {
Toast.makeText(QuestionInterfaceActivity.this, "İlk Sorudasınız",
Toast.LENGTH_SHORT).show();
} else {
currentQuestionIndex--;
settleOrientation();
showQuestion();
}
}
public Question setQuestionFieldById(int questionId) {
Question q = new Question();
for (int i = 0; i < nodeList.getLength(); i++) {
node = nodeList.item(i);
int idFromXml = Integer.parseInt(parseItToStringByName(node,
"questionNumber"));
if (questionId == idFromXml) {
q.setQuestionId(questionId);
q.setChoiceA(parseItToStringByName(node, "choiceA"));
q.setChoiceB(parseItToStringByName(node, "choiceB"));
q.setChoiceC(parseItToStringByName(node, "choiceC"));
q.setChoiceD(parseItToStringByName(node, "choiceD"));
q.setChoiceE(parseItToStringByName(node, "choiceE"));
q.setQuestionText(parseItToStringByName(node,
"questionText"));
q.setRightAnswer(parseItToStringByName(node,
"rightAnswer"));
q.setRightAnswerDetail(parseItToStringByName(node,
"answerDetail"));
}
}
return q;
}
public String parseItToStringByName(Node node, String nodeName) {
Element mainELement = (Element) node;
NodeList questionList = mainELement.getElementsByTagName(nodeName);
Element questionElement = (Element) questionList.item(0);
NodeList question = questionElement.getChildNodes();
String result = question.item(0).getNodeValue().replaceAll("\n", "")
.replaceAll("\t", "");
result.trim();
return result;
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
setContentView(R.layout.landscapequestion);
showQuestion();
} else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
setContentView(R.layout.buttontry);
showQuestion();
}
}
#Override
public void onBackPressed() {
beforeQuitProcess();
super.onBackPressed();
}
public void beforeQuitProcess() {
postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("testId", testRelationId));
postParameters
.add(new BasicNameValuePair("rightAnswers", rightAnswers));
postParameters.add(new BasicNameValuePair("userAnswers", userAnswers));
postParameters.add(new BasicNameValuePair("userAnswerAndResult",
resultOfAnswers));
postParameters.add(new BasicNameValuePair("userId", userId));
PostDataToServer postDataToServer = new PostDataToServer();
HttpResponse response = postDataToServer.postData(willPostUrl,
postParameters);
contentStream = postDataToServer.parseHttpResponseToStream(response);
String responseFromServer = postDataToServer
.convertStreamToString(contentStream);
if (responseFromServer != null) {
Toast.makeText(QuestionInterfaceActivity.this, "Kayıt Edildi",
Toast.LENGTH_SHORT).show();
}
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
Toast.makeText(QuestionInterfaceActivity.this, "Çıktı Hacı",
Toast.LENGTH_SHORT).show();
// Save UI state changes to the savedInstanceState.
// This bundle will be passed to onCreate if the process is
// killed and restarted.
savedInstanceState.putBoolean("MyBoolean", true);
savedInstanceState.putDouble("myDouble", 1.9);
savedInstanceState.putInt("MyInt", 1);
savedInstanceState.putString("MyString", "Welcome back to Android");
// etc.
super.onSaveInstanceState(savedInstanceState);
finish();
}
public void onDestroy() {
super.onDestroy();
android.os.Process.killProcess(android.os.Process.myPid());
}
#Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
Toast.makeText(QuestionInterfaceActivity.this, "Hoşgeldin Hacı",
Toast.LENGTH_SHORT).show();
super.onRestoreInstanceState(savedInstanceState);
// Restore UI state from the savedInstanceState.
// This bundle has also been passed to onCreate.
boolean myBoolean = savedInstanceState.getBoolean("MyBoolean");
double myDouble = savedInstanceState.getDouble("myDouble");
int myInt = savedInstanceState.getInt("MyInt");
String myString = savedInstanceState.getString("MyString");
}
#Override
protected void onResume() {
super.onResume();
}
public void onshowAnswer(View v) {
callEvaluationActivity(1, "A");
}
public void onshowQuestion(View view) {
setContentView(R.layout.buttontry);
loadDesign();
showQuestion();
}
public void goHome(View view) {
beforeQuitProcess();
Intent intent = new Intent(QuestionInterfaceActivity.this,
LoginEvaluation.class);
intent.putExtra("userId", userId);
startActivity(intent);
}
public void createButton(final String text) {
Button button = new Button(this);
button.setTextColor(Color.parseColor("#000000"));
button.setBackgroundResource(R.drawable.button_selector);
button.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
clickMeMyFriend(view, text);
}
});
button.setText(text);
if (text.equals("A")) {
layoutForA.addView(button);
}
if (text.equals("B")) {
layoutForB.addView(button);
}
if (text.equals("C")) {
layoutForC.addView(button);
}
if (text.equals("D")) {
layoutForD.addView(button);
}
if (text.equals("E")) {
layoutForE.addView(button);
}
}
private void clickMeMyFriend(View view, String chooice) {
if (chooice.equals("A")) {
approveAnswer(2, "A");
}
if (chooice.equals("B")) {
approveAnswer(2, "B");
}
if (chooice.equals("C")) {
approveAnswer(2, "C");
}
if (chooice.equals("D")) {
approveAnswer(2, "D");
}
if (chooice.equals("E")) {
approveAnswer(2, "E");
}
}
public void onTotalAClick(View view) {
switch (view.getId()) {
case R.id.choiceTotalPlain:
choiceATotalPlain.setBackgroundResource(R.drawable.black_button);
approveAnswer(2, "A");
break;
case R.id.choiceBTotalPlain:
choiceBTotalPlain.setBackgroundResource(R.drawable.black_button);
approveAnswer(2, "B");
break;
case R.id.choiceCTotalPlain:
approveAnswer(2, "C");
choiceCTotalPlain.setBackgroundResource(R.drawable.black_button);
break;
case R.id.choiceDTotalPlain:
approveAnswer(2, "D");
choiceDTotalPlain.setBackgroundResource(R.drawable.black_button);
break;
case R.id.choiceETotalPlain:
approveAnswer(2, "E");
choiceETotalPlain.setBackgroundResource(R.drawable.black_button);
break;
default:
break;
}
}
}
Thanks for all help
Thanks too much for your effort Barak , Alex Lockwood and the others too i recode my xml layout upon your advices nothing changed but i could seen an error cant be realize before due to my unnecassary LinearLayout block .Whatever the error is :there is a statement in my layout
android:textStyle="#style/boldText"
in this statement the value can be only bold or normal etc .this statement should be like
style="#style/choiceStyle"
thanks for your help .I decided not to work after 00:00
Are you saying you are trying to use setContentView more than once in an activity?
From everything I have read, that won't work.
If you want to change your UI without switching activities you need to use fragments, or put all of the Views you want into your one layout and hide/show only the relevant ones for each portion of your activity with setVisibility().
The reason why you are getting a NumberFormatException is because #2131230721 is not an integer. Here's what you should do:
Re-do your entire XML layout. I am not kidding... the layout you have posted is an absolute disaster. Sorry if that's mean, but I can't let you go on thinking this is the correct way to make your layouts :).
From what I can tell, you are wrapping every single view in a LinearLayout to achieve some sort of margin/padding effect. This is what the android:margin and android:padding attributes are for. Don't over-complicate things with weird android:layout_weight values, as this will make your app run slower when your layout gets inflated. If you ever find that your XML has more than 3 or 4 LinearLayouts you should take a step back and see if you are missing an easier, more efficient solution. It is frowned upon to have nested LinearLayouts too, as it is expensive to inflate these at runtime and will drain your battery as a result.
Do a Project --> Clean and restart eclipse.
Post more information. For example, your entire logcat output would be nice (not just one line). Posting your code is almost always a good idea too. It is very difficult to understand the problem from the tiny amount of information you have provided. Remember that it is beneficial to you to provide as much information as you can because the more information we have, the more likely it is that we can help answer your question. You should also provide us with line numbers and/or indicate on which lines the errors occur.
Oh yeah, and welcome to StackOverflow... :P
Is it possible that the weights are causing the problems? I've never used weights as decimals before, I thought they had to be real numbers, I mean like 1 or 2 etc. Floor numbers. Just a thought
From what I can see its something to do with a number and a text view, this could either be the text views color, weight, ID or style.
What's in style/boldText and style/rightAnswer?
You layout file does Start with a LinearLayout and defines a xmlns:android="http://schemas.android.com/apk/res/android", but you end up with a closing <ScrollView> Tag? Is there anything missing? Plus, javaCode would be great!
By the way: did u try to "clean" you project in eclipse, using Project->Clean?
This resets the R file and often helps!
Related
(Very first thing i want to make clear is that i am COMPLETELY NEWBIE, very beginner in android, in fact in programming/coding!)
The menu is referred in onCreateOptionMenu and the calling method is also onOptionsItemSelected to open up menu but the method for each option/item is set as onMenuItemClick and onMenuItemLongClick which is ideal for context menu options/items!
The problem is onMenuItemClick have input parameters as (View v, int position) and I cannot change it to only (View v) or to (MenuItem item).
What I want is clicking on each item of menu should bring out new activity!
I also tried putting all my switch-case-break statements to onOptionsItemSelected method but it is still not working!
I also tried in fragment class, setHasOptionsMenu (true); but it did not work!
onMenuItemClick doesn't get called
(Deprecated) Fragment onOptionsItemSelected not being called
Below is the activity_main_menu.xml layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#color/menu_item_background">
<include layout="#layout/toolbar" />
<FrameLayout
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
Below is the fragment_main.xml layout
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.android.coffeeshop.MainFragment">
<!-- TODO: Update blank fragment layout -->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:background="#color/menu_item_background">
<EditText
android:id="#+id/username"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:cursorVisible="true"
android:hint="#string/EditTextHint"
android:inputType="textNoSuggestions" />
<EditText
android:id="#+id/usercontact"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:cursorVisible="true"
android:hint="#string/usercontactHint"
android:inputType="textNoSuggestions" />
<EditText
android:id="#+id/useremail"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:cursorVisible="true"
android:hint="#string/useremailHint"
android:inputType="textEmailAddress" />
<TextView
style="#style/HeaderTextStyle"
android:layout_marginTop="16dp"
android:text="#string/Toppings" />
<CheckBox
android:id="#+id/whippedCreamcheckbox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:paddingEnd="24dp"
android:paddingLeft="24dp"
android:paddingStart="24dp"
android:text="#string/WhippedCream"
android:textSize="16sp" />
<CheckBox
android:id="#+id/Chocolatebox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:paddingEnd="24dp"
android:paddingLeft="24dp"
android:paddingStart="24dp"
android:text="#string/Chocolate"
android:textSize="16sp" />
<TextView
style="#style/HeaderTextStyle"
android:layout_marginTop="16dp"
android:text="#string/quantity" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:layout_width="48dp"
android:layout_height="48dp"
android:layout_marginTop="16dp"
android:onClick="decrement"
android:text="#string/minus" />
<TextView
android:id="#+id/quantity_text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginTop="16dp"
android:text="#string/Zero"
android:textColor="#android:color/black"
android:textSize="20sp" />
<Button
android:layout_width="48dp"
android:layout_height="48dp"
android:layout_marginTop="16dp"
android:onClick="increment"
android:text="#string/plus" />
</LinearLayout>
<TextView
style="#style/HeaderTextStyle"
android:layout_marginTop="16dp"
android:text="#string/OrderSummary" />
<TextView
android:id="#+id/order_summary_text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:text="#string/Price"
android:textColor="#android:color/black"
android:textSize="20sp" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:id="#+id/orderButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:onClick="submitOrder"
android:text="#string/Order" />
<Button
android:id="#+id/placeOrder"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="16dp"
android:layout_marginStart="16dp"
android:layout_marginTop="16dp"
android:onClick="placeOrder"
android:text="#string/PlaceOrder" />
</LinearLayout>
</LinearLayout>
</ScrollView>
Below is the MainMenu.java class file from where i am trying to handle fragment menu!
package com.example.android.coffeeshop5profile;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.ActionMenuView;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.yalantis.contextmenu.lib.ContextMenuDialogFragment;
import com.yalantis.contextmenu.lib.MenuObject;
import com.yalantis.contextmenu.lib.MenuParams;
import com.yalantis.contextmenu.lib.interfaces.OnMenuItemLongClickListener;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
/**
* This app displays an order form to order coffee.
*/
public class MainMenu extends AppCompatActivity implements ActionMenuView.OnMenuItemClickListener, OnMenuItemLongClickListener {
private FragmentManager fragmentManager;
private ContextMenuDialogFragment mMenuDialogFragment;
int quantity = 1;
int price = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_menu);
fragmentManager = getSupportFragmentManager();
initToolbar();
initMenuFragment();
addFragment(new MainFragment(), true, R.id.container);
}
private void initMenuFragment() {
MenuParams menuParams = new MenuParams();
menuParams.setActionBarSize((int) getResources().getDimension(R.dimen.tool_bar_height));
menuParams.setMenuObjects(getMenuObjects());
menuParams.setClosableOutside(false);
mMenuDialogFragment = ContextMenuDialogFragment.newInstance(menuParams);
mMenuDialogFragment.setItemLongClickListener(this);
}
private List<MenuObject> getMenuObjects() {
List<MenuObject> menuObjects = new ArrayList<>();
MenuObject close = new MenuObject();
close.setResource(R.drawable.icn_close);
MenuObject send = new MenuObject("Send message");
send.setResource(R.drawable.icn_1);
MenuObject like = new MenuObject("Like profile");
Bitmap b = BitmapFactory.decodeResource(getResources(), R.drawable.icn_2);
like.setBitmap(b);
MenuObject addFr = new MenuObject("Add to friends");
BitmapDrawable bd = new BitmapDrawable(getResources(),
BitmapFactory.decodeResource(getResources(), R.drawable.icn_3));
addFr.setDrawable(bd);
MenuObject addFav = new MenuObject("Add to favorites");
addFav.setResource(R.drawable.icn_4);
MenuObject block = new MenuObject("Block user");
block.setResource(R.drawable.icn_5);
menuObjects.add(close);
menuObjects.add(send);
menuObjects.add(like);
menuObjects.add(addFr);
menuObjects.add(addFav);
menuObjects.add(block);
return menuObjects;
}
private void initToolbar() {
Toolbar mToolbar = (Toolbar) findViewById(R.id.toolbar);
TextView mToolBarTextView = (TextView) findViewById(R.id.text_view_toolbar_title);
setSupportActionBar(mToolbar);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowTitleEnabled(false);
mToolbar.setNavigationIcon(R.drawable.btn_back);
mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onBackPressed();
}
});
mToolBarTextView.setText(R.string.title_text);
}
protected void addFragment(Fragment fragment, boolean addToBackStack, int containerId) {
invalidateOptionsMenu();
String backStackName = fragment.getClass().getName();
boolean fragmentPopped = fragmentManager.popBackStackImmediate(backStackName, 0);
if (!fragmentPopped) {
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.add(containerId, fragment, backStackName)
.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
if (addToBackStack)
transaction.addToBackStack(backStackName);
transaction.commit();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.context_main_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.context_menu:
if (fragmentManager.findFragmentByTag(ContextMenuDialogFragment.TAG) == null) {
mMenuDialogFragment.show(fragmentManager, ContextMenuDialogFragment.TAG);
}
break;
case R.drawable.icn_3:
Intent userProfileIntent = new Intent(MainMenu.this, UserProfile.class);
MainMenu.this.startActivity(userProfileIntent);
break;
case R.drawable.icn_4:
Intent wishListIntent = new Intent(MainMenu.this, UserProfile.class);
MainMenu.this.startActivity(wishListIntent);
break;
}
return false; //Turning this true or to super.OnOptionsItemSelected did nothing!
}
#Override
public void onBackPressed() {
if (mMenuDialogFragment != null && mMenuDialogFragment.isAdded()) {
mMenuDialogFragment.dismiss();
} else {
finish();
}
}
#Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()){
case R.drawable.icn_3:
Intent userProfileIntent = new Intent(MainMenu.this, UserProfile.class);
MainMenu.this.startActivity(userProfileIntent);
break;
case R.drawable.icn_4:
Intent wishListIntent = new Intent(MainMenu.this, UserProfile.class);
MainMenu.this.startActivity(wishListIntent);
break;
} return true;
}
#Override
public void onMenuItemLongClick(View clickedView, int position) {
Toast.makeText(this, "Long clicked on position: " + position, Toast.LENGTH_SHORT).show();
}
public void submitOrder(View view) {
String orderSummaryString = createOrderSummary(quantity);
displayMessage(orderSummaryString);
}
public void placeOrder(View view) {
TextView useremail = (TextView) findViewById(R.id.useremail);
String useremailString = useremail.getText().toString();
String orderSummaryString = createOrderSummary(quantity);
sendMail(useremailString, "Coffee Order By: " + useremailString, orderSummaryString);
}
private void sendMail(String email, String subject, String messageBody) {
Session session = createSessionObject();
try {
Message message = createMessage(email, subject, messageBody, session);
new SendMailTask().execute(message);
} catch (MessagingException | UnsupportedEncodingException e) {
e.printStackTrace();
}
}
private Message createMessage(String email, String subject, String messageBody, Session session)
throws MessagingException, UnsupportedEncodingException {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("clientaddress#gmail.com", "Coffee Order By"));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(email, email));
message.setSubject(subject);
message.setText(messageBody);
return message;
}
private Session createSessionObject() {
Properties properties = new Properties();
properties.put("mail.smtp.auth", "true");
properties.put("mail.smtp.starttls.enable", "true");
properties.put("mail.smtp.host", "smtp.gmail.com");
properties.put("mail.smtp.port", "587");
return Session.getInstance(properties, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("clientaddress#gmail.com", "************");
}
});
}
public class SendMailTask extends AsyncTask<Message, Void, Void> {
private ProgressDialog progressDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = ProgressDialog.show(MainMenu.this, "Please wait", "Sending mail", true, false);
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
progressDialog.dismiss();
}
#Override
public Void doInBackground(Message... messages) {
try {
Transport.send(messages[0]);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
/**
* This method is called when the plus button is clicked.
*/
public void increment(View view) {
if (quantity < 100) {
quantity = quantity + 1;
displayQuantity(quantity);
} else {
Toast.makeText(this, "You have reached maximum numbers of coffees to be allowed!", Toast.LENGTH_SHORT).show();
}
}
/**
* This method is called when the minus button is clicked.
*/
public void decrement(View view) {
if (quantity >= 2) {
quantity = quantity - 1;
displayQuantity(quantity);
} else {
Toast.makeText(this, "You can not place order in negative number!", Toast.LENGTH_SHORT).show();
}
}
public String createOrderSummary(int quantity) {
CheckBox whippedCreamCheckbox = (CheckBox) findViewById(R.id.whippedCreamcheckbox);
boolean hasWhippedCream = whippedCreamCheckbox.isChecked();
CheckBox chocolatebox = (CheckBox) findViewById(R.id.Chocolatebox);
boolean hasChocolate = chocolatebox.isChecked();
price = 5;
if (hasWhippedCream) {
price = price + 1;
}
if (hasChocolate) {
price = price + 2;
}
int finalPrice = quantity * price;
EditText usernameTextView = (EditText) findViewById(R.id.username);
String usernameString = usernameTextView.getText().toString();
EditText usercontact = (EditText) findViewById(R.id.usercontact);
String userContactString = usercontact.getText().toString();
EditText useremail = (EditText) findViewById(R.id.useremail);
String userEmailString = useremail.getText().toString();
String OrderSummary = getString(R.string.username) + ": " + usernameString;
OrderSummary += "\n" + getString(R.string.ContactNumber) + " " + userContactString;
OrderSummary += "\n" + getString(R.string.eAddress) + " " + userEmailString;
OrderSummary += "\n" + getString(R.string.AddedWhippedCream) + " " + hasWhippedCream;
OrderSummary += "\n" + getString(R.string.AddedChocolate) + " " + hasChocolate;
OrderSummary += "\n" + getString(R.string.quantity) + ": " + quantity;
OrderSummary += "\n" + getString(R.string.totalprice) + finalPrice;
OrderSummary += "\n" + getString(R.string.thankyou);
return OrderSummary;
}
/**
* This method displays the given quantity value on the screen.
*/
public void displayQuantity(int number) {
TextView quantityTextView = (TextView) findViewById(
R.id.quantity_text_view);
quantityTextView.setText(String.format("%d", number));
}
/**
* This method displays the given text on the screen.
*/
public void displayMessage(String message) {
TextView orderSummaryTextView = (TextView) findViewById(R.id.order_summary_text_view);
orderSummaryTextView.setText(message);
}
}
Below is the MainFragment.java class file
package com.example.android.coffeeshop5profile;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class MainFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
setHasOptionsMenu(true);
setMenuVisibility(false);
return rootView;
}
}
Following is the Activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/main_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/blue_grey_700"
android:orientation="vertical"
android:weightSum="4"
tools:context=".legacy.MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="3"
android:gravity="center_vertical"
android:orientation="vertical">
<ImageView
android:id="#+id/google_icon"
android:layout_width="48dp"
android:layout_height="48dp"
android:layout_gravity="center"
android:layout_marginBottom="10dp"
android:contentDescription="#string/desc_google_icon"
android:src="#drawable/googleg_color" />
<TextView
android:id="#+id/title_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:layout_gravity="center"
android:text="#string/title_text"
android:textColor="#android:color/white"
android:textSize="36sp" />
<TextView
android:id="#+id/status"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="#string/signed_out"
android:textColor="#android:color/white"
android:textSize="14sp" />
<TextView
android:id="#+id/detail"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fadeScrollbars="true"
android:gravity="center"
android:maxLines="5"
android:padding="10dp"
android:scrollbars="vertical"
android:textColor="#android:color/white"
android:textSize="14sp" />
</LinearLayout>
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:background="#color/blue_grey_900">
<com.google.android.gms.common.SignInButton
android:id="#+id/sign_in_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:visibility="visible"
tools:visibility="gone" />
<LinearLayout
android:id="#+id/sign_out_and_disconnect"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:orientation="horizontal"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:visibility="gone"
tools:visibility="visible">
<Button
android:id="#+id/sign_out_button"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="#string/sign_out"
android:theme="#style/ThemeOverlay.MyDarkButton" />
<Button
android:id="#+id/disconnect_button"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="#string/disconnect"
android:theme="#style/ThemeOverlay.MyDarkButton" />
<Button
android:id="#+id/secondpage"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="#string/secondpage"
android:theme="#style/ThemeOverlay.MyDarkButton" />
</LinearLayout>
</RelativeLayout>
</LinearLayout>
below is the res/menu/context_main_menu.xml file
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="#+id/context_menu"
android:title="#string/context_menu"
android:icon="#drawable/btn_add"
android:orderInCategory="100"
app:showAsAction="always" />
</menu>
...unfortunately, 30000 characters limit has been reached so i cant upload mainActivity.java file!
Kindly help!
Best regards,
sagar
try this code on
Change the following code
onMenuItemClick(MenuItem item)
to
onMenuItemClick(View clickedView, int position)
like this
`#override
public void onMenuItemClick(View clickedView, int position) {
switch (position) {
case 1:
startActivity(new Intent(MainActivity.this, UserProfile.class));
break;
case 2:
startActivity(new Intent(MainActivity.this, UserProfile.class));
break;
}
}`
i hope this help you
If onOptionsItemSelected() method is not called in fragment then just make sure you return false from the onOptionsItemSelected() method of Activity.
I am trying to programmatically generate two RadioGroups. I have succesfully generated the first one but I need to generate the second one onCheckedChangeListener of the first radio group. Here is my code for the activity.
package com.packr.activities;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.support.design.widget.TextInputLayout;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import com.avast.android.dialogs.fragment.SimpleDialogFragment;
import com.avast.android.dialogs.iface.ISimpleDialogListener;
import com.kbeanie.imagechooser.api.ChooserType;
import com.kbeanie.imagechooser.api.ChosenImage;
import com.kbeanie.imagechooser.api.ImageChooserListener;
import com.kbeanie.imagechooser.api.ImageChooserManager;
import com.packr.R;
import com.packr.adapters.ShipmentsAdapter;
import com.packr.classes.Item;
import com.packr.classes.Packr;
import com.packr.classes.Shipment;
import com.packr.database.DBShipments;
import com.packr.logging.L;
import java.util.ArrayList;
public class ItemDetailsActivity extends AppCompatActivity implements ISimpleDialogListener, ImageChooserListener {
private Toolbar toolbar;
private ImageChooserManager imageChooserManager;
private SeekBar seekBar;
private Intent intent;
private RadioGroup itemTypeRadioGroup, deliveryMethod;
private TextView addImage;
private Bitmap myBitmap;
private ShipmentsAdapter mShipmentAdapter;
private static long back_pressed;
private MyShipmentsActivity activity;
private ImageView itemImage;
private LinearLayout itemDetailsLinearLayout, weightTypeLinearLayout;
private TextInputLayout itemDescriptionText, quantityText, valueOfItemText;
private EditText itemDescription, quantity, valueOfItem;
private TextView weightUnit, weightValue, selectWeight;
private ArrayList<Shipment> shipmentArrayList = new ArrayList<>();
private ArrayList<Item> deliveryTypeArrayList = new ArrayList<>();
private ArrayList<Item> itemTypeArrayList = new ArrayList<>();
private ArrayList<Item> shipmentTypeArrayList = new ArrayList<>();
private ArrayList<Item> weightTypeArrayList = new ArrayList<>();
private String city, state, pincode, recipientName, recipientContact, street, itemType = "", deliveryType = "", route;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_item_details);
initialize();
onClick();
toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setTitle("Item details");
setSupportActionBar(toolbar);
deliveryTypeArrayList = Packr.getWritableDatabase().readDeliveryType(DBShipments.DELIVERY_TYPE);
for (int i = 0; i < deliveryTypeArrayList.size(); i++) {
}
itemTypeArrayList = Packr.getWritableDatabase().readDeliveryType(DBShipments.ITEM_TYPE);
int itemId;
//first radio group
RadioButton rb = null;
float scale = getResources().getDisplayMetrics().density;
final int dpAsPixels = (int) (10 * scale + 0.5f);
RadioGroup rg = new RadioGroup(this); //create the RadioGroup
rg.setOrientation(RadioGroup.HORIZONTAL);//or RadioGroup.VERTICAL
rg.setPadding(dpAsPixels, dpAsPixels, dpAsPixels, dpAsPixels);
final Drawable drawableTop = getResources().getDrawable(R.drawable.document_icon);
for (int i = 0; i < itemTypeArrayList.size(); i++) {
if (itemTypeArrayList.get(i).getActive() == 1) {
rb = new RadioButton(this);
rg.addView(rb); //the RadioButtons are added to the radioGroup instead of the layout
rb.setText(itemTypeArrayList.get(i).getCode());
rb.setId(itemTypeArrayList.get(i).getId());
L.m(itemTypeArrayList.get(i).getId() + "hello");
}
if (rb != null) {
rb.setAllCaps(true);
}
assert rb != null;
rb.setGravity(Gravity.CENTER_VERTICAL);
rb.setButtonDrawable(null);
rb.setPadding(dpAsPixels, 0, dpAsPixels, 0);
rb.setCompoundDrawablesWithIntrinsicBounds(null, drawableTop, null, null);
}
itemDetailsLinearLayout.addView(rg);
final RadioGroup weightTypeRadioGroup = new RadioGroup(this); //create the RadioGroup
weightTypeRadioGroup.setOrientation(RadioGroup.HORIZONTAL);//or RadioGroup.VERTICAL
weightTypeRadioGroup.setPadding(dpAsPixels, dpAsPixels, dpAsPixels, dpAsPixels);
shipmentTypeArrayList = Packr.getWritableDatabase().readDeliveryType(DBShipments.SHIPMENT_TYPE);
for (int i = 0; i < shipmentTypeArrayList.size(); i++) {
}
final RadioButton finalRb = rb;
rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
if (finalRb != null) {
checkedId = finalRb.getId();
System.out.print(checkedId);
L.m(group.getCheckedRadioButtonId() + "");
weightTypeArrayList = Packr.getWritableDatabase().readWeightType();
for (int i = 0; i < weightTypeArrayList.size(); i++) {
L.m(weightTypeArrayList.get(i).getTitle());
//second radio group
RadioButton weightTypeRadioButton = null;
weightTypeRadioButton = new RadioButton(getApplicationContext());
weightTypeRadioGroup.addView(weightTypeRadioButton);
weightTypeRadioButton.setText(weightTypeArrayList.get(i).getTitle());
weightTypeRadioButton.setId(weightTypeArrayList.get(i).getId());
}
if (weightTypeRadioGroup.getParent() != null){
((ViewGroup)weightTypeRadioGroup.getParent()).removeView(weightTypeRadioGroup);
weightTypeLinearLayout.addView(weightTypeRadioGroup);
}
}
}
});
deliveryMethod.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
if (checkedId == R.id.normalDeliveryRadioButton) {
deliveryType = "Normal Delivery";
} else {
deliveryType = "Express Delivery";
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_item_details, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_done) {
if (validationCheck()) {
Shipment shipment = new Shipment();
shipment.setRecipientName(recipientName);
shipment.setRecipientContact(recipientContact);
shipment.setCity(city);
shipment.setState(state);
shipment.setStreetNo(street);
shipment.setRoute(route);
shipment.setPostalCode(pincode);
shipment.setItemQuantity(quantity.getText().toString());
shipment.setItemType(itemType);
shipment.setDeliveryType(deliveryType);
shipmentArrayList.add(shipment);
Packr.getWritableDatabase().insertShipment(shipmentArrayList, false);
mShipmentAdapter = new ShipmentsAdapter(getApplicationContext(), activity);
mShipmentAdapter.setShipmentArrayList(shipmentArrayList);
Intent intent = new Intent(ItemDetailsActivity.this, MyShipmentsActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish();
}
return true;
}
return super.onOptionsItemSelected(item);
}
public void initialize() {
intent = getIntent();
recipientName = intent.getStringExtra("recipientName");
recipientContact = intent.getStringExtra("recipientContact");
city = intent.getStringExtra("city");
state = intent.getStringExtra("state");
pincode = intent.getStringExtra("pincode");
street = intent.getStringExtra("street");
route = intent.getStringExtra("route");
deliveryMethod = (RadioGroup) findViewById(R.id.radioGroupShippingMethod);
selectWeight = (TextView) findViewById(R.id.selectWeight);
addImage = (TextView) findViewById(R.id.addImage);
itemImage = (ImageView) findViewById(R.id.item_image);
itemDescriptionText = (TextInputLayout) findViewById(R.id.item_description_text_input_layout);
quantityText = (TextInputLayout) findViewById(R.id.item_quantity_text_input_layout);
valueOfItemText = (TextInputLayout) findViewById(R.id.item_value_text_input_layout);
itemDescription = (EditText) findViewById(R.id.item_description_edit_text);
quantity = (EditText) findViewById(R.id.item_quantity_edit_text);
valueOfItem = (EditText) findViewById(R.id.item_value_edit_text);
itemDetailsLinearLayout = (LinearLayout) findViewById(R.id.itemDetailsLinearLayout);
weightTypeLinearLayout = (LinearLayout) findViewById(R.id.weightTypeRadioButton);
}
public void onClick() {
addImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SimpleDialogFragment.createBuilder(getApplicationContext(), getSupportFragmentManager()).setTitle("Choose item image").setMessage(R.string.selectImage).setNegativeButtonText("Gallery").setPositiveButtonText("Camera").show();
}
});
}
public Boolean validationCheck() {
if (itemDescription.getText().length() == 0) {
itemDescriptionText.setErrorEnabled(true);
itemDescriptionText.setError("Please provide an item description");
} else if (quantity.getText().length() == 0) {
quantityText.setErrorEnabled(true);
quantityText.setError("Provide item quantity");
} else if (valueOfItem.getText().length() == 0) {
valueOfItemText.setErrorEnabled(true);
valueOfItemText.setError("Please provide value of item");
} else {
return true;
}
return false;
}
public void chooseImage() {
imageChooserManager = new ImageChooserManager(this,
ChooserType.REQUEST_PICK_PICTURE);
imageChooserManager.setImageChooserListener(this);
try {
imageChooserManager.choose();
} catch (Exception e) {
e.printStackTrace();
}
}
public void snapImage() {
imageChooserManager = new ImageChooserManager(this, ChooserType.REQUEST_CAPTURE_PICTURE);
imageChooserManager.setImageChooserListener(this);
try {
imageChooserManager.choose();
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onNegativeButtonClicked(int i) {
chooseImage();
}
#Override
public void onNeutralButtonClicked(int i) {
}
#Override
public void onPositiveButtonClicked(int i) {
snapImage();
}
#Override
public void onImageChosen(ChosenImage chosenImage) {
myBitmap = BitmapFactory.decodeFile(chosenImage.getFileThumbnail());
runOnUiThread(new Runnable() {
public void run() {
itemImage.setImageBitmap(myBitmap);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK &&
(requestCode == ChooserType.REQUEST_PICK_PICTURE ||
requestCode == ChooserType.REQUEST_CAPTURE_PICTURE)) {
imageChooserManager.submit(requestCode, data);
}
}
#Override
public void onError(String s) {
}
#Override
public void onBackPressed() {
AlertDialog.Builder alert = new AlertDialog.Builder(ItemDetailsActivity.this);
alert.setTitle("Cancel shipment");
alert.setMessage("Are you sure?");
alert.setPositiveButton("YES", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(ItemDetailsActivity.this, MyShipmentsActivity.class);
startActivity(intent);
finish();
}
});
alert.setNegativeButton("NO", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//Cancel
}
});
alert.show();
}
}
Here is the code for my layout xml file.
<RelativeLayout
android:focusableInTouchMode="true"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/white"
tools:context="com.packr.activities.ItemDetailsActivity"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto">
<include
android:id="#+id/toolbar"
layout="#layout/toolbar"/>
<ScrollView
android:layout_below="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/scrollView"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:paddingBottom="80dp">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="What are you sending?"
android:fontFamily="sans-serif-light"
android:padding="20dp"
android:textColor="#color/textColorPrimary"/>
<LinearLayout
android:id="#+id/itemDetailsLinearLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
</LinearLayout>
<LinearLayout
tools:visibility="visible"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
tools:ignore="UseCompoundDrawables">
<ImageView
android:id="#+id/item_image"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:src="#drawable/image_background"
android:layout_margin="16dp"
android:contentDescription="#string/product_image" />
<TextView
android:id="#+id/addImage"
android:padding="20dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Add an image"
android:layout_gravity="center"
android:layout_marginLeft="10dp"
android:textColor="#color/textColorSecondary"
/>
</LinearLayout>
<android.support.design.widget.TextInputLayout
android:id="#+id/item_description_text_input_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
tools:visibility="gone"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp">
<EditText
android:id="#+id/item_description_edit_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/item_description"
android:inputType="textMultiLine"
android:imeOptions="flagNoFullscreen"
android:lines="5"/>
</android.support.design.widget.TextInputLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/selectWeight"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="18sp"
android:text="Permitted weight"
android:fontFamily="sans-serif-light"
android:padding="20dp"/>
</RelativeLayout>
<LinearLayout
android:id="#+id/weightTypeRadioButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
</LinearLayout>
<android.support.design.widget.TextInputLayout
android:id="#+id/item_quantity_text_input_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
tools:visibility="visible"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp">
<EditText
android:id="#+id/item_quantity_edit_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/itemQuantity"
android:inputType="number" />
</android.support.design.widget.TextInputLayout>
<android.support.design.widget.TextInputLayout
android:id="#+id/item_value_text_input_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
tools:visibility="visible"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp">
<EditText
android:id="#+id/item_value_edit_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/item_value"
android:inputType="number"
android:imeOptions="flagNoFullscreen"/>
</android.support.design.widget.TextInputLayout>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Choose shipping method"
android:fontFamily="sans-serif-light"
android:textColor="#color/textColorPrimary"
android:layout_marginLeft="25dp"
android:layout_marginStart="25dp"
android:layout_marginTop="25dp"/>
<RadioGroup
android:id="#+id/radioGroupShippingMethod"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="20dp">
<RadioButton
android:id="#+id/normalDeliveryRadioButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Normal Delivery"
android:checked="true"/>
<RadioButton
android:id="#+id/expressDeliveryRadioButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Express Delivery"/>
</RadioGroup>
</LinearLayout>
</ScrollView>
//This contains the layout for the bottom price bar //
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:background="#color/textColorPrimary"
android:padding="12dp">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true">
<TextView
android:id="#+id/priceText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Price"
android:textSize="18sp"
android:fontFamily="sans-serif-light"
android:textColor="#color/white"/>
<TextView
android:id="#+id/equals"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/equals"
android:textSize="18sp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:textColor="#color/white"/>
<TextView
android:id="#+id/Rs"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/Rs"
android:textSize="18sp"
android:fontFamily="sans-serif-light"
android:layout_marginRight="10dp"
android:layout_marginEnd="10dp"
android:textColor="#color/white"/>
<TextView
android:id="#+id/calculatedPrice"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="550"
android:textSize="18sp"
android:fontFamily="sans-serif-light"
android:layout_marginRight="10dp"
android:layout_marginEnd="10dp"
android:textColor="#color/white"/>
</LinearLayout>
</RelativeLayout>
</RelativeLayout>
do you not just need to repeat the same proccess inside the onCheckChangedListener?
rg.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
//Create another radio group here
//then add it to the view
RadioGroup rg2 = new RadioGroup(this); //create the RadioGroup
rg2.setOrientation(RadioGroup.HORIZONTAL);//or RadioGroup.VERTICAL
rg2.setPadding(dpAsPixels, dpAsPixels, dpAsPixels, dpAsPixels);
final Drawable drawableTop = getResources().getDrawable(R.drawable.document_icon);
for (int i = 0; i < itemTypeArrayList.size(); i++) {
if (itemTypeArrayList.get(i).getActive() == 1) {
rb = new RadioButton(this);
rg2.addView(rb); //the RadioButtons are added to the radioGroup instead of the layout
rb.setText(itemTypeArrayList.get(i).getCode());
rb.setId(itemTypeArrayList.get(i).getId());
}
}
itemDetailsLinearLayout.addView(rg);
}
});
You may need to declare rg2 public at the top of the class so it can be accessed by the onCheckChangedListener
Right now I have an idea for a project and I would like to know if anyone can help me on the same logic.
As such I need to create or generate a number of EditText according to amount you enter, ie, to select or enter a number such as 5, show me 5 EditText layout for type 5 values. They know that the form could accomplish this? Any ideas please?
I guess it must be a way to do it with a loop, but not like carrying this calculation Java to XML. Thank you.
Here is an example of generating EditText items based on the number you enter. You can ignore the scrollview in the layout file I just put it in case someone added a lot of EditText items that would go off the screen.
MainActivity.java
package com.example.test;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TextView;
public class MainActivity extends Activity {
public static final String TAG = MainActivity.class.getSimpleName();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText count = (EditText) findViewById(R.id.count);
final TextView output = (TextView) findViewById(R.id.output);
final Button generate = (Button) findViewById(R.id.generate);
final Button values = (Button) findViewById(R.id.values);
final LinearLayout container = (LinearLayout) findViewById(R.id.container);
generate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int numberOfControlsToGenerate = 0;
try {
numberOfControlsToGenerate = Integer.parseInt(count.getText().toString().trim());
} catch (NumberFormatException e) {
Log.e(TAG, e.getMessage(), e);
}
if (numberOfControlsToGenerate > 0) {
if (container.getChildCount() > 0) {
container.removeAllViews();
}
for (int counter = 0; counter < numberOfControlsToGenerate; counter++) {
addEditText(container);
}
}
}
});
values.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String[] editTextValues = new String[container.getChildCount()];
StringBuilder editTextValuesBuilder = new StringBuilder();
for (int counter = 0; counter < container.getChildCount(); counter++) {
EditText child = (EditText) container.getChildAt(counter);
editTextValues[counter] = child.getText().toString().trim();
editTextValuesBuilder.append(editTextValues[counter]).append("\n");
}
output.setText(editTextValuesBuilder.toString());
}
});
}
private void addEditText(LinearLayout container) {
final LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
EditText editTextToAdd = new EditText(this);
editTextToAdd.setLayoutParams(params);
container.addView(editTextToAdd);
}
}
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_horizontal"
android:orientation="vertical"
android:padding="16dp"
tools:context="${packageName}.${activityClass}" >
<EditText
android:id="#+id/count"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:imeOptions="actionDone"
android:inputType="number"
android:textSize="20sp" />
<Button
android:id="#+id/generate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Go" />
<Button
android:id="#+id/values"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Get Values" />
<TextView
android:id="#+id/output"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent" >
<LinearLayout
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
</LinearLayout>
</ScrollView>
</LinearLayout>
I have 5 buttons every one has letter (Button "H",Button "E"Button "L"Button "L"Button "O") which make the word "HELLO". what I need is to make on click sequence to these buttons so if I click "H" first and "E" second until complete the word the app will do something, But if I click "L" first will give me some error message.
Any Idea to do this sequence?
Thanks
Just have an Array like this:
int[] tracker = new int[5];
and when you click a button, say "H", set tracker[0] = 1;
but when you click a button, say "L", check whether all the previous button values are 1. If yes, then set the corresponding tracker to 1 else, show an error message, and do not make any change to the tracker Array.
Something Like this:
onHClick{
tracker[0] = 1;
}
onEClick{
for(int i=0; i<1; i++){
if(tracker[i] == 0){
//show error message and return;
}else{
tracker[1] = 1;
return;
}
}
}
You can do something like
When activity started you just make other button Enabled = false of something like that. But make the first button Enabled. Don't make the Visible=false.
Now on click of Button "H" make enable Button "E" and so on.
So user will only have to click the button in sequence. Button can not be presses in any random manner.
Try this and let me know that it works or not.
Very Interesting and exactly same to your requirement..check once..
If you give any string other than HELLO also works better.
public class ButtonTest extends Activity
{
private String result="";
String sampleText = "HELLO";
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.test);
int noOfBtns = sampleText.length();
LinearLayout ll = (LinearLayout)findViewById(R.id.btnlay);
final TextView tvtext = (TextView)findViewById(R.id.result);
final Button[] btns = new Button[noOfBtns];
for(int i=0;i<noOfBtns;i++)
{
btns[i] = new Button(this);
btns[i].setText(sampleText.substring(i,i+1));
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
ll.addView(btns[i], lp);
final int j = i;
btns[i].setOnClickListener(new OnClickListener() {
public void onClick(View v)
{
System.out.println(j+" "+result.length());
if(j == result.length())
{
result = result+btns[j].getText().toString();
if(sampleText.startsWith(result))
{
tvtext.setText(result);
}
}
else
{
Toast.makeText(getApplicationContext(), "Wrong Button Pressed", Toast.LENGTH_SHORT).show();
}
}
});
}
}
}
Layout file
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:id="#+id/result"
android:layout_width="fill_parent"
android:layout_height="50dp"
android:textColor="#fff"/>
<LinearLayout
android:id="#+id/btnlay"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal">
</LinearLayout>
</LinearLayout>
Try the following
package com.example.buttonsequence;
import java.util.ArrayList;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity
{
ArrayList<Button> buttonList=null;
TextView resultTextView=null;
Button buttons[]=null;
String helloStr="HELLO";
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonList=new ArrayList<Button>();
buttons=new Button[5];
this.resultTextView=(TextView) this.findViewById(R.id.result_text);
this.resultTextView.setText("");
buttons[0]=(Button)this.findViewById(R.id.h_button);
buttons[1]=(Button)this.findViewById(R.id.e_button);
buttons[2]=(Button)this.findViewById(R.id.l_button);
buttons[3]=(Button)this.findViewById(R.id.l2_button);
buttons[4]=(Button)this.findViewById(R.id.o_button);
for(int k=0;k<5;k++)
buttons[k].setOnClickListener(onClickListener);
Button button=(Button)this.findViewById(R.id.exit_button);
button.setOnClickListener
(
new OnClickListener()
{
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
finish();
}
}
);
}
OnClickListener onClickListener=new OnClickListener()
{
#Override
public void onClick(View v)
{
// TODO Auto-generated method stub
Button b=(Button)v;
buttonList.add(b);
int size=buttonList.size();
if(size>0)
{
StringBuilder resultBuilder=new StringBuilder();
for(int i=0;i<size;i++)
{
Button tempButton=buttonList.get(i);
if(tempButton==buttons[i])
{
resultBuilder.append(helloStr.charAt(i));
if(i==4)
{
resultTextView.setText(resultBuilder.toString()+" clicked");
buttonList.clear();
}
else
{
resultTextView.setText(resultBuilder.toString()+" clicked");
}
}
else
{
buttonList.remove(i);
Toast.makeText(getApplicationContext(), "No correctly clicked", Toast.LENGTH_SHORT).show();
break;
}
}
}
else
{
resultTextView.setText("Invalid pressed");
}
}
};
}
activity_main.xml
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/hello_world" />
<Button
android:id="#+id/h_button"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="H" />
<Button
android:id="#+id/e_button"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="E" />
<Button
android:id="#+id/l_button"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="L" />
<Button
android:id="#+id/l2_button"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="L" />
<Button
android:id="#+id/o_button"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="O" />
<TextView
android:id="#+id/result_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Small Text"
android:textAppearance="?android:attr/textAppearanceSmall" />
<Button
android:id="#+id/exit_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Exit" />
</LinearLayout>
I don't know exactly your flow but you can try this.
set Tag to each button as its Text, like this.
b.setTag("H");
and than after like this.
Button b;
String name = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String s = (String) v.getTag();
name +=s;
if( "HELLO".startsWith(name)){
<VALID>
}else{
<ERROR>
}
}
});
}
check the variable name on each button click with your original word i.e. HELLO like above.
Hi I am developing a app in which alphabets are not fitting for every device. For HCL ME tablet my design won't fit. For samsung it is working. MY XML file is:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="2" android:orientation="vertical">
<LinearLayout android:id="#+id/linearLayout1" android:layout_height="match_parent"
android:orientation="horizontal" android:layout_width="match_parent"
android:layout_weight="1">
<LinearLayout android:id="#+id/linearLayout1" android:layout_height="match_parent"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_weight="1">
<TextView android:id="#+id/letter1" android:gravity="center" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_weight="1"></TextView>
<TextView android:id="#+id/letter2" android:gravity="center" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_margin="10dip"></TextView>
<TextView android:id="#+id/letter3" android:gravity="center" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_margin="10dip"></TextView>
</LinearLayout>
<LinearLayout android:id="#+id/linearLayout1" android:layout_height="match_parent"
android:gravity="center"
android:orientation="horizontal" android:layout_width="match_parent"
android:layout_weight="1">
<ImageView android:id="#+id/imag"
android:gravity="center"
android:scaleType = "fitCenter"
android:layout_height="fill_parent"
android:layout_width="fill_parent"
android:layout_gravity="center">
</ImageView>
</LinearLayout>
</LinearLayout>
<LinearLayout android:layout_gravity="bottom"
android:id="#+id/linearLayout2"
android:layout_height="wrap_content" android:orientation="horizontal" android:layout_width="match_parent">
<Button android:id="#+id/previous" android:layout_width="wrap_content" android:layout_weight="1" android:text="Previous" android:layout_height="wrap_content" ></Button>
<Button android:id="#+id/practice" android:layout_width="wrap_content" android:layout_weight="1" android:text="Practice" android:layout_height="wrap_content" android:onClick="onClick"></Button>
<Button android:id="#+id/home" android:layout_width="wrap_content" android:layout_weight="1" android:text="Home" android:layout_height="wrap_content"></Button>
<Button android:id="#+id/spell" android:layout_width="wrap_content" android:layout_weight="1" android:text="Spell" android:layout_height="wrap_content" android:onClick="Content"></Button>
<Button android:id="#+id/next" android:layout_width="wrap_content" android:layout_weight="1" android:text="Next" android:layout_height="wrap_content" android:onClick="Content"></Button>
</LinearLayout>
</LinearLayout>
and my java file is:
package com.android;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Typeface;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.android.SimpleGestureFilter.SimpleGestureListener;
public class MyAcivity extends Activity implements SimpleGestureListener {
private SimpleGestureFilter detector;
private static int counter=-1;
private String[] mBtn1 ={"C","D","E","F","G","H","IÄ","J","K","L","M","N","O","CA","CB"};
private TextView txtLetter;
private ImageView imgLetter;
private int[] imgArr={R.drawable.w1,R.drawable.w2,R.drawable.w3,R.drawable.w4,R.drawable.w5,R.drawable.w6,R.drawable.w7,R.drawable.w8,R.drawable.w9,R.drawable.w10,R.drawable.w11,R.drawable.w12,
R.drawable.w13,R.drawable.w14,R.drawable.w15};
private TextView txtKannada;
private String[] mBtn2 = {"CgÀ¸À","DªÉÄ","E°","F±À","GqÀ","Hl","IĶ","J¯É","Kr","LzÀÄ","M¯É","N¯É","OµÀzsÀ",
"CAUÀr","CB"};
private String[] mBtn3 = {"ARASA","AME","ILI","ISA","UDA","UTA","RUSHI","ELE","EDI","AIDU","oLE","OLE","AUSHADA",
"ANGADI","AHA"};
private TextView txtEnglish;
private int[] mAudio = {R.raw.a,R.raw.b,R.raw.c,R.raw.d,R.raw.e,R.raw.f,R.raw.g,R.raw.h,R.raw.i,R.raw.j,
R.raw.k,R.raw.l,R.raw.m,R.raw.n,R.raw.o};
protected MediaPlayer mp;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.content);
detector = new SimpleGestureFilter(this,this);
if(counter == -1)
counter =getIntent().getExtras().getInt("POSITION");
Typeface tf = Typeface.createFromAsset(getBaseContext().getAssets(), "fonts/brhknd.ttf");
txtLetter = (TextView)findViewById(R.id.letter1);
txtKannada = (TextView)findViewById(R.id.letter2);
txtEnglish = (TextView)findViewById(R.id.letter3);
imgLetter = (ImageView)findViewById(R.id.imag);
txtLetter.setTypeface(tf);
txtLetter.setText(mBtn1[counter]);
txtLetter.setTextSize(350);
txtKannada.setTypeface(tf);
txtKannada.setText(mBtn2[counter]);
txtKannada.setTextSize(100);
txtEnglish.setText(mBtn3[counter]);
txtEnglish.setTextSize(50);
Button btnNext = (Button)findViewById(R.id.next);
btnNext.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(counter<imgArr.length-1)
counter++;
changeContent();
}
});
Button mPlay = (Button)findViewById(R.id.spell);
mPlay.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
mp = MediaPlayer.create(MySwara.this, mAudio[counter]);
mp.start();
}
});
Button btnPrvs = (Button)findViewById(R.id.previous);
btnPrvs.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(counter>0)
counter--;
changeContent();
}
});
Button btnPractice = (Button)findViewById(R.id.practice);
btnPractice.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MySwara.this,DrawingActivity.class);
startActivity(intent);
}
});
Button btnHome = (Button)findViewById(R.id.home);
btnHome.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MySwara.this,mainClass.class);
startActivity(intent);
}
});
}
public void changeContent()
{
txtLetter.setText(mBtn1[counter]);
txtKannada.setText(mBtn2[counter]);
txtEnglish.setText(mBtn3[counter]);
//imgLetter.setBackgroundResource(imgArr[counter]);
Bitmap bm = BitmapFactory.decodeResource(getResources(), imgArr[counter]);
imgLetter.setImageBitmap(bm);
}
#Override
public boolean dispatchTouchEvent(MotionEvent me){
this.detector.onTouchEvent(me);
return super.dispatchTouchEvent(me);
}
#Override
public void onSwipe(int direction) {
String str = "";
switch (direction) {
case SimpleGestureFilter.SWIPE_RIGHT : str = "Swipe Right";
if(counter>0)
counter--;
changeContent();
break;
case SimpleGestureFilter.SWIPE_LEFT : str = "Swipe Left";
if(counter<imgArr.length-1)
counter++;
changeContent();
break;
}
}
}
How i can fit to all devices. Can anyone help?? Thanks in advance.
There are couple of possibilities:
use different xml files for different sizes of screen -> check here http://developer.android.com/guide/practices/screens_support.html
you may use scrollview -> http://developer.android.com/reference/android/widget/ScrollView.html
or simply make your layout fit to the smallest screen size you like to support and then just have "a little" unused space on the larger screens.
It really depends on what you need. Probably the most compatible and advanced solution would be 1.
BUT be aware of the fact that EVERY change on the screen layout has to be duplicated for each xml file following this route!
create xml for each device separately. follow this
second way:
create a parent LinearLayout and pass it to the following method
public static boolean isTabletPC(Context context) {
Display display = ((WindowManager) context
.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
if (display.getWidth() >= 1200) {
isTabletPC = true;
return isTabletPC;
} else {
isTabletPC = false;
return isTabletPC;
}
}
public static void fixUiDeviceDependencies(
Activity act, LinearLayout llParent) {
if (Utilities.isTabletPC(act)) {
Display display = ((WindowManager) act
.getSystemService(Context.WINDOW_SERVICE))
.getDefaultDisplay();
LayoutParams params = (LayoutParams) llParent
.getLayoutParams();
params.width = display.getWidth() / 2;
llParent.setLayoutParams(params);
}
}